@peopl-health/nexus 5.74.0-dev.15346 → 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']);
|
|
@@ -117,6 +128,7 @@ const COMPUTED_FIELD_TYPES = Object.freeze([
|
|
|
117
128
|
'createdTime', 'createdBy', 'autoNumber', 'button', 'aiText',
|
|
118
129
|
]);
|
|
119
130
|
const ARCHIVE_LEASE_MS = 15 * 60 * 1000;
|
|
131
|
+
const ARCHIVE_LEASE_RENEW_MS = 60 * 1000;
|
|
120
132
|
const ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30000;
|
|
121
133
|
|
|
122
134
|
module.exports = {
|
|
@@ -125,6 +137,7 @@ module.exports = {
|
|
|
125
137
|
MIN_ARCHIVE_AGE_DAYS,
|
|
126
138
|
ARCHIVE_BATCH_SIZE,
|
|
127
139
|
ARCHIVE_LEASE_MS,
|
|
140
|
+
ARCHIVE_LEASE_RENEW_MS,
|
|
128
141
|
ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
|
|
129
142
|
COMPUTED_FIELD_TYPES,
|
|
130
143
|
GROUP_LINKS,
|
|
@@ -132,6 +145,7 @@ module.exports = {
|
|
|
132
145
|
BACKWARD_LINKS,
|
|
133
146
|
EXTERNAL_LINKS,
|
|
134
147
|
PATIENT_FIELDS,
|
|
148
|
+
PLANNER_FIELDS,
|
|
135
149
|
WHATSAPP_FIELDS,
|
|
136
150
|
LINK_FIELD_TYPES,
|
|
137
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, 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, PLANNER_FIELDS,
|
|
8
8
|
} = require('../config/airtableArchiveConfig');
|
|
9
9
|
const { logger } = require('../utils/logger');
|
|
10
10
|
const { stableStringify } = require('../utils/jsonUtils');
|
|
@@ -12,10 +12,10 @@ 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
|
-
const {
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
|
55
|
-
await renewLease(runId);
|
|
81
|
+
recordsByTable[schema.tables[key]] = await scanTable({ baseId, tableId, filterByFormula: createdBefore(cutoff), fieldIds: PLANNER_FIELDS[tableId], schema, lease });
|
|
56
82
|
}
|
|
57
83
|
return recordsByTable;
|
|
58
84
|
}
|
|
59
85
|
|
|
60
|
-
async function scanPatientsWithRecent(baseId, cutoff,
|
|
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
|
|
66
|
-
|
|
67
|
-
|
|
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');
|
|
@@ -159,18 +200,50 @@ async function writeOps(ArchiveRecord, ops, runId) {
|
|
|
159
200
|
}
|
|
160
201
|
}
|
|
161
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
|
+
|
|
162
224
|
// Where readers find a record: a renamed table or a regrouped record is rewritten even when its fields did not change.
|
|
163
225
|
const placementOf = (tableName, groupId, patient, createdTime) => stableStringify({ tableName, groupId, patient, createdTime: new Date(createdTime).getTime() });
|
|
164
226
|
|
|
165
|
-
async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now }) {
|
|
227
|
+
async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease }) {
|
|
166
228
|
const ArchiveRecord = getAirtableArchiveRecord();
|
|
167
|
-
const
|
|
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));
|
|
168
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())
|
|
169
236
|
.map((doc) => [doc._id, doc]));
|
|
170
237
|
|
|
171
238
|
const expected = new Map();
|
|
172
239
|
const ops = [];
|
|
173
|
-
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);
|
|
174
247
|
const _id = archiveRecordId(baseId, record.id);
|
|
175
248
|
const { normalized, attachments } = normalizeFields(record.fields);
|
|
176
249
|
const fieldsHash = hashFields(normalized);
|
|
@@ -224,6 +297,21 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now }
|
|
|
224
297
|
}
|
|
225
298
|
}
|
|
226
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
|
+
|
|
227
315
|
function validateRequest({ baseId, cutoff, mode, now }) {
|
|
228
316
|
if (!baseId) throw archiveError('archive_base_required');
|
|
229
317
|
if (!ARCHIVE_RUN_MODES.includes(mode)) throw archiveError('archive_mode_invalid');
|
|
@@ -241,20 +329,21 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
|
|
|
241
329
|
try {
|
|
242
330
|
const schema = await readArchiveSchema(baseId);
|
|
243
331
|
counts = Object.fromEntries(Object.values(schema.tables).map((table) => [table, emptyCounts()]));
|
|
244
|
-
const
|
|
245
|
-
const
|
|
332
|
+
const lease = leaseFor(runId);
|
|
333
|
+
const recordsByTable = await scanOldRecords(baseId, cutoff, schema, lease);
|
|
334
|
+
const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, schema, lease);
|
|
246
335
|
await assertSchemaUnchanged(baseId, schema);
|
|
247
336
|
const plan = planArchive({ recordsByTable, patientsWithRecent, schema });
|
|
248
337
|
|
|
249
338
|
Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
|
|
250
339
|
const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
|
|
251
|
-
const work = plan.eligible.
|
|
252
|
-
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; });
|
|
253
342
|
|
|
254
343
|
if (mode === 'copy' && work.length) {
|
|
255
344
|
const schemaId = await storeSchemaSnapshot(baseId, schema.snapshot, now);
|
|
256
|
-
for (
|
|
257
|
-
await copyBatch({ baseId, runId, batch
|
|
345
|
+
for (const batch of groupBatches(work)) {
|
|
346
|
+
await copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease });
|
|
258
347
|
await renewLease(runId);
|
|
259
348
|
}
|
|
260
349
|
}
|
|
@@ -271,7 +360,7 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
|
|
|
271
360
|
logger.info('[airtableArchive] Run finished', summary);
|
|
272
361
|
return summary;
|
|
273
362
|
} catch (error) {
|
|
274
|
-
const errorCode = error?.code && typeof
|
|
363
|
+
const errorCode = [error?.code, error?.error].find((code) => code && typeof code === 'string') || 'UNKNOWN';
|
|
275
364
|
await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, errorCode } });
|
|
276
365
|
logger.error('[airtableArchive] Run failed', { runId, mode, errorCode });
|
|
277
366
|
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
|
|
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
|
-
|
|
138
|
+
return await withAirtableRetry(async () => {
|
|
150
139
|
try {
|
|
151
|
-
const response = await axios.
|
|
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
|
-
},
|
|
160
|
-
return data.tables;
|
|
149
|
+
}, label);
|
|
161
150
|
} catch (error) {
|
|
162
|
-
logger.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
|
-
|
|
323
|
+
scanRecordPages,
|
|
301
324
|
getBaseSchema,
|
|
302
325
|
updateRecordByFilter,
|
|
303
326
|
addLinkedRecord,
|