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

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.
@@ -117,6 +117,7 @@ const COMPUTED_FIELD_TYPES = Object.freeze([
117
117
  'createdTime', 'createdBy', 'autoNumber', 'button', 'aiText',
118
118
  ]);
119
119
  const ARCHIVE_LEASE_MS = 15 * 60 * 1000;
120
+ const ARCHIVE_LEASE_RENEW_MS = 60 * 1000;
120
121
  const ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30000;
121
122
 
122
123
  module.exports = {
@@ -125,6 +126,7 @@ module.exports = {
125
126
  MIN_ARCHIVE_AGE_DAYS,
126
127
  ARCHIVE_BATCH_SIZE,
127
128
  ARCHIVE_LEASE_MS,
129
+ ARCHIVE_LEASE_RENEW_MS,
128
130
  ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
129
131
  COMPUTED_FIELD_TYPES,
130
132
  GROUP_LINKS,
@@ -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, ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
7
+ ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ARCHIVE_LEASE_RENEW_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS, PATIENT_FIELDS,
8
8
  } = require('../config/airtableArchiveConfig');
9
9
  const { logger } = require('../utils/logger');
10
10
  const { stableStringify } = require('../utils/jsonUtils');
@@ -15,7 +15,7 @@ const {
15
15
  const { createdBefore, createdSince } = require('../helpers/airtableFormulaHelper');
16
16
  const { normalizeFields, hashFields, schemaSnapshotId } = require('../helpers/airtableArchiveHelper');
17
17
 
18
- const { getRecordsWithMetadata, getBaseSchema } = require('./airtableService');
18
+ const { scanRecordPages, getBaseSchema } = require('./airtableService');
19
19
  const { planArchive, resolveArchiveSchema } = require('./airtableArchivePlanService');
20
20
 
21
21
  const DUPLICATE_KEY_ERROR = 11000;
@@ -38,7 +38,7 @@ async function readArchiveSchema(baseId) {
38
38
  return schema;
39
39
  }
40
40
 
41
- // Records come back keyed by name, so a rename during the scans would hide links from the planner.
41
+ // A deleted or retyped field during the scans would read as empty links to the planner.
42
42
  async function assertSchemaUnchanged(baseId, schema) {
43
43
  const current = await readArchiveSchema(baseId);
44
44
  const changed = schema.snapshot.filter((table, i) => stableStringify(table) !== stableStringify(current.snapshot[i])).map((table) => table.id);
@@ -48,23 +48,49 @@ async function assertSchemaUnchanged(baseId, schema) {
48
48
  }
49
49
  }
50
50
 
51
- async function scanOldRecords(baseId, cutoff, runId, schema) {
51
+ // Records are read by field id and named from the run's snapshot, so a rename mid-scan cannot change what the planner sees.
52
+ async function scanTable({ baseId, tableId, filterByFormula, fieldIds, schema, lease }) {
53
+ const names = new Map(schema.snapshot.find((table) => table.id === tableId).fields.map((field) => [field.id, field.name]));
54
+ const records = [];
55
+ await scanRecordPages(baseId, tableId, {
56
+ filterByFormula,
57
+ fieldIds,
58
+ onPage: async (page) => {
59
+ for (const record of page) {
60
+ const fields = {};
61
+ for (const [fieldId, value] of Object.entries(record.fields)) {
62
+ if (!names.has(fieldId)) {
63
+ logger.error('[airtableArchive] Scanned a field missing from the run schema', { baseId, tableId, fieldId });
64
+ throw archiveError('archive_schema_mismatch');
65
+ }
66
+ fields[names.get(fieldId)] = value;
67
+ }
68
+ records.push({ id: record.id, createdTime: record.createdTime, fields });
69
+ }
70
+ await lease.renewIfDue();
71
+ },
72
+ onRestart: () => { records.length = 0; },
73
+ });
74
+ await lease.renew();
75
+ return records;
76
+ }
77
+
78
+ async function scanOldRecords(baseId, cutoff, schema, lease) {
52
79
  const recordsByTable = {};
53
80
  for (const [key, tableId] of Object.entries(ARCHIVE_TABLES)) {
54
- recordsByTable[schema.tables[key]] = await getRecordsWithMetadata(baseId, tableId, createdBefore(cutoff));
55
- await renewLease(runId);
81
+ recordsByTable[schema.tables[key]] = await scanTable({ baseId, tableId, filterByFormula: createdBefore(cutoff), schema, lease });
56
82
  }
57
83
  return recordsByTable;
58
84
  }
59
85
 
60
- async function scanPatientsWithRecent(baseId, cutoff, runId, schema) {
86
+ async function scanPatientsWithRecent(baseId, cutoff, schema, lease) {
61
87
  const patientsWithRecent = {};
62
88
  for (const key of ['QUESTIONNAIRES', 'TRIAGES']) {
63
89
  const table = schema.tables[key];
64
90
  const patientField = schema.patientFields[table];
65
- const records = await getRecordsWithMetadata(baseId, ARCHIVE_TABLES[key], createdSince(cutoff), [patientField]);
66
- patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields?.[patientField] || []));
67
- await renewLease(runId);
91
+ const tableId = ARCHIVE_TABLES[key];
92
+ const records = await scanTable({ baseId, tableId, filterByFormula: createdSince(cutoff), fieldIds: [PATIENT_FIELDS[tableId]], schema, lease });
93
+ patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields[patientField] || []));
68
94
  }
69
95
  return patientsWithRecent;
70
96
  }
