@peopl-health/nexus 5.77.0 → 5.78.0-dev.16561
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.
|
@@ -130,6 +130,14 @@ const COMPUTED_FIELD_TYPES = Object.freeze([
|
|
|
130
130
|
const ARCHIVE_LEASE_MS = 15 * 60 * 1000;
|
|
131
131
|
const ARCHIVE_LEASE_RENEW_MS = 60 * 1000;
|
|
132
132
|
const ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30000;
|
|
133
|
+
// A delete run takes at most this many groups, so every slice stays small enough to review.
|
|
134
|
+
const ARCHIVE_DELETE_MAX_GROUPS = 1000;
|
|
135
|
+
// Parents first: a surviving parent never sees its children vanish, which would match the base's send automations.
|
|
136
|
+
const ARCHIVE_DELETE_ORDER = Object.freeze([
|
|
137
|
+
ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_TABLES.TRIAGES, ARCHIVE_TABLES.RECOMMENDATIONS,
|
|
138
|
+
ARCHIVE_TABLES.RESOLUTIONS, ARCHIVE_TABLES.ADDITIONAL_ANSWERS, ARCHIVE_TABLES.SYMPTOMS,
|
|
139
|
+
]);
|
|
140
|
+
const ARCHIVE_DELETE_SPACING_MS = 250;
|
|
133
141
|
|
|
134
142
|
module.exports = {
|
|
135
143
|
ARCHIVE_TABLES,
|
|
@@ -139,6 +147,9 @@ module.exports = {
|
|
|
139
147
|
ARCHIVE_LEASE_MS,
|
|
140
148
|
ARCHIVE_LEASE_RENEW_MS,
|
|
141
149
|
ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
|
|
150
|
+
ARCHIVE_DELETE_MAX_GROUPS,
|
|
151
|
+
ARCHIVE_DELETE_ORDER,
|
|
152
|
+
ARCHIVE_DELETE_SPACING_MS,
|
|
142
153
|
COMPUTED_FIELD_TYPES,
|
|
143
154
|
GROUP_LINKS,
|
|
144
155
|
CARRY_OVER_LINKS,
|
|
@@ -3,7 +3,7 @@ const mongoose = require('mongoose');
|
|
|
3
3
|
const { getDb, getModelDatabase } = require('../config/mongoConfig');
|
|
4
4
|
|
|
5
5
|
const ARCHIVE_SCHEMA_VERSION = 1;
|
|
6
|
-
const ARCHIVE_RUN_MODES = ['plan', 'copy'];
|
|
6
|
+
const ARCHIVE_RUN_MODES = ['plan', 'copy', 'delete'];
|
|
7
7
|
const ARCHIVE_RUN_STATUSES = ['running', 'succeeded', 'failed'];
|
|
8
8
|
|
|
9
9
|
const archivedAttachmentSchema = new mongoose.Schema({
|
|
@@ -37,6 +37,7 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
|
|
|
37
37
|
runId: { type: String, required: true },
|
|
38
38
|
archivedAt: { type: Date, required: true },
|
|
39
39
|
sourceDeletedAt: { type: Date, default: null },
|
|
40
|
+
deleteRunId: { type: String, default: null },
|
|
40
41
|
schemaVersion: { type: Number, required: true, default: ARCHIVE_SCHEMA_VERSION },
|
|
41
42
|
}, { collection: 'airtable_archive_records', minimize: false, versionKey: false });
|
|
42
43
|
|
|
@@ -53,6 +54,19 @@ const tableCountsSchema = new mongoose.Schema({
|
|
|
53
54
|
refreshed: { type: Number, default: 0 },
|
|
54
55
|
verified: { type: Number, default: 0 },
|
|
55
56
|
failed: { type: Number, default: 0 },
|
|
57
|
+
skipped: { type: Number, default: 0 },
|
|
58
|
+
stamped: { type: Number, default: 0 },
|
|
59
|
+
deleted: { type: Number, default: 0 },
|
|
60
|
+
}, { _id: false });
|
|
61
|
+
|
|
62
|
+
// One eligible group as the plan saw it, so a later delete can name exactly the groups that were reviewed.
|
|
63
|
+
const plannedGroupSchema = new mongoose.Schema({
|
|
64
|
+
groupId: { type: String, required: true },
|
|
65
|
+
// Every patient of the group's records: a shared questionnaire can join two patients.
|
|
66
|
+
patientRecordIds: { type: [String], default: [] },
|
|
67
|
+
// None of them has a patient-linked questionnaire or triage since the cutoff.
|
|
68
|
+
inactive: { type: Boolean, required: true },
|
|
69
|
+
records: { type: Map, of: Number, default: {} },
|
|
56
70
|
}, { _id: false });
|
|
57
71
|
|
|
58
72
|
const airtableArchiveRunSchema = new mongoose.Schema({
|
|
@@ -69,6 +83,14 @@ const airtableArchiveRunSchema = new mongoose.Schema({
|
|
|
69
83
|
kept: { type: Map, of: Number, default: {} },
|
|
70
84
|
},
|
|
71
85
|
tables: { type: Map, of: tableCountsSchema, default: {} },
|
|
86
|
+
eligibleGroups: { type: [plannedGroupSchema], default: [] },
|
|
87
|
+
requestedGroupIds: { type: [String], default: [] },
|
|
88
|
+
groups: {
|
|
89
|
+
requested: { type: Number, default: 0 },
|
|
90
|
+
notEligible: { type: Number, default: 0 },
|
|
91
|
+
unverified: { type: Number, default: 0 },
|
|
92
|
+
deleted: { type: Number, default: 0 },
|
|
93
|
+
},
|
|
72
94
|
errorCode: { type: String, default: null },
|
|
73
95
|
}, { collection: 'airtable_archive_runs', minimize: false, timestamps: true });
|
|
74
96
|
|
|
@@ -5,6 +5,7 @@ const runtimeConfig = require('../config/runtimeConfig');
|
|
|
5
5
|
const { uploadBufferToS3 } = require('../config/awsConfig');
|
|
6
6
|
const {
|
|
7
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
|
+
ARCHIVE_DELETE_MAX_GROUPS, ARCHIVE_DELETE_ORDER, ARCHIVE_DELETE_SPACING_MS, LINK_FIELD_TYPES,
|
|
8
9
|
} = require('../config/airtableArchiveConfig');
|
|
9
10
|
const { logger } = require('../utils/logger');
|
|
10
11
|
const { stableStringify } = require('../utils/jsonUtils');
|
|
@@ -15,7 +16,7 @@ const {
|
|
|
15
16
|
const { createdBefore, createdSince, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
16
17
|
const { normalizeFields, hashFields, schemaSnapshotId } = require('../helpers/airtableArchiveHelper');
|
|
17
18
|
|
|
18
|
-
const { scanRecordPages, getBaseSchema } = require('./airtableService');
|
|
19
|
+
const { scanRecordPages, getBaseSchema, deleteRecords } = require('./airtableService');
|
|
19
20
|
const { planArchive, resolveArchiveSchema } = require('./airtableArchivePlanService');
|
|
20
21
|
|
|
21
22
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
@@ -118,7 +119,7 @@ function ensureRunIndexes() {
|
|
|
118
119
|
return runIndexesReady;
|
|
119
120
|
}
|
|
120
121
|
|
|
121
|
-
async function acquireRun({ baseId, mode, cutoff, now }) {
|
|
122
|
+
async function acquireRun({ baseId, mode, cutoff, now, groupIds }) {
|
|
122
123
|
await ensureRunIndexes();
|
|
123
124
|
const Run = getAirtableArchiveRun();
|
|
124
125
|
await Run.updateMany(
|
|
@@ -127,7 +128,7 @@ async function acquireRun({ baseId, mode, cutoff, now }) {
|
|
|
127
128
|
);
|
|
128
129
|
try {
|
|
129
130
|
return await Run.create({
|
|
130
|
-
runId: uuidv4(), baseId, mode, cutoff, status: 'running', startedAt: now, leaseExpiresAt: new Date(now.getTime() + ARCHIVE_LEASE_MS),
|
|
131
|
+
runId: uuidv4(), baseId, mode, cutoff, status: 'running', startedAt: now, leaseExpiresAt: new Date(now.getTime() + ARCHIVE_LEASE_MS), requestedGroupIds: groupIds,
|
|
131
132
|
});
|
|
132
133
|
} catch (error) {
|
|
133
134
|
if (error?.code === DUPLICATE_KEY_ERROR) throw archiveError('archive_run_in_progress');
|
|
@@ -180,7 +181,7 @@ async function rehostAttachments({ baseId, tableId, recordId, attachments, alrea
|
|
|
180
181
|
return hosted;
|
|
181
182
|
}
|
|
182
183
|
|
|
183
|
-
const emptyCounts = () => ({ scanned: 0, eligible: 0, copied: 0, refreshed: 0, verified: 0, failed: 0 });
|
|
184
|
+
const emptyCounts = () => ({ scanned: 0, eligible: 0, copied: 0, refreshed: 0, verified: 0, failed: 0, skipped: 0, stamped: 0, deleted: 0 });
|
|
184
185
|
|
|
185
186
|
const WRITE_REJECTIONS = ['MongoBulkWriteError', 'MongooseBulkWriteError', 'MongoInvalidArgumentError'];
|
|
186
187
|
|
|
@@ -232,12 +233,17 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
|
|
|
232
233
|
return !whole || plannerInputs(whole, schema.plannerFields[table]) !== plannerInputs(scanned, schema.plannerFields[table]);
|
|
233
234
|
}).map(({ group }) => group.groupId));
|
|
234
235
|
const ids = batch.map(({ record: scanned }) => archiveRecordId(baseId, scanned.id));
|
|
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())
|
|
236
|
+
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, sourceDeletedAt: 1 }).lean())
|
|
236
237
|
.map((doc) => [doc._id, doc]));
|
|
237
238
|
|
|
238
239
|
const expected = new Map();
|
|
239
240
|
const ops = [];
|
|
240
241
|
for (const { table, record: scanned, group, patient } of batch) {
|
|
242
|
+
// A stamped copy is what readers serve once the delete finishes, so a record a stopped delete left behind keeps it.
|
|
243
|
+
if (existing.get(archiveRecordId(baseId, scanned.id))?.sourceDeletedAt) {
|
|
244
|
+
counts[table].skipped += 1;
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
241
247
|
if (changedGroups.has(group.groupId)) {
|
|
242
248
|
counts[table].failed += 1;
|
|
243
249
|
logger.error('[airtableArchive] Group changed or gone since the scan', { runId, table, recordId: scanned.id, groupId: group.groupId });
|
|
@@ -297,6 +303,134 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
|
|
|
297
303
|
}
|
|
298
304
|
}
|
|
299
305
|
|
|
306
|
+
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
307
|
+
|
|
308
|
+
const linkNamesOf = (schema, table) => schema.snapshot.find((t) => t.name === table).fields.filter((f) => LINK_FIELD_TYPES.includes(f.type)).map((f) => f.name);
|
|
309
|
+
|
|
310
|
+
// Airtable drops links to a deleted record, so a link that lost only records gone from Airtable with a stamped copy reads as before.
|
|
311
|
+
function restoreDeletedLinks(fields, reference, linkNames, goneIds) {
|
|
312
|
+
const restored = { ...fields };
|
|
313
|
+
for (const name of linkNames) {
|
|
314
|
+
const before = reference[name] || [];
|
|
315
|
+
const after = fields[name] || [];
|
|
316
|
+
const lost = before.filter((id) => !after.includes(id));
|
|
317
|
+
if (lost.length && lost.every((id) => goneIds.has(id)) && after.every((id) => before.includes(id))) restored[name] = reference[name];
|
|
318
|
+
}
|
|
319
|
+
return restored;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Why a record must stay in Airtable, or null when its archived copy can stand in for it.
|
|
323
|
+
function deleteBlocker({ whole, scanned, doc, table, group, patient, schema, goneIds }) {
|
|
324
|
+
if (!whole) return 'gone_from_source';
|
|
325
|
+
const linkNames = linkNamesOf(schema, table);
|
|
326
|
+
const asScanned = { ...whole, fields: restoreDeletedLinks(whole.fields, scanned.fields, linkNames, goneIds) };
|
|
327
|
+
if (plannerInputs(asScanned, schema.plannerFields[table]) !== plannerInputs(scanned, schema.plannerFields[table])) return 'changed_since_scan';
|
|
328
|
+
if (!doc) return 'not_archived';
|
|
329
|
+
if (hashFields(doc.fields) !== doc.fieldsHash) return 'copy_damaged';
|
|
330
|
+
const { normalized, attachments } = normalizeFields(whole.fields);
|
|
331
|
+
if (doc.sourceHash !== hashFields(restoreDeletedLinks(normalized, doc.fields, linkNames, goneIds), schema.computed.get(table))) return 'source_edited';
|
|
332
|
+
if (placementOf(doc.tableName, doc.groupId, doc.patient, doc.createdTime) !== placementOf(table, group.groupId, patient, whole.createdTime)) return 'placement_changed';
|
|
333
|
+
const hosted = new Set((doc.attachments || []).map((a) => a.id));
|
|
334
|
+
if (attachments.some(({ item }) => !hosted.has(item.id))) return 'attachment_not_hosted';
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// The request may have landed even when it failed, so what is still in Airtable decides.
|
|
339
|
+
async function deleteChunk({ baseId, runId, tableId, recordIds, schema, lease }) {
|
|
340
|
+
try {
|
|
341
|
+
if ((await deleteRecords(baseId, tableId, recordIds)).length === recordIds.length) return;
|
|
342
|
+
} catch (error) {
|
|
343
|
+
logger.warn('[airtableArchive] Delete request failed, re-reading what is left', { runId, tableId, statusCode: error?.statusCode || null });
|
|
344
|
+
}
|
|
345
|
+
const left = await scanTable({ baseId, tableId, filterByFormula: recordIdIn(recordIds), schema, lease });
|
|
346
|
+
if (left.length) throw archiveError('archive_delete_failed');
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const ARCHIVED_PROJECTION = { fields: 1, fieldsHash: 1, sourceHash: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1 };
|
|
350
|
+
|
|
351
|
+
// Linked records missing from Airtable whose copies were stamped deleted; only records the scan covers count, so missing means gone.
|
|
352
|
+
async function goneLinkedIds({ baseId, entries, wholeById, archived, schema, liveIds, cutoff }) {
|
|
353
|
+
const missing = new Set();
|
|
354
|
+
for (const { table, record: scanned } of entries) {
|
|
355
|
+
const whole = wholeById.get(scanned.id);
|
|
356
|
+
const doc = archived.get(archiveRecordId(baseId, scanned.id));
|
|
357
|
+
for (const name of linkNamesOf(schema, table)) {
|
|
358
|
+
[...(scanned.fields[name] || []), ...(doc?.fields?.[name] || [])]
|
|
359
|
+
.filter((id) => !(whole?.fields[name] || []).includes(id) && !liveIds.has(id)).forEach((id) => missing.add(id));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (!missing.size) return new Set();
|
|
363
|
+
const stamped = await getAirtableArchiveRecord().find({ _id: { $in: [...missing].map((id) => archiveRecordId(baseId, id)) }, sourceDeletedAt: { $ne: null }, createdTime: { $lt: cutoff } }, { recordId: 1 }).lean();
|
|
364
|
+
return new Set(stamped.map((doc) => doc.recordId));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
async function findBlockers({ baseId, entries, schema, lease, liveIds, cutoff }) {
|
|
368
|
+
const wholeById = await readWholeRecords(baseId, entries, schema, lease);
|
|
369
|
+
const archived = new Map((await getAirtableArchiveRecord().find(
|
|
370
|
+
{ _id: { $in: entries.map(({ record }) => archiveRecordId(baseId, record.id)) } }, ARCHIVED_PROJECTION,
|
|
371
|
+
).lean()).map((doc) => [doc._id, doc]));
|
|
372
|
+
const goneIds = await goneLinkedIds({ baseId, entries, wholeById, archived, schema, liveIds, cutoff });
|
|
373
|
+
return entries.map((entry) => ({
|
|
374
|
+
entry,
|
|
375
|
+
reason: deleteBlocker({
|
|
376
|
+
whole: wholeById.get(entry.record.id), scanned: entry.record, doc: archived.get(archiveRecordId(baseId, entry.record.id)), ...entry, schema, goneIds,
|
|
377
|
+
}),
|
|
378
|
+
})).filter(({ reason }) => reason);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Every record of a verified group is stamped deleted in the archive before Airtable deletes it, so readers never miss it.
|
|
382
|
+
async function deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff }) {
|
|
383
|
+
const ArchiveRecord = getAirtableArchiveRecord();
|
|
384
|
+
const blocked = new Set();
|
|
385
|
+
for (const { entry: { table, record, group }, reason } of await findBlockers({ baseId, entries: batch, schema, lease, liveIds, cutoff })) {
|
|
386
|
+
blocked.add(group.groupId);
|
|
387
|
+
logger.error('[airtableArchive] Group kept in Airtable: its copy cannot stand in for the source', { runId, table, recordId: record.id, groupId: group.groupId, reason });
|
|
388
|
+
}
|
|
389
|
+
groups.unverified += blocked.size;
|
|
390
|
+
const verified = batch.filter(({ group }) => !blocked.has(group.groupId));
|
|
391
|
+
if (!verified.length) return;
|
|
392
|
+
|
|
393
|
+
const verifiedIds = verified.map(({ record }) => archiveRecordId(baseId, record.id));
|
|
394
|
+
await ArchiveRecord.updateMany(
|
|
395
|
+
{ _id: { $in: verifiedIds }, sourceDeletedAt: null },
|
|
396
|
+
{ $set: { sourceDeletedAt: new Date(), deleteRunId: runId } },
|
|
397
|
+
{ writeConcern: WRITE_CONCERN },
|
|
398
|
+
);
|
|
399
|
+
const stamped = await ArchiveRecord.find({ _id: { $in: verifiedIds }, sourceDeletedAt: { $ne: null } }, { _id: 1 }).lean();
|
|
400
|
+
if (stamped.length !== verifiedIds.length) throw archiveError('archive_stamp_failed');
|
|
401
|
+
verified.forEach(({ table }) => { counts[table].stamped += 1; });
|
|
402
|
+
|
|
403
|
+
for (const tableId of ARCHIVE_DELETE_ORDER) {
|
|
404
|
+
const entries = verified.filter(({ table }) => schema.tableIds[table] === tableId);
|
|
405
|
+
for (let i = 0; i < entries.length; i += 10) {
|
|
406
|
+
const chunk = entries.slice(i, i + 10);
|
|
407
|
+
// Re-checked right before its request, so an edit made while earlier chunks were deleted stops the run with its copy stamped.
|
|
408
|
+
const changed = await findBlockers({ baseId, entries: chunk, schema, lease, liveIds, cutoff });
|
|
409
|
+
if (changed.length) {
|
|
410
|
+
changed.forEach(({ entry: { table, record, group }, reason }) => logger.error('[airtableArchive] Record changed during the delete', { runId, table, recordId: record.id, groupId: group.groupId, reason }));
|
|
411
|
+
throw archiveError('archive_changed_during_delete');
|
|
412
|
+
}
|
|
413
|
+
await deleteChunk({ baseId, runId, tableId, recordIds: chunk.map(({ record }) => record.id), schema, lease });
|
|
414
|
+
chunk.forEach(({ table, record }) => {
|
|
415
|
+
counts[table].deleted += 1;
|
|
416
|
+
liveIds.delete(record.id);
|
|
417
|
+
});
|
|
418
|
+
await lease.renewIfDue();
|
|
419
|
+
await delay(ARCHIVE_DELETE_SPACING_MS);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if ((await readWholeRecords(baseId, verified, schema, lease)).size) throw archiveError('archive_delete_incomplete');
|
|
423
|
+
groups.deleted += new Set(verified.map(({ group }) => group.groupId)).size;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function plannedGroup(group, patientsWithRecent) {
|
|
427
|
+
const patientRecordIds = [...new Set(group.records.map(({ patient }) => patient?.recordId).filter(Boolean))];
|
|
428
|
+
const records = {};
|
|
429
|
+
group.records.forEach(({ table }) => { records[table] = (records[table] || 0) + 1; });
|
|
430
|
+
const isInactive = (patientId) => Object.values(patientsWithRecent).every((patients) => !patients.has(patientId));
|
|
431
|
+
return { groupId: group.groupId, patientRecordIds, inactive: patientRecordIds.length > 0 && patientRecordIds.every(isInactive), records };
|
|
432
|
+
}
|
|
433
|
+
|
|
300
434
|
// Batches never split a group, so a changed record holds back its whole group.
|
|
301
435
|
function groupBatches(groups) {
|
|
302
436
|
const batches = [];
|
|
@@ -312,19 +446,25 @@ function groupBatches(groups) {
|
|
|
312
446
|
return batches;
|
|
313
447
|
}
|
|
314
448
|
|
|
315
|
-
function validateRequest({ baseId, cutoff, mode, now }) {
|
|
449
|
+
function validateRequest({ baseId, cutoff, mode, now, groupIds }) {
|
|
316
450
|
if (!baseId) throw archiveError('archive_base_required');
|
|
317
451
|
if (!ARCHIVE_RUN_MODES.includes(mode)) throw archiveError('archive_mode_invalid');
|
|
452
|
+
if (mode === 'delete') {
|
|
453
|
+
const valid = Array.isArray(groupIds) && groupIds.length > 0 && groupIds.length <= ARCHIVE_DELETE_MAX_GROUPS
|
|
454
|
+
&& groupIds.every((id) => typeof id === 'string' && id) && new Set(groupIds).size === groupIds.length;
|
|
455
|
+
if (!valid) throw archiveError('archive_delete_groups_invalid');
|
|
456
|
+
}
|
|
318
457
|
if (!(cutoff instanceof Date) || Number.isNaN(cutoff.getTime())) throw archiveError('archive_cutoff_invalid');
|
|
319
458
|
if (daysSince(cutoff, now.getTime()) < MIN_ARCHIVE_AGE_DAYS) throw archiveError('archive_cutoff_too_recent');
|
|
320
459
|
}
|
|
321
460
|
|
|
322
|
-
//
|
|
323
|
-
async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
|
|
324
|
-
validateRequest({ baseId, cutoff, mode, now });
|
|
325
|
-
const run = await acquireRun({ baseId, mode, cutoff, now });
|
|
461
|
+
// `plan` and `copy` never delete from Airtable; `delete` removes only the named groups that are still eligible and verified.
|
|
462
|
+
async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date(), groupIds = [] }) {
|
|
463
|
+
validateRequest({ baseId, cutoff, mode, now, groupIds });
|
|
464
|
+
const run = await acquireRun({ baseId, mode, cutoff, now, groupIds: mode === 'delete' ? groupIds : [] });
|
|
326
465
|
const { runId } = run;
|
|
327
466
|
let counts = {};
|
|
467
|
+
const groups = { requested: mode === 'delete' ? groupIds.length : 0, notEligible: 0, unverified: 0, deleted: 0 };
|
|
328
468
|
|
|
329
469
|
try {
|
|
330
470
|
const schema = await readArchiveSchema(baseId);
|
|
@@ -348,20 +488,37 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
|
|
|
348
488
|
}
|
|
349
489
|
}
|
|
350
490
|
|
|
491
|
+
if (mode === 'delete') {
|
|
492
|
+
const requested = new Set(groupIds);
|
|
493
|
+
const targets = work.filter(([{ group }]) => requested.has(group.groupId));
|
|
494
|
+
groups.notEligible = requested.size - targets.length;
|
|
495
|
+
const liveIds = new Set(recordsById.keys());
|
|
496
|
+
for (const batch of groupBatches(targets)) {
|
|
497
|
+
await deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff });
|
|
498
|
+
await renewLease(runId);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// Only a plan stores its groups: a copy run's list would include groups it held back, so slices are picked from plans.
|
|
503
|
+
const eligibleGroups = mode === 'plan' ? plan.eligible.map((group) => plannedGroup(group, patientsWithRecent)) : [];
|
|
351
504
|
const failed = Object.values(counts).reduce((sum, c) => sum + c.failed, 0);
|
|
505
|
+
// A delete that left any named group in Airtable is not a finished slice.
|
|
506
|
+
const errorCode = (failed && 'records_failed') || ((groups.notEligible || groups.unverified) && 'groups_not_deleted') || null;
|
|
352
507
|
const summary = {
|
|
353
|
-
runId, mode, cutoff, status:
|
|
354
|
-
components: { eligible: plan.eligible.length, kept: plan.keptByReason }, tables: counts,
|
|
508
|
+
runId, mode, cutoff, status: errorCode ? 'failed' : 'succeeded',
|
|
509
|
+
components: { eligible: plan.eligible.length, kept: plan.keptByReason }, tables: counts, groups,
|
|
355
510
|
};
|
|
356
511
|
const finished = await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, {
|
|
357
|
-
$set: {
|
|
512
|
+
$set: {
|
|
513
|
+
status: summary.status, finishedAt: new Date(), components: summary.components, tables: counts, eligibleGroups, groups, errorCode,
|
|
514
|
+
},
|
|
358
515
|
});
|
|
359
516
|
if (!finished?.matchedCount) throw archiveError('archive_lease_lost');
|
|
360
517
|
logger.info('[airtableArchive] Run finished', summary);
|
|
361
518
|
return summary;
|
|
362
519
|
} catch (error) {
|
|
363
520
|
const errorCode = [error?.code, error?.error].find((code) => code && typeof code === 'string') || 'UNKNOWN';
|
|
364
|
-
await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, errorCode } });
|
|
521
|
+
await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, groups, errorCode } });
|
|
365
522
|
logger.error('[airtableArchive] Run failed', { runId, mode, errorCode });
|
|
366
523
|
throw error;
|
|
367
524
|
}
|
|
@@ -18,6 +18,7 @@ const SCAN_PAGE_SIZE = 100;
|
|
|
18
18
|
const SCAN_PAGE_INTERVAL_MS = 400;
|
|
19
19
|
const ITERATOR_EXPIRED = 'LIST_RECORDS_ITERATOR_NOT_AVAILABLE';
|
|
20
20
|
const MAX_SCAN_RESTARTS = 1;
|
|
21
|
+
const MAX_DELETE_BATCH = 10;
|
|
21
22
|
|
|
22
23
|
function isPermanentAirtableError(error) {
|
|
23
24
|
const status = error?.statusCode;
|
|
@@ -131,7 +132,7 @@ async function getRecordByFilter(baseID, tableName, filter, view = 'Grid view',
|
|
|
131
132
|
}
|
|
132
133
|
}
|
|
133
134
|
|
|
134
|
-
async function airtableRequest(method, path, body, label) {
|
|
135
|
+
async function airtableRequest(method, path, body, label, retryOptions) {
|
|
135
136
|
const apiKey = getApiKey();
|
|
136
137
|
if (!apiKey) throw new Error('Airtable not configured. Set AIRTABLE_API_KEY');
|
|
137
138
|
try {
|
|
@@ -146,7 +147,7 @@ async function airtableRequest(method, path, body, label) {
|
|
|
146
147
|
} catch (error) {
|
|
147
148
|
throw toAirtableHttpError(error);
|
|
148
149
|
}
|
|
149
|
-
}, label);
|
|
150
|
+
}, label, retryOptions);
|
|
150
151
|
} catch (error) {
|
|
151
152
|
logger.error(`[${label}] Failed`, { ...safeAirtableFailure(error), airtableError: error.error });
|
|
152
153
|
throw error;
|
|
@@ -181,6 +182,15 @@ async function scanRecordPages(baseID, tableId, { filterByFormula, fieldIds, onP
|
|
|
181
182
|
}
|
|
182
183
|
}
|
|
183
184
|
|
|
185
|
+
// A network error is not retried: the delete may have landed, so the caller re-reads to learn what is gone.
|
|
186
|
+
async function deleteRecords(baseID, tableId, recordIds) {
|
|
187
|
+
if (!recordIds?.length || recordIds.length > MAX_DELETE_BATCH) throw new Error(`deleteRecords takes 1 to ${MAX_DELETE_BATCH} record ids`);
|
|
188
|
+
if (isShadowRun() || isEvalMode) throw new Error('deleteRecords is refused in shadow and eval mode');
|
|
189
|
+
const query = recordIds.map((id) => `records[]=${encodeURIComponent(id)}`).join('&');
|
|
190
|
+
const data = await airtableRequest('delete', `${baseID}/${tableId}?${query}`, undefined, 'deleteRecords', { retryNetworkErrors: false });
|
|
191
|
+
return (data?.records || []).filter((record) => record.deleted).map((record) => record.id);
|
|
192
|
+
}
|
|
193
|
+
|
|
184
194
|
// Needs the schema.bases:read scope; returns [{ id, name, fields: [{ id, name, type }] }] per table.
|
|
185
195
|
async function getBaseSchema(baseID) {
|
|
186
196
|
const data = await airtableRequest('get', `meta/bases/${baseID}/tables`, undefined, 'getBaseSchema');
|
|
@@ -321,6 +331,7 @@ module.exports = {
|
|
|
321
331
|
getRecords,
|
|
322
332
|
getRecordByFilter,
|
|
323
333
|
scanRecordPages,
|
|
334
|
+
deleteRecords,
|
|
324
335
|
getBaseSchema,
|
|
325
336
|
updateRecordByFilter,
|
|
326
337
|
addLinkedRecord,
|