@peopl-health/nexus 5.74.0-dev.15347 → 5.74.0-dev.15348

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.
@@ -90,6 +90,17 @@ const WHATSAPP_FIELDS = Object.freeze({
90
90
  [TABLE.SYMPTOMS]: FIELD.SYMPTOM.WHATSAPP,
91
91
  });
92
92
 
93
+ const QUESTIONNAIRE_ANCHOR_FIELDS = [FIELD.QUESTIONNAIRE.CREATED, FIELD.QUESTIONNAIRE.APPROVED];
94
+
95
+ const plannerFieldsOf = (tableId) => [...new Set([
96
+ ...[GROUP_LINKS, CARRY_OVER_LINKS, BACKWARD_LINKS, EXTERNAL_LINKS].flatMap((links) => links[tableId] || []),
97
+ PATIENT_FIELDS[tableId], WHATSAPP_FIELDS[tableId],
98
+ ...(tableId === TABLE.QUESTIONNAIRES ? QUESTIONNAIRE_ANCHOR_FIELDS : []),
99
+ ].filter(Boolean))];
100
+
101
+ // The only fields the planner reads, so the scan of every old record stays small.
102
+ const PLANNER_FIELDS = Object.freeze(Object.fromEntries(Object.values(TABLE).map((tableId) => [tableId, Object.freeze(plannerFieldsOf(tableId))])));
103
+
93
104
  const LINK_FIELD_TYPES = Object.freeze(['multipleRecordLinks']);
94
105
  const CHECKBOX_FIELD_TYPES = Object.freeze(['checkbox']);
95
106
  const DATE_FIELD_TYPES = Object.freeze(['dateTime', 'date']);
@@ -134,6 +145,7 @@ module.exports = {
134
145
  BACKWARD_LINKS,
135
146
  EXTERNAL_LINKS,
136
147
  PATIENT_FIELDS,
148
+ PLANNER_FIELDS,
137
149
  WHATSAPP_FIELDS,
138
150
  LINK_FIELD_TYPES,
139
151
  CHECKBOX_FIELD_TYPES,
@@ -1,7 +1,7 @@
1
1
  const crypto = require('crypto');
2
2
 
3
3
  const {
4
- ARCHIVE_TABLES, ARCHIVE_FIELDS, GROUP_LINKS, CARRY_OVER_LINKS, BACKWARD_LINKS, EXTERNAL_LINKS, PATIENT_FIELDS, WHATSAPP_FIELDS,
4
+ ARCHIVE_TABLES, ARCHIVE_FIELDS, GROUP_LINKS, CARRY_OVER_LINKS, BACKWARD_LINKS, EXTERNAL_LINKS, PATIENT_FIELDS, PLANNER_FIELDS, WHATSAPP_FIELDS,
5
5
  COMPUTED_FIELD_TYPES, LINK_FIELD_TYPES, CHECKBOX_FIELD_TYPES, DATE_FIELD_TYPES, FIRST_MONTH_DAYS, KEEP_REASONS,
6
6
  } = require('../config/airtableArchiveConfig');
7
7
 
@@ -81,6 +81,7 @@ function resolveArchiveSchema(baseTables = []) {
81
81
  externalLinks: byTableName(EXTERNAL_LINKS, LINK_FIELD_TYPES),
82
82
  patientFields: byTableName(PATIENT_FIELDS, LINK_FIELD_TYPES),
83
83
  whatsappFields: byTableName(WHATSAPP_FIELDS),
84
+ plannerFields: byTableName(PLANNER_FIELDS),
84
85
  questionnaireTriage: fieldName(ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_FIELDS.QUESTIONNAIRE.TRIAGE, LINK_FIELD_TYPES),
85
86
  questionnaireApproved: fieldName(ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_FIELDS.QUESTIONNAIRE.APPROVED, CHECKBOX_FIELD_TYPES),
86
87
  questionnaireCreated: fieldName(ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_FIELDS.QUESTIONNAIRE.CREATED, DATE_FIELD_TYPES),
@@ -4,7 +4,7 @@ const { v4: uuidv4 } = require('uuid');
4
4
  const runtimeConfig = require('../config/runtimeConfig');
5
5
  const { uploadBufferToS3 } = require('../config/awsConfig');
6
6
  const {
7
- ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ARCHIVE_LEASE_RENEW_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS, PATIENT_FIELDS,
7
+ ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ARCHIVE_LEASE_RENEW_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS, PATIENT_FIELDS, PLANNER_FIELDS,
8
8
  } = require('../config/airtableArchiveConfig');
9
9
  const { logger } = require('../utils/logger');
10
10
  const { stableStringify } = require('../utils/jsonUtils');
@@ -12,7 +12,7 @@ const { daysSince } = require('../utils/dateUtils');
12
12
  const {
13
13
  ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRecord, getAirtableArchiveRun, getAirtableArchiveSchema, archiveRecordId,
14
14
  } = require('../models/airtableArchiveModel');
15
- const { createdBefore, createdSince } = require('../helpers/airtableFormulaHelper');
15
+ const { createdBefore, createdSince, recordIdIn } = require('../helpers/airtableFormulaHelper');
16
16
  const { normalizeFields, hashFields, schemaSnapshotId } = require('../helpers/airtableArchiveHelper');
17
17
 
18
18
  const { scanRecordPages, getBaseSchema } = require('./airtableService');
@@ -78,7 +78,7 @@ async function scanTable({ baseId, tableId, filterByFormula, fieldIds, schema, l
78
78
  async function scanOldRecords(baseId, cutoff, schema, lease) {
79
79
  const recordsByTable = {};
80
80
  for (const [key, tableId] of Object.entries(ARCHIVE_TABLES)) {
81
- recordsByTable[schema.tables[key]] = await scanTable({ baseId, tableId, filterByFormula: createdBefore(cutoff), schema, lease });
81
+ recordsByTable[schema.tables[key]] = await scanTable({ baseId, tableId, filterByFormula: createdBefore(cutoff), fieldIds: PLANNER_FIELDS[tableId], schema, lease });
82
82
  }
83
83
  return recordsByTable;
84
84
  }
@@ -200,18 +200,50 @@ async function writeOps(ArchiveRecord, ops, runId) {
200
200
  }
201
201
  }
202
202
 
203
+ // Re-reads the batch whole, so copies carry every field and fresh attachment URLs.
204
+ async function readWholeRecords(baseId, batch, schema, lease) {
205
+ const wholeById = new Map();
206
+ const idsByTable = new Map();
207
+ for (const { table, record } of batch) {
208
+ if (!idsByTable.has(table)) idsByTable.set(table, []);
209
+ idsByTable.get(table).push(record.id);
210
+ }
211
+ for (const [table, ids] of idsByTable) {
212
+ const records = await scanTable({ baseId, tableId: schema.tableIds[table], filterByFormula: recordIdIn(ids), schema, lease });
213
+ records.forEach((record) => wholeById.set(record.id, record));
214
+ }
215
+ return wholeById;
216
+ }
217
+
218
+ // Planner inputs as the plan saw them; a group whose inputs changed since the scan is left for the next run.
219
+ const plannerInputs = (record, plannerNames) => stableStringify({
220
+ createdTime: record.createdTime,
221
+ fields: Object.fromEntries(plannerNames.filter((name) => name in record.fields).map((name) => [name, record.fields[name]])),
222
+ });
223
+
203
224
  // Where readers find a record: a renamed table or a regrouped record is rewritten even when its fields did not change.
204
225
  const placementOf = (tableName, groupId, patient, createdTime) => stableStringify({ tableName, groupId, patient, createdTime: new Date(createdTime).getTime() });
205
226
 
206
- async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now }) {
227
+ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease }) {
207
228
  const ArchiveRecord = getAirtableArchiveRecord();
208
- const ids = batch.map(({ record }) => archiveRecordId(baseId, record.id));
229
+ const wholeById = await readWholeRecords(baseId, batch, schema, lease);
230
+ const changedGroups = new Set(batch.filter(({ table, record: scanned }) => {
231
+ const whole = wholeById.get(scanned.id);
232
+ return !whole || plannerInputs(whole, schema.plannerFields[table]) !== plannerInputs(scanned, schema.plannerFields[table]);
233
+ }).map(({ group }) => group.groupId));
234
+ const ids = batch.map(({ record: scanned }) => archiveRecordId(baseId, scanned.id));
209
235
  const existing = new Map((await ArchiveRecord.find({ _id: { $in: ids } }, { fields: 1, fieldsHash: 1, sourceHash: 1, tableId: 1, schemaId: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1 }).lean())
210
236
  .map((doc) => [doc._id, doc]));
211
237
 
212
238
  const expected = new Map();
213
239
  const ops = [];
214
- for (const { table, record, group } of batch) {
240
+ for (const { table, record: scanned, group } of batch) {
241
+ if (changedGroups.has(group.groupId)) {
242
+ counts[table].failed += 1;
243
+ logger.error('[airtableArchive] Group changed or gone since the scan', { runId, table, recordId: scanned.id, groupId: group.groupId });
244
+ continue;
245
+ }
246
+ const record = wholeById.get(scanned.id);
215
247
  const _id = archiveRecordId(baseId, record.id);
216
248
  const { normalized, attachments } = normalizeFields(record.fields);
217
249
  const fieldsHash = hashFields(normalized);
@@ -265,6 +297,21 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now }
265
297
  }
266
298
  }
