@peopl-health/nexus 5.77.1 → 5.78.0-dev.16570

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,8 +3,11 @@ 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
+ const ARCHIVE_SOURCE_KINDS = ['live', 'copy', 'export'];
9
+ // Database and collection names: lowercase letters, digits and underscores, as derived by `storeName`.
10
+ const STORE_NAME_PATTERN = /^[a-z0-9_]{1,63}$/;
8
11
 
9
12
  const archivedAttachmentSchema = new mongoose.Schema({
10
13
  field: { type: String, required: true },
@@ -30,20 +33,28 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
30
33
  recordId: { type: String, default: null },
31
34
  whatsappId: { type: String, default: null },
32
35
  },
33
- groupId: { type: String, required: true },
36
+ // Set when the planner archived the record with its triage group; rows copied whole carry none.
37
+ groupId: { type: String, default: null },
34
38
  // The schema snapshot whose field names key `fields`, so a later rename can be mapped back by field id.
35
39
  schemaId: { type: String, required: true },
36
40
  attachments: { type: [archivedAttachmentSchema], default: [] },
41
+ // Where `fields` were read: the live base, or a dated copy of it holding rows the live base no longer has.
42
+ source: {
43
+ kind: { type: String, enum: ARCHIVE_SOURCE_KINDS, default: 'live' },
44
+ baseId: { type: String, default: null },
45
+ },
37
46
  runId: { type: String, required: true },
38
47
  archivedAt: { type: Date, required: true },
39
48
  sourceDeletedAt: { type: Date, default: null },
49
+ deleteRunId: { type: String, default: null },
40
50
  schemaVersion: { type: Number, required: true, default: ARCHIVE_SCHEMA_VERSION },
41
- }, { collection: 'airtable_archive_records', minimize: false, versionKey: false });
51
+ }, { minimize: false, versionKey: false });
42
52
 
43
- airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, 'patient.whatsappId': 1, createdTime: -1 });
44
- airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, 'patient.recordId': 1, createdTime: -1 });
45
- airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, createdTime: -1 });
46
- airtableArchiveRecordSchema.index({ baseId: 1, groupId: 1 });
53
+ // One collection per table, so no index needs the base or the table.
54
+ airtableArchiveRecordSchema.index({ 'patient.whatsappId': 1, createdTime: -1 });
55
+ airtableArchiveRecordSchema.index({ 'patient.recordId': 1, createdTime: -1 });
56
+ airtableArchiveRecordSchema.index({ createdTime: -1 });
57
+ airtableArchiveRecordSchema.index({ groupId: 1 });
47
58
  airtableArchiveRecordSchema.index({ runId: 1 });
48
59
 
