@stamhoofd/backend-statistics-syncer 2.148.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sync.ts ADDED
@@ -0,0 +1,611 @@
1
+ import type { SQLResultNamespacedRow } from '@simonbackx/simple-database';
2
+ import { Group, Member, MemberPlatformMembership, MemberResponsibilityRecord, Organization, Platform, Registration, RegistrationPeriod } from '@stamhoofd/models';
3
+ import { SQL, SQLSelect, SQLWhereSign } from '@stamhoofd/sql';
4
+ import { getStatisticsConnection } from './database.js';
5
+ import { applyImportedCutoff, getImportedUntil, isFrozen, loadFrozenPeriodIds, loadSettledPeriodIds, releaseUnlockedPeriods, settleLockedPeriods } from './periods.js';
6
+ import type { StatisticsRow } from './rows.js';
7
+ import { flattenDefaultAgeGroup, flattenGroup, flattenMember, flattenMembership, flattenNamedConfig, flattenOrganization, flattenPlatform, flattenRegistration, flattenRegistrationPeriod, flattenResponsibilityRecord } from './rows.js';
8
+ import { syncSource } from './sources.js';
9
+ import { nextWatermark, readSyncState, writeSyncState } from './sync-state.js';
10
+ import { deleteRows, iterateIds, upsertRows } from './writer.js';
11
+
12
+ /**
13
+ * How far before the watermark a run starts reading again. A row that was written while the previous
14
+ * run was reading may carry an `updatedAt` below the watermark that run ended on, so re-reading a
15
+ * window costs a few redundant upserts and closes that gap.
16
+ */
17
+ export const watermarkOverlap = 5 * 60 * 1000;
18
+
19
+ /** Source rows read per query. */
20
+ export const fetchBatchSize = 500;
21
+
22
+ type IncrementalTable = {
23
+ table: string;
24
+ columns: string[];
25
+ /**
26
+ * Source rows updated at or after `since` with an id after `afterId`, ordered by id. Paging on
27
+ * the id alone is what makes the cursor strictly advance; rows that move into the window while a
28
+ * run is going are picked up by the next one through the overlap.
29
+ */
30
+ fetch: (since: Date | null, afterId: string, limit: number) => Promise<{ rows: StatisticsRow[]; updatedAt: Date[]; lastId: string }>;
31
+ /** Which of these ids still exist in the source, used to reconcile deletes. */
32
+ existingIds: (ids: string[]) => Promise<Set<string>>;
33
+ /**
34
+ * The column holding the period a row belongs to. Rows of a frozen period are neither rewritten
35
+ * nor excluded, which is what keeps a settled year settled. Absent for tables that are not tied
36
+ * to a period at all.
37
+ */
38
+ periodColumn?: string;
39
+ /**
40
+ * What identifies a row, when it takes more than an id. A table keyed on more than its id can
41
+ * hold several rows per id, which the delete reconciliation has no way to tell apart -- so it
42
+ * has to be `neverDelete` as well.
43
+ */
44
+ keyColumns?: string[];
45
+ /**
46
+ * Rows that stay even when their source row is gone. Members and organizations are what the facts
47
+ * of a settled year join to for their demographics, and without one every registration it carried
48
+ * drops out of that year — an organization takes its registrations with it outright, through the
49
+ * cascade. Keeping a de-identified row of a birth year and a gender costs nothing next to losing
50
+ * those numbers.
51
+ */
52
+ neverDelete?: boolean;
53
+ };
54
+
55
+ /**
56
+ * Marks which pipeline wrote a row, so the reconciliation only ever checks its own against the main
57
+ * database and leaves imported rows alone.
58
+ */
59
+ export const sourceColumns = ['source'];
60
+
61
+ function withSource(rows: StatisticsRow[]): StatisticsRow[] {
62
+ return rows.map(row => ({ ...row, source: syncSource }));
63
+ }
64
+
65
+ function idsOf(rows: { id: string }[]): string[] {
66
+ return rows.map(row => row.id);
67
+ }
68
+
69
+ function groupByPeriod(organizations: Organization[]): Map<string, Organization[]> {
70
+ const grouped = new Map<string, Organization[]>();
71
+
72
+ for (const organization of organizations) {
73
+ const group = grouped.get(organization.periodId);
74
+ if (group) {
75
+ group.push(organization);
76
+ } else {
77
+ grouped.set(organization.periodId, [organization]);
78
+ }
79
+ }
80
+
81
+ return grouped;
82
+ }
83
+
84
+ async function existingModelIds(model: { select: () => any }, ids: string[]): Promise<Set<string>> {
85
+ const rows = await model.select().where(SQL.column('id'), ids).fetch();
86
+ return new Set(idsOf(rows as { id: string }[]));
87
+ }
88
+
89
+ /**
90
+ * The periods each of these members or units holds a registration in.
91
+ *
92
+ * Both are recorded per year, and the source has no such row: a member is simply a member there and
93
+ * a unit simply a unit, and it is the registrations that place them in a year.
94
+ *
95
+ * Limited to the periods the statistics database already holds. A registration can point at a period
96
+ * that has not been synced yet, and a row for it would be refused by the foreign key, which would
97
+ * stall the whole table over one row.
98
+ */
99
+ async function periodIdsByRegistration(column: 'memberId' | 'organizationId', ids: string[]): Promise<Map<string, Set<string>>> {
100
+ const byId = new Map<string, Set<string>>();
101
+ if (ids.length === 0) {
102
+ return byId;
103
+ }
104
+
105
+ const rows = await new SQLSelect(
106
+ (row: SQLResultNamespacedRow) => ({
107
+ key: row[Registration.table][column] as string,
108
+ periodId: row[Registration.table].periodId as string | null,
109
+ }),
110
+ SQL.column(column),
111
+ SQL.column('periodId'),
112
+ )
113
+ .from(Registration.table)
114
+ .where(SQL.column(column), ids)
115
+ .fetch();
116
+
117
+ const known = await existingPeriodIds(rows.map(row => row.periodId).filter((id): id is string => id !== null));
118
+
119
+ for (const row of rows) {
120
+ if (row.periodId !== null && known.has(row.periodId)) {
121
+ addTo(byId, row.key, row.periodId);
122
+ }
123
+ }
124
+
125
+ return byId;
126
+ }
127
+
128
+ function periodIdsByMember(memberIds: string[]): Promise<Map<string, Set<string>>> {
129
+ return periodIdsByRegistration('memberId', memberIds);
130
+ }
131
+
132
+ /**
133
+ * Which of these members are charged the platform's verlaagd lidgeld: those with financiële
134
+ * ondersteuning or an active UITPAS.
135
+ *
136
+ * That status is the input the price of a lidgeld is calculated from, and the only record of which
137
+ * tarief was charged -- the membership itself keeps the amount and not what it was made of. Read off
138
+ * the member here so a lidgeld row can carry it, which is the grain the reports split on.
139
+ *
140
+ * It answers what is true of the member now, like their gender and postal code, and lands in the
141
+ * years still open only: a settled year keeps the tarief it was counted with.
142
+ */
143
+ async function reducedPriceByMember(memberIds: string[]): Promise<Set<string>> {
144
+ const unique = [...new Set(memberIds)];
145
+ if (unique.length === 0) {
146
+ return new Set();
147
+ }
148
+
149
+ const members = await Member.select().where(SQL.column('id'), unique).fetch() as Member[];
150
+ return new Set(members.filter(member => member.details.shouldApplyReducedPrice).map(member => member.id));
151
+ }
152
+
153
+ /**
154
+ * A unit also gets a row for the period it is in now, before anyone has registered in it: its netwerk
155
+ * is recorded against that period, and a netwerk link to a unit that has no row yet is a link to
156
+ * nothing.
157
+ */
158
+ async function periodIdsByOrganization(organizations: Organization[]): Promise<Map<string, Set<string>>> {
159
+ const byOrganization = await periodIdsByRegistration('organizationId', idsOf(organizations));
160
+ const known = await existingPeriodIds(organizations.map(organization => organization.periodId));
161
+
162
+ for (const organization of organizations) {
163
+ if (known.has(organization.periodId)) {
164
+ addTo(byOrganization, organization.id, organization.periodId);
165
+ }
166
+ }
167
+
168
+ return byOrganization;
169
+ }
170
+
171
+ function addTo(map: Map<string, Set<string>>, key: string, value: string): void {
172
+ const values = map.get(key);
173
+ if (values) {
174
+ values.add(value);
175
+ } else {
176
+ map.set(key, new Set([value]));
177
+ }
178
+ }
179
+
180
+ async function existingPeriodIds(ids: string[]): Promise<Set<string>> {
181
+ const unique = [...new Set(ids)];
182
+ if (unique.length === 0) {
183
+ return new Set();
184
+ }
185
+
186
+ const connection = getStatisticsConnection();
187
+ const [rows] = await connection.select('SELECT `id` FROM `registration_periods` WHERE `id` IN (?)', [unique], { nestTables: false });
188
+ return new Set((rows as unknown as { id: string }[]).map(row => row.id));
189
+ }
190
+
191
+ function incrementalQuery(model: { select: () => any }, since: Date | null, afterId: string, limit: number) {
192
+ const query = model.select().where(SQL.column('id'), SQLWhereSign.Greater, afterId);
193
+ if (since) {
194
+ query.where(SQL.column('updatedAt'), SQLWhereSign.GreaterEqual, since);
195
+ }
196
+ return query.orderBy(SQL.column('id'), 'ASC').limit(limit);
197
+ }
198
+
199
+ /**
200
+ * The dimension ids the statistics database currently knows, across every period it holds them for.
201
+ * Rows referring to anything else are dropped or nulled before writing: platform configuration can
202
+ * lose an age group or a membership type while rows still point at it, and the reports would
203
+ * otherwise group by a name that is no longer there.
204
+ */
205
+ async function loadIdSet(table: string): Promise<Set<string>> {
206
+ const connection = getStatisticsConnection();
207
+ const [rows] = await connection.select(`SELECT DISTINCT \`id\` FROM ${connection.escapeId(table)}`, [], { nestTables: false });
208
+ return new Set((rows as unknown as { id: string }[]).map(row => row.id));
209
+ }
210
+
211
+ /**
212
+ * The periods, which every other table here is keyed by and therefore has to be synced before any of
213
+ * them: which periods exist, and which of them are still open, decides what the rest of a run writes
214
+ * at all.
215
+ */
216
+ function periodsTable(): IncrementalTable {
217
+ return {
218
+ table: 'registration_periods',
219
+ columns: ['id', 'startDate', 'endDate', 'locked', 'organizationId', 'previousPeriodId', 'nextPeriodId', 'customName', 'name', 'createdAt', 'updatedAt'],
220
+ fetch: async (since, afterId, limit) => {
221
+ const periods = await incrementalQuery(RegistrationPeriod, since, afterId, limit).fetch() as RegistrationPeriod[];
222
+ return { rows: periods.map(flattenRegistrationPeriod), updatedAt: periods.map(period => period.updatedAt), lastId: periods.at(-1)?.id ?? afterId };
223
+ },
224
+ existingIds: ids => existingModelIds(RegistrationPeriod, ids),
225
+ periodColumn: 'id',
226
+ // A period is what every historical figure hangs off, and everything else points at it with
227
+ // ON DELETE RESTRICT. Removing one would either be refused by the database or take a settled
228
+ // year's numbers with it, so a period that disappears from the administration stays here,
229
+ // like its members and organizations.
230
+ neverDelete: true,
231
+ };
232
+ }
233
+
234
+ function buildIncrementalTables(known: { ageGroups: Set<string>; membershipTypes: Set<string>; responsibilities: Set<string> }, frozen: Set<string>, openPeriodIds: string[]): IncrementalTable[] {
235
+ return [
236
+ {
237
+ table: 'organizations',
238
+ columns: ['id', 'periodId', 'name', 'uri', 'postalCode', 'city', 'active', 'createdAt', 'updatedAt'],
239
+ fetch: async (since, afterId, limit) => {
240
+ const organizations = await incrementalQuery(Organization, since, afterId, limit).fetch() as Organization[];
241
+ await syncOrganizationTagsAndResponsibilities(organizations, frozen, openPeriodIds);
242
+ const periodIds = await periodIdsByOrganization(organizations);
243
+ const rows = organizations.flatMap(organization => [...periodIds.get(organization.id) ?? []].map(periodId => flattenOrganization(organization, periodId)));
244
+ return { rows, updatedAt: organizations.map(organization => organization.updatedAt), lastId: organizations.at(-1)?.id ?? afterId };
245
+ },
246
+ existingIds: ids => existingModelIds(Organization, ids),
247
+ periodColumn: 'periodId',
248
+ keyColumns: ['id', 'periodId'],
249
+ neverDelete: true,
250
+ },
251
+ {
252
+ table: 'groups',
253
+ columns: ['id', 'type', 'name', 'organizationId', 'periodId', 'defaultAgeGroupId', 'status', 'deletedAt', 'createdAt', 'updatedAt'],
254
+ fetch: async (since, afterId, limit) => {
255
+ const groups = await incrementalQuery(Group, since, afterId, limit).fetch() as Group[];
256
+ const rows = groups.map((group) => {
257
+ const row = flattenGroup(group);
258
+ if (typeof row.defaultAgeGroupId === 'string' && !known.ageGroups.has(row.defaultAgeGroupId)) {
259
+ row.defaultAgeGroupId = null;
260
+ }
261
+ return row;
262
+ });
263
+ return { rows, updatedAt: groups.map(group => group.updatedAt), lastId: groups.at(-1)?.id ?? afterId };
264
+ },
265
+ existingIds: ids => existingModelIds(Group, ids),
266
+ periodColumn: 'periodId',
267
+ },
268
+ {
269
+ table: 'members',
270
+ columns: ['id', 'periodId', 'birthDate', 'gender', 'postalCode', 'organizationId', 'createdAt', 'updatedAt', 'lastRegisteredAt'],
271
+ fetch: async (since, afterId, limit) => {
272
+ const members = await incrementalQuery(Member, since, afterId, limit).fetch() as Member[];
273
+ const periodIds = await periodIdsByMember(members.map(member => member.id));
274
+ const rows = members.flatMap(member => [...periodIds.get(member.id) ?? []].map(periodId => flattenMember(member, periodId)));
275
+ return { rows, updatedAt: members.map(member => member.updatedAt), lastId: members.at(-1)?.id ?? afterId };
276
+ },
277
+ existingIds: ids => existingModelIds(Member, ids),
278
+ periodColumn: 'periodId',
279
+ keyColumns: ['id', 'periodId'],
280
+ neverDelete: true,
281
+ },
282
+ {
283
+ table: 'registrations',
284
+ columns: ['id', 'organizationId', 'memberId', 'groupId', 'periodId', 'registeredAt', 'startDate', 'endDate', 'trialUntil', 'deactivatedAt', 'createdAt', 'updatedAt'],
285
+ fetch: async (since, afterId, limit) => {
286
+ const registrations = await incrementalQuery(Registration, since, afterId, limit).fetch() as Registration[];
287
+ return { rows: registrations.map(flattenRegistration), updatedAt: registrations.map(registration => registration.updatedAt), lastId: registrations.at(-1)?.id ?? afterId };
288
+ },
289
+ existingIds: ids => existingModelIds(Registration, ids),
290
+ periodColumn: 'periodId',
291
+ },
292
+ {
293
+ table: 'member_platform_memberships',
294
+ columns: ['id', 'memberId', 'membershipTypeId', 'reducedPrice', 'organizationId', 'periodId', 'startDate', 'endDate', 'expireDate', 'trialUntil', 'deletedAt', 'createdAt', 'updatedAt'],
295
+ fetch: async (since, afterId, limit) => {
296
+ const memberships = await incrementalQuery(MemberPlatformMembership, since, afterId, limit).fetch() as MemberPlatformMembership[];
297
+ const kept = memberships.filter(membership => known.membershipTypes.has(membership.membershipTypeId));
298
+ const reduced = await reducedPriceByMember(kept.map(membership => membership.memberId));
299
+ const rows = kept.map(membership => flattenMembership(membership, reduced.has(membership.memberId)));
300
+ return { rows, updatedAt: kept.map(membership => membership.updatedAt), lastId: memberships.at(-1)?.id ?? afterId };
301
+ },
302
+ existingIds: ids => existingModelIds(MemberPlatformMembership, ids),
303
+ periodColumn: 'periodId',
304
+ },
305
+ ];
306
+ }
307
+
308
+ /**
309
+ * Copy the platform record and the configuration that lives in json on it into the dimension tables.
310
+ * Small enough to write on every run, and it has to happen before the tables pointing at it.
311
+ *
312
+ * The configuration holds one answer -- the name a tak, netwerk, lidgeldtype or functie carries
313
+ * today -- and no history at all, so that answer is written against every period still open. The
314
+ * frozen ones keep the answer they were counted with.
315
+ */
316
+ async function syncPlatformConfig(openPeriodIds: string[]): Promise<void> {
317
+ const platform = await Platform.getShared();
318
+ const config = platform.config;
319
+
320
+ const perPeriod = <T>(items: T[], flatten: (item: T, periodId: string) => StatisticsRow) =>
321
+ openPeriodIds.flatMap(periodId => items.map(item => flatten(item, periodId)));
322
+
323
+ // The platform record itself rather than its configuration, and therefore not per period: the
324
+ // reports read which organization it runs and what it calls its verlaagd lidgeld, and what they
325
+ // print of that organization comes from `organizations`, which is recorded per year like
326
+ // everything else.
327
+ await upsertRows('platform', ['id', 'name', 'membershipOrganizationId', 'reducedPriceName'], [flattenPlatform(platform)], ['id']);
328
+
329
+ await upsertRows('organization_tags', ['id', 'periodId', 'name'], perPeriod(config.tags, flattenNamedConfig), namedConfigKey);
330
+
331
+ await upsertRows('default_age_groups', ['id', 'periodId', 'name', 'minAge', 'maxAge'], perPeriod(config.defaultAgeGroups, (group, periodId) => flattenDefaultAgeGroup({ id: group.id, names: group.names, minAge: group.minAge, maxAge: group.maxAge }, periodId)), namedConfigKey);
332
+ await upsertRows('platform_membership_types', ['id', 'periodId', 'name'], perPeriod(config.membershipTypes, flattenNamedConfig), namedConfigKey);
333
+ await upsertRows('responsibilities', ['id', 'periodId', 'name'], perPeriod(config.responsibilities, flattenNamedConfig), namedConfigKey);
334
+ }
335
+
336
+ /** The periods the sync still writes into: everything the statistics database knows, minus the frozen ones. */
337
+ async function loadOpenPeriodIds(frozen: Set<string>): Promise<string[]> {
338
+ return [...await loadIdSet('registration_periods')].filter(id => !frozen.has(id));
339
+ }
340
+
341
+ const namedConfigKey = ['id', 'periodId'];
342
+
343
+ /**
344
+ * The tags an organization carries and the responsibilities it defines itself. Both hang off the
345
+ * organization record, so they are written along with the batch of organizations they belong to
346
+ * rather than by scanning every organization again.
347
+ */
348
+ async function syncOrganizationTagsAndResponsibilities(organizations: Organization[], frozen: Set<string>, openPeriodIds: string[]): Promise<void> {
349
+ if (organizations.length === 0) {
350
+ return;
351
+ }
352
+
353
+ const ownResponsibilities = organizations.flatMap(organization => organization.privateMeta.responsibilities);
354
+ await upsertRows('responsibilities', ['id', 'periodId', 'name'], openPeriodIds.flatMap(periodId => ownResponsibilities.map(responsibility => flattenNamedConfig(responsibility, periodId))), namedConfigKey);
355
+
356
+ // The source only knows the tags an organization carries now, so they are recorded against the
357
+ // period it is in. A frozen period keeps the netwerk it was recorded with while it was live.
358
+ const knownPeriods = await loadIdSet('registration_periods');
359
+ const live = organizations.filter(organization => knownPeriods.has(organization.periodId) && !isFrozen(frozen, organization.periodId));
360
+ if (live.length === 0) {
361
+ return;
362
+ }
363
+
364
+ const knownTags = await loadIdSet('organization_tags');
365
+ const connection = getStatisticsConnection();
366
+
367
+ // Replace the links of these organizations for the period they are in, leaving every other
368
+ // period exactly as it was recorded.
369
+ for (const [periodId, group] of groupByPeriod(live)) {
370
+ await connection.delete(
371
+ `DELETE FROM ${connection.escapeId('_organizations_organization_tags')} WHERE \`organizationsId\` IN (?) AND \`periodId\` = ?`,
372
+ [idsOf(group), periodId],
373
+ );
374
+ }
375
+
376
+ const links = live.flatMap(organization => organization.meta.tags
377
+ .filter(tagId => knownTags.has(tagId))
378
+ .map(tagId => ({ organizationsId: organization.id, organizationTagsId: tagId, periodId: organization.periodId })));
379
+ await upsertRows('_organizations_organization_tags', ['organizationsId', 'organizationTagsId', 'periodId', ...sourceColumns], withSource(links));
380
+ }
381
+
382
+ type PeriodRange = { id: string; organizationId: string | null; startDate: Date; endDate: Date };
383
+
384
+ /**
385
+ * The years the sync still writes into, grouped by the unit holding them. Every unit keeps its own
386
+ * row per year; the platform's own years are the ones under no unit at all.
387
+ */
388
+ async function loadOpenPeriodsByOrganization(frozen: Set<string>): Promise<Map<string | null, PeriodRange[]>> {
389
+ const connection = getStatisticsConnection();
390
+ const [rows] = await connection.select(
391
+ 'SELECT `id`, `organizationId`, `startDate`, `endDate` FROM `registration_periods`',
392
+ [],
393
+ { nestTables: false },
394
+ );
395
+
396
+ const byOrganization = new Map<string | null, PeriodRange[]>();
397
+ for (const period of rows as unknown as PeriodRange[]) {
398
+ if (frozen.has(period.id)) {
399
+ continue;
400
+ }
401
+
402
+ const periods = byOrganization.get(period.organizationId);
403
+ if (periods) {
404
+ periods.push(period);
405
+ } else {
406
+ byOrganization.set(period.organizationId, [period]);
407
+ }
408
+ }
409
+
410
+ return byOrganization;
411
+ }
412
+
413
+ /**
414
+ * The years a record runs through: the ones of its own unit that its date range overlaps, or the
415
+ * platform's own when it belongs to no unit.
416
+ *
417
+ * A record with no end date runs until now rather than forever, so a functie someone still holds is
418
+ * not also recorded against the years that have not happened yet.
419
+ */
420
+ function periodIdsOfRecord(record: MemberResponsibilityRecord, byOrganization: Map<string | null, PeriodRange[]>, now: Date): string[] {
421
+ const periods = byOrganization.get(record.organizationId) ?? byOrganization.get(null) ?? [];
422
+ const runsUntil = record.endDate !== null && record.endDate < now ? record.endDate : now;
423
+
424
+ return periods
425
+ .filter(period => period.startDate <= runsUntil && period.endDate >= record.startDate)
426
+ .map(period => period.id);
427
+ }
428
+
429
+ /**
430
+ * Responsibility records carry no `updatedAt`, so there is no watermark to advance: they are written
431
+ * in full on every run. Records pointing at a responsibility that no longer exists are skipped.
432
+ */
433
+ async function syncResponsibilityRecords(knownResponsibilities: Set<string>, frozen: Set<string>): Promise<void> {
434
+ const columns = ['id', 'periodId', 'memberId', 'groupId', 'organizationId', 'responsibilityId', 'startDate', 'endDate'];
435
+ const byOrganization = await loadOpenPeriodsByOrganization(frozen);
436
+ const connection = getStatisticsConnection();
437
+ const now = new Date();
438
+ let afterId = '';
439
+
440
+ for (;;) {
441
+ const records = await MemberResponsibilityRecord.select()
442
+ .where(SQL.column('id'), SQLWhereSign.Greater, afterId)
443
+ .orderBy(SQL.column('id'), 'ASC')
444
+ .limit(fetchBatchSize)
445
+ .fetch() as MemberResponsibilityRecord[];
446
+
447
+ if (records.length === 0) {
448
+ return;
449
+ }
450
+
451
+ // Which years a record runs through follows from its dates, so a record whose dates changed
452
+ // has to lose the years it no longer covers. Only outside the frozen ones: those are settled.
453
+ const ids = idsOf(records);
454
+ if (frozen.size > 0) {
455
+ await connection.delete('DELETE FROM `member_responsibility_records` WHERE `id` IN (?) AND `periodId` NOT IN (?)', [ids, [...frozen]]);
456
+ } else {
457
+ await connection.delete('DELETE FROM `member_responsibility_records` WHERE `id` IN (?)', [ids]);
458
+ }
459
+
460
+ await upsertRows('member_responsibility_records', [...columns, ...sourceColumns], withSource(records
461
+ .filter(record => knownResponsibilities.has(record.responsibilityId))
462
+ .flatMap(record => periodIdsOfRecord(record, byOrganization, now).map(periodId => flattenResponsibilityRecord(record, periodId)))), ['id', 'periodId']);
463
+ afterId = records[records.length - 1].id;
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Of these statistics rows, the ones that do not belong to a frozen period. A deleted source row in a
469
+ * settled year stays exactly as it was counted.
470
+ */
471
+ async function withoutFrozen(table: string, ids: string[], frozen: Set<string>, periodColumn: string): Promise<string[]> {
472
+ if (ids.length === 0 || frozen.size === 0) {
473
+ return ids;
474
+ }
475
+
476
+ const connection = getStatisticsConnection();
477
+ const column = connection.escapeId(periodColumn);
478
+ const [rows] = await connection.select(
479
+ `SELECT \`id\` FROM ${connection.escapeId(table)} WHERE \`id\` IN (?) AND (${column} IS NULL OR ${column} NOT IN (?))`,
480
+ [ids, [...frozen]],
481
+ { nestTables: false },
482
+ );
483
+ return (rows as unknown as { id: string }[]).map(row => row.id);
484
+ }
485
+
486
+ async function syncIncrementalTable(definition: IncrementalTable, frozen: Set<string>): Promise<void> {
487
+ const startedAt = new Date();
488
+ const state = await readSyncState(definition.table);
489
+ const since = state.watermark ? new Date(state.watermark.getTime() - watermarkOverlap) : null;
490
+ const seen: Date[] = [];
491
+ let afterId = '';
492
+
493
+ for (;;) {
494
+ const { rows, updatedAt, lastId } = await definition.fetch(since, afterId, fetchBatchSize);
495
+ if (lastId === afterId) {
496
+ break;
497
+ }
498
+
499
+ const live = definition.periodColumn
500
+ ? rows.filter(row => !isFrozen(frozen, row[definition.periodColumn!] as string | null))
501
+ : rows;
502
+ await upsertRows(definition.table, [...definition.columns, ...sourceColumns], withSource(live), definition.keyColumns);
503
+ seen.push(...updatedAt);
504
+ afterId = lastId;
505
+ }
506
+
507
+ await writeSyncState(definition.table, {
508
+ watermark: nextWatermark(state.watermark, seen, startedAt),
509
+ lastSucceededAt: new Date(),
510
+ });
511
+ }
512
+
513
+ function emptyKnownIds() {
514
+ return { ageGroups: new Set<string>(), membershipTypes: new Set<string>(), responsibilities: new Set<string>() };
515
+ }
516
+
517
+ /** The tables the delete reconciliation walks, which is every table it may take a row out of. */
518
+ export function reconciledTables(): string[] {
519
+ return [periodsTable(), ...buildIncrementalTables(emptyKnownIds(), new Set(), [])]
520
+ .filter(definition => !definition.neverDelete)
521
+ .map(definition => definition.table);
522
+ }
523
+
524
+ /**
525
+ * Bring the statistics database up to date with everything that changed since the last run.
526
+ *
527
+ * Written so a crash is harmless: every write is an upsert, and a table that throws keeps its old
528
+ * watermark, so the next run reads the same window again instead of skipping it.
529
+ */
530
+ export async function syncStatistics(): Promise<void> {
531
+ await applyImportedCutoff(getImportedUntil());
532
+
533
+ // The periods before anything else, and the configuration before the rows that group by it: every
534
+ // table here is written per period, so a period that is not in yet is a period nothing can be
535
+ // written against.
536
+ //
537
+ // Only a settled year leaves its own row alone as well. A locked period keeps following the
538
+ // administration, because that row is where `locked` arrives: freezing it would freeze the one
539
+ // field an unlock has to come through.
540
+ await syncIncrementalTable(periodsTable(), await loadSettledPeriodIds());
541
+
542
+ // Also apply the cutoff for newly added rows
543
+ await applyImportedCutoff(getImportedUntil());
544
+
545
+ await releaseUnlockedPeriods();
546
+
547
+ const frozen = await loadFrozenPeriodIds();
548
+ const openPeriodIds = await loadOpenPeriodIds(frozen);
549
+ await syncPlatformConfig(openPeriodIds);
550
+
551
+ const known = {
552
+ ageGroups: await loadIdSet('default_age_groups'),
553
+ membershipTypes: await loadIdSet('platform_membership_types'),
554
+ responsibilities: await loadIdSet('responsibilities'),
555
+ };
556
+
557
+ for (const definition of buildIncrementalTables(known, frozen, openPeriodIds)) {
558
+ await syncIncrementalTable(definition, frozen);
559
+ }
560
+
561
+ await syncResponsibilityRecords(await loadIdSet('responsibilities'), frozen);
562
+ }
563
+
564
+ /**
565
+ * Remove statistics rows whose source row is gone. Deletes leave nothing behind to notice in an
566
+ * incremental pass, so they are reconciled separately by walking the statistics ids and asking the
567
+ * source which of them still exist.
568
+ */
569
+ export async function syncStatisticsDeletes(): Promise<void> {
570
+ const frozen = await loadFrozenPeriodIds();
571
+
572
+ for (const definition of [periodsTable(), ...buildIncrementalTables(emptyKnownIds(), frozen, [])]) {
573
+ if (definition.neverDelete) {
574
+ continue;
575
+ }
576
+
577
+ for await (const ids of iterateIds(definition.table, syncSource)) {
578
+ const existing = await definition.existingIds(ids);
579
+ const missing = ids.filter(id => !existing.has(id));
580
+ await deleteRows(definition.table, definition.periodColumn ? await withoutFrozen(definition.table, missing, frozen, definition.periodColumn) : missing);
581
+ }
582
+ await writeSyncState(definition.table, { lastReconciledAt: new Date() });
583
+ }
584
+
585
+ for await (const ids of iterateIds('member_responsibility_records', syncSource)) {
586
+ const existing = await existingModelIds(MemberResponsibilityRecord, ids);
587
+ await deleteRows('member_responsibility_records', ids.filter(id => !existing.has(id)));
588
+ }
589
+ await writeSyncState('member_responsibility_records', { lastReconciledAt: new Date() });
590
+ }
591
+
592
+ /**
593
+ * One whole run of the sync: everything that changed, then the rows whose source is gone, then the
594
+ * periods the administration has locked since.
595
+ *
596
+ * The order is what makes each of the three sound, so they are run from here rather than from the
597
+ * cron that schedules them.
598
+ */
599
+ export async function runStatisticsCycle(): Promise<void> {
600
+ await syncStatistics();
601
+
602
+ // After the incremental pass, never next to it: reconciling first would see a row the sync is
603
+ // about to write back and one that was deleted since the sync read it as equally present,
604
+ // leaving the deleted one behind for a full day.
605
+ await syncStatisticsDeletes();
606
+
607
+ // Last, and only when both passes came through: a locked period has had the changes and the
608
+ // deletions of the day it was locked written by now, so its numbers are final. A pass that threw
609
+ // never gets here, which leaves the period to be read again by the next run.
610
+ await settleLockedPeriods();
611
+ }