267
299
 
300
+ // Batches never split a group, so a changed record holds back its whole group.
301
+ function groupBatches(groups) {
302
+ const batches = [];
303
+ let batch = [];
304
+ for (const group of groups) {
305
+ if (batch.length && batch.length + group.length > ARCHIVE_BATCH_SIZE) {
306
+ batches.push(batch);
307
+ batch = [];
308
+ }
309
+ batch.push(...group);
310
+ }
311
+ if (batch.length) batches.push(batch);
312
+ return batches;
313
+ }
314
+
268
315
  function validateRequest({ baseId, cutoff, mode, now }) {
269
316
  if (!baseId) throw archiveError('archive_base_required');
270
317
  if (!ARCHIVE_RUN_MODES.includes(mode)) throw archiveError('archive_mode_invalid');
@@ -290,13 +337,13 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
290
337
 
291
338
  Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
292
339
  const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
293
- const work = plan.eligible.flatMap((group) => group.records.map(({ table, id }) => ({ table, record: recordsById.get(id), group })));
294
- work.forEach(({ table }) => { counts[table].eligible += 1; });
340
+ const work = plan.eligible.map((group) => group.records.map(({ table, id }) => ({ table, record: recordsById.get(id), group })));
341
+ work.flat().forEach(({ table }) => { counts[table].eligible += 1; });
295
342
 
296
343
  if (mode === 'copy' && work.length) {
297
344
  const schemaId = await storeSchemaSnapshot(baseId, schema.snapshot, now);
298
- for (let i = 0; i < work.length; i += ARCHIVE_BATCH_SIZE) {
299
- await copyBatch({ baseId, runId, batch: work.slice(i, i + ARCHIVE_BATCH_SIZE), schema, schemaId, counts, now });
345
+ for (const batch of groupBatches(work)) {
346
+ await copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease });
300
347
  await renewLease(runId);
301
348
  }
302
349
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.74.0-dev.15347",
3
+ "version": "5.74.0-dev.15348",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",