@@ -118,6 +144,21 @@ async function renewLease(runId) {
118
144
  if (!result?.matchedCount) throw archiveError('archive_lease_lost');
119
145
  }
120
146
 
147
+ // Renews at most once per interval, so a scan of hundreds of pages costs a handful of writes.
148
+ function leaseFor(runId) {
149
+ let renewedAt = Date.now();
150
+ const renew = async () => {
151
+ await renewLease(runId);
152
+ renewedAt = Date.now();
153
+ };
154
+ return {
155
+ renew,
156
+ renewIfDue: async () => {
157
+ if (Date.now() - renewedAt >= ARCHIVE_LEASE_RENEW_MS) await renew();
158
+ },
159
+ };
160
+ }
161
+
121
162
  async function rehostAttachments({ baseId, tableId, recordId, attachments, alreadyHosted }) {
122
163
  if (!attachments.length) return [];
123
164
  const bucket = runtimeConfig.get('AIRTABLE_ARCHIVE_BUCKET');
@@ -241,8 +282,9 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
241
282
  try {
242
283
  const schema = await readArchiveSchema(baseId);
243
284
  counts = Object.fromEntries(Object.values(schema.tables).map((table) => [table, emptyCounts()]));
244
- const recordsByTable = await scanOldRecords(baseId, cutoff, runId, schema);
245
- const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, runId, schema);
285
+ const lease = leaseFor(runId);
286
+ const recordsByTable = await scanOldRecords(baseId, cutoff, schema, lease);
287
+ const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, schema, lease);
246
288
  await assertSchemaUnchanged(baseId, schema);
247
289
  const plan = planArchive({ recordsByTable, patientsWithRecent, schema });
248
290
 
@@ -271,7 +313,7 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
271
313
  logger.info('[airtableArchive] Run finished', summary);
272
314
  return summary;
273
315
  } catch (error) {
274
- const errorCode = error?.code && typeof error.code === 'string' ? error.code : 'UNKNOWN';
316
+ const errorCode = [error?.code, error?.error].find((code) => code && typeof code === 'string') || 'UNKNOWN';
275
317
  await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, errorCode } });
276
318
  logger.error('[airtableArchive] Run failed', { runId, mode, errorCode });
277
319
  throw error;
@@ -14,6 +14,10 @@ const MAX_ATTEMPTS = 3;
14
14
  const AIRTABLE_API_URL = 'https://api.airtable.com/v0';
15
15
  const AXIOS_TIMEOUT_CODE = 'ECONNABORTED';
16
16
  const RETRY_BASE_DELAY_MS = 1000;
17
+ const SCAN_PAGE_SIZE = 100;
18
+ const SCAN_PAGE_INTERVAL_MS = 400;
19
+ const ITERATOR_EXPIRED = 'LIST_RECORDS_ITERATOR_NOT_AVAILABLE';
20
+ const MAX_SCAN_RESTARTS = 1;
17
21
 
18
22
  function isPermanentAirtableError(error) {
19
23
  const status = error?.statusCode;
@@ -127,28 +131,14 @@ async function getRecordByFilter(baseID, tableName, filter, view = 'Grid view',
127
131
  }
128
132
  }
129
133
 