49
60
  const tableCountsSchema = new mongoose.Schema({
@@ -53,6 +64,19 @@ const tableCountsSchema = new mongoose.Schema({
53
64
  refreshed: { type: Number, default: 0 },
54
65
  verified: { type: Number, default: 0 },
55
66
  failed: { type: Number, default: 0 },
67
+ skipped: { type: Number, default: 0 },
68
+ stamped: { type: Number, default: 0 },
69
+ deleted: { type: Number, default: 0 },
70
+ }, { _id: false });
71
+
72
+ // One eligible group as the plan saw it, so a later delete can name exactly the groups that were reviewed.
73
+ const plannedGroupSchema = new mongoose.Schema({
74
+ groupId: { type: String, required: true },
75
+ // Every patient of the group's records: a shared questionnaire can join two patients.
76
+ patientRecordIds: { type: [String], default: [] },
77
+ // None of them has a patient-linked questionnaire or triage since the cutoff.
78
+ inactive: { type: Boolean, required: true },
79
+ records: { type: Map, of: Number, default: {} },
56
80
  }, { _id: false });
57
81
 
58
82
  const airtableArchiveRunSchema = new mongoose.Schema({
@@ -69,6 +93,14 @@ const airtableArchiveRunSchema = new mongoose.Schema({
69
93
  kept: { type: Map, of: Number, default: {} },
70
94
  },
71
95
  tables: { type: Map, of: tableCountsSchema, default: {} },
96
+ eligibleGroups: { type: [plannedGroupSchema], default: [] },
97
+ requestedGroupIds: { type: [String], default: [] },
98
+ groups: {
99
+ requested: { type: Number, default: 0 },
100
+ notEligible: { type: Number, default: 0 },
101
+ unverified: { type: Number, default: 0 },
102
+ deleted: { type: Number, default: 0 },
103
+ },
72
104
  errorCode: { type: String, default: null },
73
105
  }, { collection: 'airtable_archive_runs', minimize: false, timestamps: true });
74
106
 
@@ -83,16 +115,26 @@ const airtableArchiveSchemaSchema = new mongoose.Schema({
83
115
  capturedAt: { type: Date, required: true },
84
116
  }, { collection: 'airtable_archive_schemas', minimize: false, versionKey: false });
85
117
 
118
+ // Which collection holds a table, pinned at its first write so renaming the table in Airtable never moves its records.
119
+ const airtableArchiveTableSchema = new mongoose.Schema({
120
+ _id: { type: String, required: true },
121
+ baseId: { type: String, required: true },
122
+ tableId: { type: String, required: true },
123
+ // The table's current Airtable name, kept up to date by writers so readers find a renamed table.
124
+ tableName: { type: String, default: null },
125
+ dbName: { type: String, required: true },
126
+ collectionName: { type: String, required: true },
127
+ pinnedAt: { type: Date, required: true },
128
+ }, { collection: 'airtable_archive_tables', minimize: false, versionKey: false });
129
+
130
+ airtableArchiveTableSchema.index({ dbName: 1, collectionName: 1 }, { unique: true });
131
+ airtableArchiveTableSchema.index({ baseId: 1, tableName: 1 });
132
+
86
133
  const getDatabase = (modelName) => {
87
134
  const dbName = getModelDatabase(modelName);
88
135
  return dbName ? getDb(dbName) : mongoose;
89
136
  };
90
137
 
91
- const getAirtableArchiveRecord = () => {
92
- const db = getDatabase('AirtableArchiveRecord');
93
- return db.models.AirtableArchiveRecord || db.model('AirtableArchiveRecord', airtableArchiveRecordSchema);
94
- };
95
-
96
138
  const getAirtableArchiveRun = () => {
97
139
  const db = getDatabase('AirtableArchiveRun');
98
140
  return db.models.AirtableArchiveRun || db.model('AirtableArchiveRun', airtableArchiveRunSchema);
@@ -103,14 +145,86 @@ const getAirtableArchiveSchema = () => {
103
145
  return db.models.AirtableArchiveSchema || db.model('AirtableArchiveSchema', airtableArchiveSchemaSchema);
104
146
  };
105
147
 
106
- const archiveRecordId = (baseId, recordId) => `${baseId}:${recordId}`;
148
+ const getAirtableArchiveTable = () => {
149
+ const db = getDatabase('AirtableArchiveTable');
150
+ return db.models.AirtableArchiveTable || db.model('AirtableArchiveTable', airtableArchiveTableSchema);
151
+ };
152
+
153
+ const DUPLICATE_KEY_ERROR = 11000;
154
+ const storeError = (code) => Object.assign(new Error(code), { code });
155
+
156
+ // Airtable names as Mongo names: accents dropped, lowercase, every run of other characters one underscore.
157
+ const storeName = (name) => String(name).normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase()
158
+ .replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
159
+
160
+ // The host names each base's database, e.g. `AirtableBase:appX` → `symptoms`; an unmapped base has nowhere to go.
161
+ const baseDatabaseKey = (baseId) => `AirtableBase:${baseId}`;
162
+
163
+ function baseDatabase(baseId) {
164
+ const db = getModelDatabase(baseDatabaseKey(baseId));
165
+ if (!db || !STORE_NAME_PATTERN.test(db)) throw storeError('archive_base_unmapped');
166
+ return db;
167
+ }
168
+
169
+ function recordModel(db, collection) {
170
+ const connection = getDb(db);
171
+ const name = `AirtableRecord.${collection}`;
172
+ return connection.models[name] || connection.model(name, airtableArchiveRecordSchema, collection);
173
+ }
174
+
175
+ const pinnedCollections = new Map();
176
+
177
+ async function pinCollection({ baseId, tableId, tableName, db }) {
178
+ const Table = getAirtableArchiveTable();
179
+ // Uniqueness of a collection rests on the registry index, so nothing is pinned before it exists.
180
+ await Table.init();
181
+ const _id = `${baseId}:${tableId}`;
182
+ const collectionName = storeName(tableName);
183
+ if (!STORE_NAME_PATTERN.test(collectionName)) throw storeError('archive_collection_invalid');
184
+ try {
185
+ await Table.updateOne(
186
+ { _id }, { $set: { tableName }, $setOnInsert: { baseId, tableId, dbName: db, collectionName, pinnedAt: new Date() } }, { upsert: true },
187
+ );
188
+ } catch (error) {
189
+ if (error?.code === DUPLICATE_KEY_ERROR) throw storeError('archive_collection_taken');
190
+ throw error;
191
+ }
192
+ const pinned = await Table.findOne({ _id }).lean();
193
+ if (pinned?.dbName !== db) throw storeError('archive_base_moved');
194
+ return pinned.collectionName;
195
+ }
196
+
197
+ // The collection a writer stores one table's records in, pinning it on first use.
198
+ async function getAirtableTableRecords({ baseId, tableId, tableName }) {
199
+ const db = baseDatabase(baseId);
200
+ const key = `${db}:${baseId}:${tableId}:${tableName}`;
201
+ if (!pinnedCollections.has(key)) {
202
+ pinnedCollections.set(key, pinCollection({ baseId, tableId, tableName, db }).catch((error) => {
203
+ pinnedCollections.delete(key);
204
+ throw error;
205
+ }));
206
+ }
207
+ return recordModel(db, await pinnedCollections.get(key));
208
+ }
209
+
210
+ // Readers name a table as Airtable does now; one never written has no collection, so nothing of it is archived.
211
+ async function findAirtableTableRecords({ baseId, tableName }) {
212
+ const db = baseDatabase(baseId);
213
+ const pinned = await getAirtableArchiveTable().findOne({ baseId, dbName: db, tableName }, { collectionName: 1 }).lean();
214
+ return pinned ? recordModel(db, pinned.collectionName) : null;
215
+ }
107
216
 
108
217
  module.exports = {
109
218
  ARCHIVE_SCHEMA_VERSION,
110
219
  ARCHIVE_RUN_MODES,
220
+ ARCHIVE_SOURCE_KINDS,
111
221
  airtableArchiveRecordSchema,
112
- getAirtableArchiveRecord,
222
+ airtableArchiveTableSchema,
113
223
  getAirtableArchiveRun,
114
224
  getAirtableArchiveSchema,
115
- archiveRecordId,
225
+ getAirtableArchiveTable,
226
+ getAirtableTableRecords,
227
+ findAirtableTableRecords,
228
+ baseDatabaseKey,
229
+ storeName,
116
230
  };
@@ -1,16 +1,9 @@
1
- const { getModelDatabase } = require('../config/mongoConfig');
2
- const { getAirtableArchiveRecord, archiveRecordId } = require('../models/airtableArchiveModel');
1
+ const { findAirtableTableRecords } = require('../models/airtableArchiveModel');
3
2
  const { toAirtableRow } = require('../helpers/airtableArchiveHelper');
4
3
 
5
4
  // Only rows already deleted from Airtable: a copy whose source is still live must never reach a reader.
6
5
  const DELETED_FROM_SOURCE = { sourceDeletedAt: { $ne: null } };
7
6
 
8
- // Unmapped, the model would fall back to the default database and every read would come back empty.
9
- function archiveRecords() {
10
- if (!getModelDatabase('AirtableArchiveRecord')) throw new Error('AirtableArchiveRecord db not mapped (setModelDatabases)');
11
- return getAirtableArchiveRecord();
12
- }
13
-
14
7
  function readProjection({ fields, withAttachments = false } = {}) {
15
8
  const projection = { recordId: 1, createdTime: 1 };
16
9
  if (fields?.length) fields.forEach((name) => { projection[`fields.${name}`] = 1; });
@@ -21,25 +14,30 @@ function readProjection({ fields, withAttachments = false } = {}) {
21
14
 
22
15
  async function findArchivedByPatient({ baseId, tableName, whatsappId, patientRecordId, since, fields, withAttachments }) {
23
16
  if (!whatsappId && !patientRecordId) return [];
24
- const query = { baseId, tableName, ...DELETED_FROM_SOURCE };
17
+ const Records = await findAirtableTableRecords({ baseId, tableName });
18
+ if (!Records) return [];
19
+ const query = { ...DELETED_FROM_SOURCE };
25
20
  if (patientRecordId) query['patient.recordId'] = patientRecordId;
26
21
  else query['patient.whatsappId'] = whatsappId;
27
22
  if (since) query.createdTime = { $gte: since };
28
- const docs = await archiveRecords().find(query, readProjection({ fields, withAttachments })).sort({ createdTime: -1 }).lean();
23
+ const docs = await Records.find(query, readProjection({ fields, withAttachments })).sort({ createdTime: -1 }).lean();
29
24
  return docs.map(toAirtableRow);
30
25
  }
31
26
 
32
27
  async function findArchivedByRecordIds({ baseId, tableName, recordIds, fields, withAttachments }) {
33
28
  if (!recordIds?.length) return [];
34
- const query = { _id: { $in: recordIds.map((id) => archiveRecordId(baseId, id)) }, tableName, ...DELETED_FROM_SOURCE };
35
- const docs = await archiveRecords().find(query, readProjection({ fields, withAttachments })).lean();
29
+ const Records = await findAirtableTableRecords({ baseId, tableName });
30
+ if (!Records) return [];
31
+ const docs = await Records.find({ _id: { $in: recordIds }, ...DELETED_FROM_SOURCE }, readProjection({ fields, withAttachments })).lean();
36
32
  return docs.map(toAirtableRow);
37
33
  }
38
34
 
39
35
  async function findArchivedByTable({ baseId, tableName, since, fields }) {
40
- const query = { baseId, tableName, ...DELETED_FROM_SOURCE };
36
+ const Records = await findAirtableTableRecords({ baseId, tableName });
37
+ if (!Records) return [];
38
+ const query = { ...DELETED_FROM_SOURCE };
41
39
  if (since) query.createdTime = { $gte: since };
42
- const docs = await archiveRecords().find(query, readProjection({ fields })).sort({ createdTime: -1 }).lean();
40
+ const docs = await Records.find(query, readProjection({ fields })).sort({ createdTime: -1 }).lean();
43
41
  return docs.map(toAirtableRow);
44
42
  }
45
43
 
@@ -5,17 +5,18 @@ 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');
11
12
  const { daysSince } = require('../utils/dateUtils');
12
13
  const {
13
- ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRecord, getAirtableArchiveRun, getAirtableArchiveSchema, archiveRecordId,
14
+ ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRun, getAirtableArchiveSchema, getAirtableTableRecords,
14
15
  } = require('../models/airtableArchiveModel');
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,21 +181,45 @@ 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
+ // Each table is its own collection, so a run that writes holds one model per archived table.
185
+ async function tableModels(baseId, schema) {
186
+ const models = new Map();
187
+ for (const table of Object.values(schema.tables)) {
188
+ models.set(table, await getAirtableTableRecords({ baseId, tableId: schema.tableIds[table], tableName: table }));
189
+ }
190
+ return models;
191
+ }
192
+
193
+ const idsByTableOf = (entries) => {
194
+ const idsByTable = new Map();
195
+ entries.forEach(({ table, record }) => idsByTable.set(table, [...(idsByTable.get(table) || []), record.id]));
196
+ return idsByTable;
197
+ };
198
+
199
+ // The stored copies of a batch spanning tables, keyed by record id.
200
+ async function findCopies(models, entries, projection, filter = {}) {
201
+ const copies = new Map();
202
+ for (const [table, ids] of idsByTableOf(entries)) {
203
+ (await models.get(table).find({ _id: { $in: ids }, ...filter }, projection).lean()).forEach((doc) => copies.set(doc._id, doc));
204
+ }
205
+ return copies;
206
+ }
207
+
208
+ const emptyCounts = () => ({ scanned: 0, eligible: 0, copied: 0, refreshed: 0, verified: 0, failed: 0, skipped: 0, stamped: 0, deleted: 0 });
184
209
 
185
210
  const WRITE_REJECTIONS = ['MongoBulkWriteError', 'MongooseBulkWriteError', 'MongoInvalidArgumentError'];
186
211
 
187
- const writeBatch = (ArchiveRecord, ops) => ArchiveRecord.bulkWrite(ops, { ordered: false, throwOnValidationError: true, writeConcern: WRITE_CONCERN });
212
+ const writeBatch = (Records, ops) => Records.bulkWrite(ops, { ordered: false, throwOnValidationError: true, writeConcern: WRITE_CONCERN });
188
213
 
189
214
  // A rejected batch is retried op by op, so one bad record cannot block the rest; the read-back decides each record.
190
- async function writeOps(ArchiveRecord, ops, runId) {
215
+ async function writeOps(Records, ops, runId) {
191
216
  try {
192
- await writeBatch(ArchiveRecord, ops);
217
+ await writeBatch(Records, ops);
193
218
  } catch (error) {
194
219
  if (!WRITE_REJECTIONS.includes(error?.name)) throw error;
195
220
  logger.error('[airtableArchive] Batch write rejected, retrying one by one', { runId, errorName: error?.name || 'UNKNOWN' });
196
221
  for (const op of ops) {
197
- await writeBatch(ArchiveRecord, [op])
222
+ await writeBatch(Records, [op])
198
223
  .catch((opError) => logger.error('[airtableArchive] Record write rejected', { runId, _id: op.updateOne.filter._id, errorName: opError?.name || 'UNKNOWN' }));
199
224
  }
200
225
  }
@@ -224,27 +249,31 @@ const plannerInputs = (record, plannerNames) => stableStringify({
224
249
  // Where readers find a record: a renamed table or a regrouped record is rewritten even when its fields did not change.
225
250
  const placementOf = (tableName, groupId, patient, createdTime) => stableStringify({ tableName, groupId, patient, createdTime: new Date(createdTime).getTime() });
226
251
 
227
- async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease }) {
228
- const ArchiveRecord = getAirtableArchiveRecord();
252
+ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease, models }) {
229
253
  const wholeById = await readWholeRecords(baseId, batch, schema, lease);
230
254
  const changedGroups = new Set(batch.filter(({ table, record: scanned }) => {
231
255
  const whole = wholeById.get(scanned.id);
232
256
  return !whole || plannerInputs(whole, schema.plannerFields[table]) !== plannerInputs(scanned, schema.plannerFields[table]);
233
257
  }).map(({ group }) => group.groupId));
234
- 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
- .map((doc) => [doc._id, doc]));
258
+ const existing = await findCopies(models, batch, {
259
+ fields: 1, fieldsHash: 1, sourceHash: 1, tableId: 1, schemaId: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1, sourceDeletedAt: 1,
260
+ });
237
261
 
238
262
  const expected = new Map();
239
- const ops = [];
263
+ const opsByTable = new Map();
240
264
  for (const { table, record: scanned, group, patient } of batch) {
265
+ // A stamped copy is what readers serve once the delete finishes, so a record a stopped delete left behind keeps it.
266
+ if (existing.get(scanned.id)?.sourceDeletedAt) {
267
+ counts[table].skipped += 1;
268
+ continue;
269
+ }
241
270
  if (changedGroups.has(group.groupId)) {
242
271
  counts[table].failed += 1;
243
272
  logger.error('[airtableArchive] Group changed or gone since the scan', { runId, table, recordId: scanned.id, groupId: group.groupId });
244
273
  continue;
245
274
  }
246
275
  const record = wholeById.get(scanned.id);
247
- const _id = archiveRecordId(baseId, record.id);
276
+ const _id = record.id;
248
277
  const { normalized, attachments } = normalizeFields(record.fields);
249
278
  const fieldsHash = hashFields(normalized);
250
279
  const sourceHash = hashFields(normalized, schema.computed.get(table));
@@ -259,14 +288,15 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
259
288
  try {
260
289
  const alreadyHosted = new Map((previous?.attachments || []).map((a) => [a.id, a]));
261
290
  const hosted = await rehostAttachments({ baseId, tableId, recordId: record.id, attachments, alreadyHosted });
262
- ops.push({
291
+ if (!opsByTable.has(table)) opsByTable.set(table, []);
292
+ opsByTable.get(table).push({
263
293
  updateOne: {
264
294
  filter: { _id },
265
295
  update: {
266
296
  $set: {
267
297
  baseId, tableId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
268
298
  fields: normalized, fieldsHash, sourceHash, patient, groupId: group.groupId, schemaId, attachments: hosted,
269
- schemaVersion: ARCHIVE_SCHEMA_VERSION,
299
+ source: { kind: 'live', baseId }, schemaVersion: ARCHIVE_SCHEMA_VERSION,
270
300
  },
271
301
  $setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
272
302
  },
@@ -283,10 +313,11 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
283
313
  if (attachments.length) await renewLease(runId);
284
314
  }
285
315
 
286
- if (ops.length) await writeOps(ArchiveRecord, ops, runId);
316
+ for (const [table, ops] of opsByTable) await writeOps(models.get(table), ops, runId);
287
317
 
288
- const stored = await ArchiveRecord.find({ _id: { $in: [...expected.keys()] } }, { fields: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1 }).lean();
289
- const storedById = new Map(stored.map((doc) => [doc._id, doc]));
318
+ const storedById = await findCopies(
319
+ models, [...expected.values()].map(({ table, recordId }) => ({ table, record: { id: recordId } })), { fields: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1 },
320
+ );
290
321
  for (const [_id, { table, recordId, fieldsHash, placement }] of expected) {
291
322
  const doc = storedById.get(_id);
292
323
  if (doc && hashFields(doc.fields) === fieldsHash && placementOf(doc.tableName, doc.groupId, doc.patient, doc.createdTime) === placement) counts[table].verified += 1;
@@ -297,6 +328,137 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
297
328
  }
298
329
  }
299
330
 
331
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
332
+
333
+ const linkNamesOf = (schema, table) => schema.snapshot.find((t) => t.name === table).fields.filter((f) => LINK_FIELD_TYPES.includes(f.type)).map((f) => f.name);
334
+
335
+ // Airtable drops links to a deleted record, so a link that lost only records gone from Airtable with a stamped copy reads as before.
336
+ function restoreDeletedLinks(fields, reference, linkNames, goneIds) {
337
+ const restored = { ...fields };
338
+ for (const name of linkNames) {
339
+ const before = reference[name] || [];
340
+ const after = fields[name] || [];
341
+ const lost = before.filter((id) => !after.includes(id));
342
+ if (lost.length && lost.every((id) => goneIds.has(id)) && after.every((id) => before.includes(id))) restored[name] = reference[name];
343
+ }
344
+ return restored;
345
+ }
346
+
347
+ // Why a record must stay in Airtable, or null when its archived copy can stand in for it.
348
+ function deleteBlocker({ whole, scanned, doc, table, group, patient, schema, goneIds }) {
349
+ if (!whole) return 'gone_from_source';
350
+ const linkNames = linkNamesOf(schema, table);
351
+ const asScanned = { ...whole, fields: restoreDeletedLinks(whole.fields, scanned.fields, linkNames, goneIds) };
352
+ if (plannerInputs(asScanned, schema.plannerFields[table]) !== plannerInputs(scanned, schema.plannerFields[table])) return 'changed_since_scan';
353
+ if (!doc) return 'not_archived';
354
+ if (hashFields(doc.fields) !== doc.fieldsHash) return 'copy_damaged';
355
+ const { normalized, attachments } = normalizeFields(whole.fields);
356
+ if (doc.sourceHash !== hashFields(restoreDeletedLinks(normalized, doc.fields, linkNames, goneIds), schema.computed.get(table))) return 'source_edited';
357
+ if (placementOf(doc.tableName, doc.groupId, doc.patient, doc.createdTime) !== placementOf(table, group.groupId, patient, whole.createdTime)) return 'placement_changed';
358
+ const hosted = new Set((doc.attachments || []).map((a) => a.id));
359
+ if (attachments.some(({ item }) => !hosted.has(item.id))) return 'attachment_not_hosted';
360
+ return null;
361
+ }
362
+
363
+ // The request may have landed even when it failed, so what is still in Airtable decides.
364
+ async function deleteChunk({ baseId, runId, tableId, recordIds, schema, lease }) {
365
+ try {
366
+ if ((await deleteRecords(baseId, tableId, recordIds)).length === recordIds.length) return;
367
+ } catch (error) {
368
+ logger.warn('[airtableArchive] Delete request failed, re-reading what is left', { runId, tableId, statusCode: error?.statusCode || null });
369
+ }
370
+ const left = await scanTable({ baseId, tableId, filterByFormula: recordIdIn(recordIds), schema, lease });
371
+ if (left.length) throw archiveError('archive_delete_failed');
372
+ }
373
+
374
+ const ARCHIVED_PROJECTION = { fields: 1, fieldsHash: 1, sourceHash: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1 };
375
+
376
+ // Linked records missing from Airtable whose copies were stamped deleted; only records the scan covers count, so missing means gone.
377
+ async function goneLinkedIds({ entries, wholeById, archived, schema, liveIds, cutoff, models }) {
378
+ const missing = new Set();
379
+ for (const { table, record: scanned } of entries) {
380
+ const whole = wholeById.get(scanned.id);
381
+ const doc = archived.get(scanned.id);
382
+ for (const name of linkNamesOf(schema, table)) {
383
+ [...(scanned.fields[name] || []), ...(doc?.fields?.[name] || [])]
384
+ .filter((id) => !(whole?.fields[name] || []).includes(id) && !liveIds.has(id)).forEach((id) => missing.add(id));
385
+ }
386
+ }
387
+ if (!missing.size) return new Set();
388
+ // A link names no table, so every archived table is asked.
389
+ const gone = new Set();
390
+ for (const Records of models.values()) {
391
+ (await Records.find({ _id: { $in: [...missing] }, sourceDeletedAt: { $ne: null }, createdTime: { $lt: cutoff } }, { _id: 1 }).lean()).forEach((doc) => gone.add(doc._id));
392
+ }
393
+ return gone;
394
+ }
395
+
396
+ async function findBlockers({ baseId, entries, schema, lease, liveIds, cutoff, models }) {
397
+ const wholeById = await readWholeRecords(baseId, entries, schema, lease);
398
+ const archived = await findCopies(models, entries, ARCHIVED_PROJECTION);
399
+ const goneIds = await goneLinkedIds({ entries, wholeById, archived, schema, liveIds, cutoff, models });
400
+ return entries.map((entry) => ({
401
+ entry,
402
+ reason: deleteBlocker({
403
+ whole: wholeById.get(entry.record.id), scanned: entry.record, doc: archived.get(entry.record.id), ...entry, schema, goneIds,
404
+ }),
405
+ })).filter(({ reason }) => reason);
406
+ }
407
+
408
+ // Every record of a verified group is stamped deleted in the archive before Airtable deletes it, so readers never miss it.
409
+ async function deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff, models }) {
410
+ const blocked = new Set();
411
+ for (const { entry: { table, record, group }, reason } of await findBlockers({ baseId, entries: batch, schema, lease, liveIds, cutoff, models })) {
412
+ blocked.add(group.groupId);
413
+ logger.error('[airtableArchive] Group kept in Airtable: its copy cannot stand in for the source', { runId, table, recordId: record.id, groupId: group.groupId, reason });
414
+ }
415
+ groups.unverified += blocked.size;
416
+ const verified = batch.filter(({ group }) => !blocked.has(group.groupId));
417
+ if (!verified.length) return;
418
+
419
+ const stampedAt = new Date();
420
+ for (const [table, ids] of idsByTableOf(verified)) {
421
+ await models.get(table).updateMany(
422
+ { _id: { $in: ids }, sourceDeletedAt: null },
423
+ { $set: { sourceDeletedAt: stampedAt, deleteRunId: runId } },
424
+ { writeConcern: WRITE_CONCERN },
425
+ );
426
+ }
427
+ const stamped = await findCopies(models, verified, { _id: 1 }, { sourceDeletedAt: { $ne: null } });
428
+ if (stamped.size !== verified.length) throw archiveError('archive_stamp_failed');
429
+ verified.forEach(({ table }) => { counts[table].stamped += 1; });
430
+
431
+ for (const tableId of ARCHIVE_DELETE_ORDER) {
432
+ const entries = verified.filter(({ table }) => schema.tableIds[table] === tableId);
433
+ for (let i = 0; i < entries.length; i += 10) {
434
+ const chunk = entries.slice(i, i + 10);
435
+ // Re-checked right before its request, so an edit made while earlier chunks were deleted stops the run with its copy stamped.
436
+ const changed = await findBlockers({ baseId, entries: chunk, schema, lease, liveIds, cutoff, models });
437
+ if (changed.length) {
438
+ changed.forEach(({ entry: { table, record, group }, reason }) => logger.error('[airtableArchive] Record changed during the delete', { runId, table, recordId: record.id, groupId: group.groupId, reason }));
439
+ throw archiveError('archive_changed_during_delete');
440
+ }
441
+ await deleteChunk({ baseId, runId, tableId, recordIds: chunk.map(({ record }) => record.id), schema, lease });
442
+ chunk.forEach(({ table, record }) => {
443
+ counts[table].deleted += 1;
444
+ liveIds.delete(record.id);
445
+ });
446
+ await lease.renewIfDue();
447
+ await delay(ARCHIVE_DELETE_SPACING_MS);
448
+ }
449
+ }
450
+ if ((await readWholeRecords(baseId, verified, schema, lease)).size) throw archiveError('archive_delete_incomplete');
451
+ groups.deleted += new Set(verified.map(({ group }) => group.groupId)).size;
452
+ }
453
+
454
+ function plannedGroup(group, patientsWithRecent) {
455
+ const patientRecordIds = [...new Set(group.records.map(({ patient }) => patient?.recordId).filter(Boolean))];
456
+ const records = {};
457
+ group.records.forEach(({ table }) => { records[table] = (records[table] || 0) + 1; });
458
+ const isInactive = (patientId) => Object.values(patientsWithRecent).every((patients) => !patients.has(patientId));
459
+ return { groupId: group.groupId, patientRecordIds, inactive: patientRecordIds.length > 0 && patientRecordIds.every(isInactive), records };
460
+ }
461
+
300
462
  // Batches never split a group, so a changed record holds back its whole group.
301
463
  function groupBatches(groups) {
302
464
  const batches = [];
@@ -312,19 +474,25 @@ function groupBatches(groups) {
312
474
  return batches;
313
475
  }
314
476
 
315
- function validateRequest({ baseId, cutoff, mode, now }) {
477
+ function validateRequest({ baseId, cutoff, mode, now, groupIds }) {
316
478
  if (!baseId) throw archiveError('archive_base_required');
317
479
  if (!ARCHIVE_RUN_MODES.includes(mode)) throw archiveError('archive_mode_invalid');
480
+ if (mode === 'delete') {
481
+ const valid = Array.isArray(groupIds) && groupIds.length > 0 && groupIds.length <= ARCHIVE_DELETE_MAX_GROUPS
482
+ && groupIds.every((id) => typeof id === 'string' && id) && new Set(groupIds).size === groupIds.length;
483
+ if (!valid) throw archiveError('archive_delete_groups_invalid');
484
+ }
318
485
  if (!(cutoff instanceof Date) || Number.isNaN(cutoff.getTime())) throw archiveError('archive_cutoff_invalid');
319
486
  if (daysSince(cutoff, now.getTime()) < MIN_ARCHIVE_AGE_DAYS) throw archiveError('archive_cutoff_too_recent');
320
487
  }
321
488
 
322
- // Copies archivable groups older than `cutoff` into Mongo and verifies them; never deletes from Airtable.
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 });
489
+ // `plan` and `copy` never delete from Airtable; `delete` removes only the named groups that are still eligible and verified.
490
+ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date(), groupIds = [] }) {
491
+ validateRequest({ baseId, cutoff, mode, now, groupIds });
492
+ const run = await acquireRun({ baseId, mode, cutoff, now, groupIds: mode === 'delete' ? groupIds : [] });
326
493
  const { runId } = run;
327
494
  let counts = {};
495
+ const groups = { requested: mode === 'delete' ? groupIds.length : 0, notEligible: 0, unverified: 0, deleted: 0 };
328
496
 
329
497
  try {
330
498
  const schema = await readArchiveSchema(baseId);
@@ -340,28 +508,46 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
340
508
  const work = plan.eligible.map((group) => group.records.map(({ table, id, patient }) => ({ table, record: recordsById.get(id), group, patient })));
341
509
  work.flat().forEach(({ table }) => { counts[table].eligible += 1; });
342
510
 
511
+ const models = mode === 'plan' ? null : await tableModels(baseId, schema);
343
512
  if (mode === 'copy' && work.length) {
344
513
  const schemaId = await storeSchemaSnapshot(baseId, schema.snapshot, now);
345
514
  for (const batch of groupBatches(work)) {
346
- await copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease });
515
+ await copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease, models });
516
+ await renewLease(runId);
517
+ }
518
+ }
519
+
520
+ if (mode === 'delete') {
521
+ const requested = new Set(groupIds);
522
+ const targets = work.filter(([{ group }]) => requested.has(group.groupId));
523
+ groups.notEligible = requested.size - targets.length;
524
+ const liveIds = new Set(recordsById.keys());
525
+ for (const batch of groupBatches(targets)) {
526
+ await deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff, models });
347
527
  await renewLease(runId);
348
528
  }
349
529
  }
350
530
 
531
+ // Only a plan stores its groups: a copy run's list would include groups it held back, so slices are picked from plans.
532
+ const eligibleGroups = mode === 'plan' ? plan.eligible.map((group) => plannedGroup(group, patientsWithRecent)) : [];
351
533
  const failed = Object.values(counts).reduce((sum, c) => sum + c.failed, 0);
534
+ // A delete that left any named group in Airtable is not a finished slice.
535
+ const errorCode = (failed && 'records_failed') || ((groups.notEligible || groups.unverified) && 'groups_not_deleted') || null;
352
536
  const summary = {
353
- runId, mode, cutoff, status: failed ? 'failed' : 'succeeded',
354
- components: { eligible: plan.eligible.length, kept: plan.keptByReason }, tables: counts,
537
+ runId, mode, cutoff, status: errorCode ? 'failed' : 'succeeded',
538
+ components: { eligible: plan.eligible.length, kept: plan.keptByReason }, tables: counts, groups,
355
539
  };
356
540
  const finished = await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, {
357
- $set: { status: summary.status, finishedAt: new Date(), components: summary.components, tables: counts, errorCode: failed ? 'records_failed' : null },
541
+ $set: {
542
+ status: summary.status, finishedAt: new Date(), components: summary.components, tables: counts, eligibleGroups, groups, errorCode,
543
+ },
358
544
  });
359
545
  if (!finished?.matchedCount) throw archiveError('archive_lease_lost');
360
546
  logger.info('[airtableArchive] Run finished', summary);
361
547
  return summary;
362
548
  } catch (error) {
363
549
  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 } });
550
+ await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, groups, errorCode } });
365
551
  logger.error('[airtableArchive] Run failed', { runId, mode, errorCode });
366
552
  throw error;
367
553
  }
@@ -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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.77.1",
3
+ "version": "5.78.0-dev.16570",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",