import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs'; import { Dominio } from '../indicadores.models'; import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service'; import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models'; const CONCURRENCY = 3; /** The query that produced a shown answer: its cut-off, window and the filters the server applied. */ export function queryOf(response: SeguimientoTablaResponse): SeguimientoTablaQuery { return { corte: response.corte, meses: response.ventana.meses, page: 1, page_size: PAGE_SIZE_MAX, filtros: Object.fromEntries(Object.entries(response.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])), // A cohort's list is exported as that cohort, at the revision it was read at: another revision is refused by the server. contexto: contextoDe(response), }; } // The server must report having applied the window and the filters that were asked for; otherwise the file would // hold rows of another query under the title of this one. const sameQuery = consultaAplicada; /** * Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer. * Unsubscribing cancels the pending requests. It fails instead of returning a partial or unstable list. */ export function fetchAllTracking(service: SeguimientoTablaService, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable { const ask = (q: SeguimientoTablaQuery) => defer(() => service.consultar(dominio, q)); return ask({ ...query, page: 1, page_size: PAGE_SIZE_MAX }).pipe( switchMap(first => { const { total_items: total, total_pages: pages } = first.paginacion; if (!sameQuery(query, first)) throw new ExportInconsistent('The answer does not apply the query that was asked'); if (total > limit) throw new ExportLimitExceeded(total, limit); // The rest of the pages are asked for exactly what the first one was, with the cut-off it answered. const pinned = { ...query, corte: first.corte, page_size: PAGE_SIZE_MAX }; const collected = new Map([[1, first.items]]); const count = () => [...collected.values()].reduce((sum, rows) => sum + rows.length, 0); const rest = from(Array.from({ length: Math.max(0, pages - 1) }, (_, i) => i + 2)).pipe( mergeMap(page => ask({ ...pinned, page }).pipe(map(answer => ({ page, answer }))), CONCURRENCY), tap(({ page, answer }) => { if (answer.paginacion.page !== page || answer.paginacion.total_items !== total || answer.paginacion.total_pages !== pages || answer.corte !== first.corte || !sameQuery(pinned, answer)) throw new ExportInconsistent('The list changed while it was being read'); collected.set(page, answer.items); }), map((): TrackingExportEvent => ({ kind: 'progress', fetched: count(), total })), ); return rest.pipe( startWith({ kind: 'progress', fetched: first.items.length, total }), concatWith(defer(() => { const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows); const ids = new Set(items.map(item => item['id_seudonimo'])); if (items.length !== total || ids.size !== total) throw new ExportInconsistent('The pages do not add up to the announced total'); return of({ kind: 'done', snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items }, }); })), ); }), ); }