130
- async function getRecordsWithMetadata(baseID, tableName, filter, fields) {
131
- try {
132
- const selectOptions = { filterByFormula: filter };
133
- if (fields && fields.length) selectOptions.fields = fields;
134
- return await withAirtableRetry(
135
- () => collectRecords(getBase(baseID)(tableName).select(selectOptions), (r) => ({ id: r.id, createdTime: r._rawJson?.createdTime, fields: r.fields })),
136
- 'getRecordsWithMetadata'
137
- );
138
- } catch (error) {
139
- logger.error('[getRecordsWithMetadata] Failed', safeAirtableFailure(error));
140
- throw error;
141
- }
142
- }
143
-
144
- // Needs the schema.bases:read scope; returns [{ id, name, fields: [{ id, name, type }] }] per table.
145
- async function getBaseSchema(baseID) {
134
+ async function airtableRequest(method, path, body, label) {
146
135
  const apiKey = getApiKey();
147
136
  if (!apiKey) throw new Error('Airtable not configured. Set AIRTABLE_API_KEY');
148
137
  try {
149
- const data = await withAirtableRetry(async () => {
138
+ return await withAirtableRetry(async () => {
150
139
  try {
151
- const response = await axios.get(`${AIRTABLE_API_URL}/meta/bases/${baseID}/tables`, {
140
+ const response = await axios.request({
141
+ method, url: `${AIRTABLE_API_URL}/${path}`, data: body,
152
142
  headers: { Authorization: `Bearer ${apiKey}` },
153
143
  timeout: getRequestTimeoutMs(),
154
144
  });
@@ -156,14 +146,47 @@ async function getBaseSchema(baseID) {
156
146
  } catch (error) {
157
147
  throw toAirtableHttpError(error);
158
148
  }
159
- }, 'getBaseSchema');
160
- return data.tables;
149
+ }, label);
161
150
  } catch (error) {
162
- logger.error('[getBaseSchema] Failed', safeAirtableFailure(error));
151
+ logger.error(`[${label}] Failed`, { ...safeAirtableFailure(error), airtableError: error.error });
163
152
  throw error;
164
153
  }
165
154
  }
166
155
 
156
+ // Records keyed by field id. A failure retries its page, not the scan; an expired iterator restarts it after onRestart.
157
+ async function scanRecordPages(baseID, tableId, { filterByFormula, fieldIds, onPage, onRestart }) {
158
+ let offset;
159
+ let restarts = 0;
160
+ for (;;) {
161
+ const started = Date.now();
162
+ let data;
163
+ try {
164
+ data = await airtableRequest('post', `${baseID}/${tableId}/listRecords`, {
165
+ filterByFormula, pageSize: SCAN_PAGE_SIZE, returnFieldsByFieldId: true,
166
+ ...(fieldIds?.length ? { fields: fieldIds } : {}), ...(offset ? { offset } : {}),
167
+ }, 'scanRecordPages');
168
+ } catch (error) {
169
+ if (error.error !== ITERATOR_EXPIRED || !offset || restarts >= MAX_SCAN_RESTARTS) throw error;
170
+ restarts += 1;
171
+ offset = undefined;
172
+ logger.warn('[scanRecordPages] Iterator expired, restarting the scan', { baseID, tableId });
173
+ await onRestart();
174
+ continue;
175
+ }
176
+ await onPage((data.records || []).map((r) => ({ id: r.id, createdTime: r.createdTime, fields: r.fields || {} })));
177
+ offset = data.offset;
178
+ if (!offset) return;
179
+ const wait = SCAN_PAGE_INTERVAL_MS - (Date.now() - started);
180
+ if (wait > 0) await delay(wait);
181
+ }
182
+ }
183
+
184
+ // Needs the schema.bases:read scope; returns [{ id, name, fields: [{ id, name, type }] }] per table.
185
+ async function getBaseSchema(baseID) {
186
+ const data = await airtableRequest('get', `meta/bases/${baseID}/tables`, undefined, 'getBaseSchema');
187
+ return data.tables;
188
+ }
189
+
167
190
  async function updateRecordByFilter(baseID, tableName, filter, updateFields, context = null) {
168
191
  if (isShadowRun() || isBenchMode(context)) {
169
192
  logger.info(`[updateRecordByFilter:${isShadowRun() ? 'shadow' : 'bench'}] Suppressed`, { tableName, filter, code: context });
@@ -297,7 +320,7 @@ module.exports = {
297
320
  addRecord,
298
321
  getRecords,
299
322
  getRecordByFilter,
300
- getRecordsWithMetadata,
323
+ scanRecordPages,
301
324
  getBaseSchema,
302
325
  updateRecordByFilter,
303
326
  addLinkedRecord,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.74.0-dev.15346",
3
+ "version": "5.74.0-dev.15347",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",