@peopl-health/nexus 5.78.0-dev.16561 → 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.
|
@@ -44,6 +44,7 @@ const { buildTriageResponse } = require('../../fhir/helpers/triagePayloadHelper'
|
|
|
44
44
|
const { keyOf } = require('../../fhir/helpers/symptomAliasHelper');
|
|
45
45
|
const { getCatalog } = require('../../fhir/services/terminologyService');
|
|
46
46
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
47
|
+
const { findArchivedByRecordIds } = require('../../services/airtableArchiveReadService');
|
|
47
48
|
const { RecommendationPlan } = require('../../shared/dtos/RecommendationPlan');
|
|
48
49
|
const { recommendationId } = require('../../fhir/helpers/recommendationIds');
|
|
49
50
|
const { RecommendationSafetyGate } = require('../../shared/dtos/RecommendationSafetyGate');
|
|
@@ -1130,8 +1131,9 @@ async function readPriorResolutions(adherence = [], patientRecordId = null) {
|
|
|
1130
1131
|
.filter((id) => /^rec[A-Za-z0-9]+$/.test(id || ''));
|
|
1131
1132
|
if (!ids.length) return [];
|
|
1132
1133
|
const formula = `OR(${ids.map((id) => `{recordID}='${id}'`).join(',')})`;
|
|
1133
|
-
const
|
|
1134
|
-
if (!
|
|
1134
|
+
const live = await getRecordByFilter(Symptoms_ID, 'cluster_resolutions', formula).catch(() => null);
|
|
1135
|
+
if (!live) return [];
|
|
1136
|
+
const rows = [...live, ...await readArchivedResolutions(ids.filter((id) => !live.some((row) => row.recordID === id)))];
|
|
1135
1137
|
if (!patientRecordId && rows.length) {
|
|
1136
1138
|
logger.warn('[triageRecommendation] prior resolutions unverified: payload carries no patientRecordId', { count: rows.length });
|
|
1137
1139
|
}
|
|
@@ -1145,6 +1147,17 @@ async function readPriorResolutions(adherence = [], patientRecordId = null) {
|
|
|
1145
1147
|
.filter(Boolean);
|
|
1146
1148
|
}
|
|
1147
1149
|
|
|
1150
|
+
// A resolution deleted from Airtable is read from its archived copy; an unreadable archive only loses that context.
|
|
1151
|
+
async function readArchivedResolutions(ids) {
|
|
1152
|
+
if (!ids.length) return [];
|
|
1153
|
+
try {
|
|
1154
|
+
return await findArchivedByRecordIds({ baseId: Symptoms_ID, tableName: 'cluster_resolutions', recordIds: ids });
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
logger.warn('[triageRecommendation] archived prior resolutions unreadable', { count: ids.length, error: error?.message });
|
|
1157
|
+
return [];
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1148
1161
|
function ownedByPatient(row, patientRecordId) {
|
|
1149
1162
|
const owners = Array.isArray(row[PATIENT_LOOKUP_FIELD]) ? row[PATIENT_LOOKUP_FIELD] : [];
|
|
1150
1163
|
if (owners.includes(patientRecordId)) return true;
|
|
@@ -5,6 +5,9 @@ const { getDb, getModelDatabase } = require('../config/mongoConfig');
|
|
|
5
5
|
const ARCHIVE_SCHEMA_VERSION = 1;
|
|
6
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,21 +33,28 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
|
|
|
30
33
|
recordId: { type: String, default: null },
|
|
31
34
|
whatsappId: { type: String, default: null },
|
|
32
35
|
},
|
|
33
|
-
|
|
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 },
|
|
40
49
|
deleteRunId: { type: String, default: null },
|
|
41
50
|
schemaVersion: { type: Number, required: true, default: ARCHIVE_SCHEMA_VERSION },
|
|
42
|
-
}, {
|
|
51
|
+
}, { minimize: false, versionKey: false });
|
|
43
52
|
|
|
44
|
-
|
|
45
|
-
airtableArchiveRecordSchema.index({
|
|
46
|
-
airtableArchiveRecordSchema.index({
|
|
47
|
-
airtableArchiveRecordSchema.index({
|
|
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 });
|
|
48
58
|
airtableArchiveRecordSchema.index({ runId: 1 });
|
|
49
59
|
|
|
50
60
|
const tableCountsSchema = new mongoose.Schema({
|
|
@@ -105,16 +115,26 @@ const airtableArchiveSchemaSchema = new mongoose.Schema({
|
|
|
105
115
|
capturedAt: { type: Date, required: true },
|
|
106
116
|
}, { collection: 'airtable_archive_schemas', minimize: false, versionKey: false });
|
|
107
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
|
+
|
|
108
133
|
const getDatabase = (modelName) => {
|
|
109
134
|
const dbName = getModelDatabase(modelName);
|
|
110
135
|
return dbName ? getDb(dbName) : mongoose;
|
|
111
136
|
};
|
|
112
137
|
|
|
113
|
-
const getAirtableArchiveRecord = () => {
|
|
114
|
-
const db = getDatabase('AirtableArchiveRecord');
|
|
115
|
-
return db.models.AirtableArchiveRecord || db.model('AirtableArchiveRecord', airtableArchiveRecordSchema);
|
|
116
|
-
};
|
|
117
|
-
|
|
118
138
|
const getAirtableArchiveRun = () => {
|
|
119
139
|
const db = getDatabase('AirtableArchiveRun');
|
|
120
140
|
return db.models.AirtableArchiveRun || db.model('AirtableArchiveRun', airtableArchiveRunSchema);
|
|
@@ -125,14 +145,86 @@ const getAirtableArchiveSchema = () => {
|
|
|
125
145
|
return db.models.AirtableArchiveSchema || db.model('AirtableArchiveSchema', airtableArchiveSchemaSchema);
|
|
126
146
|
};
|
|
127
147
|
|
|
128
|
-
const
|
|
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
|
+
}
|
|
129
216
|
|
|
130
217
|
module.exports = {
|
|
131
218
|
ARCHIVE_SCHEMA_VERSION,
|
|
132
219
|
ARCHIVE_RUN_MODES,
|
|
220
|
+
ARCHIVE_SOURCE_KINDS,
|
|
133
221
|
airtableArchiveRecordSchema,
|
|
134
|
-
|
|
222
|
+
airtableArchiveTableSchema,
|
|
135
223
|
getAirtableArchiveRun,
|
|
136
224
|
getAirtableArchiveSchema,
|
|
137
|
-
|
|
225
|
+
getAirtableArchiveTable,
|
|
226
|
+
getAirtableTableRecords,
|
|
227
|
+
findAirtableTableRecords,
|
|
228
|
+
baseDatabaseKey,
|
|
229
|
+
storeName,
|
|
138
230
|
};
|
|
@@ -1,16 +1,9 @@
|
|
|
1
|
-
const {
|
|
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
|
|
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
|
|
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
|
|
35
|
-
|
|
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
|
|
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
|
|
40
|
+
const docs = await Records.find(query, readProjection({ fields })).sort({ createdTime: -1 }).lean();
|
|
43
41
|
return docs.map(toAirtableRow);
|
|
44
42
|
}
|
|
45
43
|
|
|
@@ -11,7 +11,7 @@ const { logger } = require('../utils/logger');
|
|
|
11
11
|
const { stableStringify } = require('../utils/jsonUtils');
|
|
12
12
|
const { daysSince } = require('../utils/dateUtils');
|
|
13
13
|
const {
|
|
14
|
-
ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION,
|
|
14
|
+
ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRun, getAirtableArchiveSchema, getAirtableTableRecords,
|
|
15
15
|
} = require('../models/airtableArchiveModel');
|
|
16
16
|
const { createdBefore, createdSince, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
17
17
|
const { normalizeFields, hashFields, schemaSnapshotId } = require('../helpers/airtableArchiveHelper');
|
|
@@ -181,21 +181,45 @@ async function rehostAttachments({ baseId, tableId, recordId, attachments, alrea
|
|
|
181
181
|
return hosted;
|
|
182
182
|
}
|
|
183
183
|
|
|
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
|
+
|
|
184
208
|
const emptyCounts = () => ({ scanned: 0, eligible: 0, copied: 0, refreshed: 0, verified: 0, failed: 0, skipped: 0, stamped: 0, deleted: 0 });
|
|
185
209
|
|
|
186
210
|
const WRITE_REJECTIONS = ['MongoBulkWriteError', 'MongooseBulkWriteError', 'MongoInvalidArgumentError'];
|
|
187
211
|
|
|
188
|
-
const writeBatch = (
|
|
212
|
+
const writeBatch = (Records, ops) => Records.bulkWrite(ops, { ordered: false, throwOnValidationError: true, writeConcern: WRITE_CONCERN });
|
|
189
213
|
|
|
190
214
|
// A rejected batch is retried op by op, so one bad record cannot block the rest; the read-back decides each record.
|
|
191
|
-
async function writeOps(
|
|
215
|
+
async function writeOps(Records, ops, runId) {
|
|
192
216
|
try {
|
|
193
|
-
await writeBatch(
|
|
217
|
+
await writeBatch(Records, ops);
|
|
194
218
|
} catch (error) {
|
|
195
219
|
if (!WRITE_REJECTIONS.includes(error?.name)) throw error;
|
|
196
220
|
logger.error('[airtableArchive] Batch write rejected, retrying one by one', { runId, errorName: error?.name || 'UNKNOWN' });
|
|
197
221
|
for (const op of ops) {
|
|
198
|
-
await writeBatch(
|
|
222
|
+
await writeBatch(Records, [op])
|
|
199
223
|
.catch((opError) => logger.error('[airtableArchive] Record write rejected', { runId, _id: op.updateOne.filter._id, errorName: opError?.name || 'UNKNOWN' }));
|
|
200
224
|
}
|
|
201
225
|
}
|
|
@@ -225,22 +249,21 @@ const plannerInputs = (record, plannerNames) => stableStringify({
|
|
|
225
249
|
// Where readers find a record: a renamed table or a regrouped record is rewritten even when its fields did not change.
|
|
226
250
|
const placementOf = (tableName, groupId, patient, createdTime) => stableStringify({ tableName, groupId, patient, createdTime: new Date(createdTime).getTime() });
|
|
227
251
|
|
|
228
|
-
async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease }) {
|
|
229
|
-
const ArchiveRecord = getAirtableArchiveRecord();
|
|
252
|
+
async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease, models }) {
|
|
230
253
|
const wholeById = await readWholeRecords(baseId, batch, schema, lease);
|
|
231
254
|
const changedGroups = new Set(batch.filter(({ table, record: scanned }) => {
|
|
232
255
|
const whole = wholeById.get(scanned.id);
|
|
233
256
|
return !whole || plannerInputs(whole, schema.plannerFields[table]) !== plannerInputs(scanned, schema.plannerFields[table]);
|
|
234
257
|
}).map(({ group }) => group.groupId));
|
|
235
|
-
const
|
|
236
|
-
|
|
237
|
-
|
|
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
|
+
});
|
|
238
261
|
|
|
239
262
|
const expected = new Map();
|
|
240
|
-
const
|
|
263
|
+
const opsByTable = new Map();
|
|
241
264
|
for (const { table, record: scanned, group, patient } of batch) {
|
|
242
265
|
// 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(
|
|
266
|
+
if (existing.get(scanned.id)?.sourceDeletedAt) {
|
|
244
267
|
counts[table].skipped += 1;
|
|
245
268
|
continue;
|
|
246
269
|
}
|
|
@@ -250,7 +273,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
|
|
|
250
273
|
continue;
|
|
251
274
|
}
|
|
252
275
|
const record = wholeById.get(scanned.id);
|
|
253
|
-
const _id =
|
|
276
|
+
const _id = record.id;
|
|
254
277
|
const { normalized, attachments } = normalizeFields(record.fields);
|
|
255
278
|
const fieldsHash = hashFields(normalized);
|
|
256
279
|
const sourceHash = hashFields(normalized, schema.computed.get(table));
|
|
@@ -265,14 +288,15 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
|
|
|
265
288
|
try {
|
|
266
289
|
const alreadyHosted = new Map((previous?.attachments || []).map((a) => [a.id, a]));
|
|
267
290
|
const hosted = await rehostAttachments({ baseId, tableId, recordId: record.id, attachments, alreadyHosted });
|
|
268
|
-
|
|
291
|
+
if (!opsByTable.has(table)) opsByTable.set(table, []);
|
|
292
|
+
opsByTable.get(table).push({
|
|
269
293
|
updateOne: {
|
|
270
294
|
filter: { _id },
|
|
271
295
|
update: {
|
|
272
296
|
$set: {
|
|
273
297
|
baseId, tableId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
|
|
274
298
|
fields: normalized, fieldsHash, sourceHash, patient, groupId: group.groupId, schemaId, attachments: hosted,
|
|
275
|
-
schemaVersion: ARCHIVE_SCHEMA_VERSION,
|
|
299
|
+
source: { kind: 'live', baseId }, schemaVersion: ARCHIVE_SCHEMA_VERSION,
|
|
276
300
|
},
|
|
277
301
|
$setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
|
|
278
302
|
},
|
|
@@ -289,10 +313,11 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
|
|
|
289
313
|
if (attachments.length) await renewLease(runId);
|
|
290
314
|
}
|
|
291
315
|
|
|
292
|
-
|
|
316
|
+
for (const [table, ops] of opsByTable) await writeOps(models.get(table), ops, runId);
|
|
293
317
|
|
|
294
|
-
const
|
|
295
|
-
|
|
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
|
+
);
|
|
296
321
|
for (const [_id, { table, recordId, fieldsHash, placement }] of expected) {
|
|
297
322
|
const doc = storedById.get(_id);
|
|
298
323
|
if (doc && hashFields(doc.fields) === fieldsHash && placementOf(doc.tableName, doc.groupId, doc.patient, doc.createdTime) === placement) counts[table].verified += 1;
|
|
@@ -349,40 +374,41 @@ async function deleteChunk({ baseId, runId, tableId, recordIds, schema, lease })
|
|
|
349
374
|
const ARCHIVED_PROJECTION = { fields: 1, fieldsHash: 1, sourceHash: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1 };
|
|
350
375
|
|
|
351
376
|
// Linked records missing from Airtable whose copies were stamped deleted; only records the scan covers count, so missing means gone.
|
|
352
|
-
async function goneLinkedIds({
|
|
377
|
+
async function goneLinkedIds({ entries, wholeById, archived, schema, liveIds, cutoff, models }) {
|
|
353
378
|
const missing = new Set();
|
|
354
379
|
for (const { table, record: scanned } of entries) {
|
|
355
380
|
const whole = wholeById.get(scanned.id);
|
|
356
|
-
const doc = archived.get(
|
|
381
|
+
const doc = archived.get(scanned.id);
|
|
357
382
|
for (const name of linkNamesOf(schema, table)) {
|
|
358
383
|
[...(scanned.fields[name] || []), ...(doc?.fields?.[name] || [])]
|
|
359
384
|
.filter((id) => !(whole?.fields[name] || []).includes(id) && !liveIds.has(id)).forEach((id) => missing.add(id));
|
|
360
385
|
}
|
|
361
386
|
}
|
|
362
387
|
if (!missing.size) return new Set();
|
|
363
|
-
|
|
364
|
-
|
|
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;
|
|
365
394
|
}
|
|
366
395
|
|
|
367
|
-
async function findBlockers({ baseId, entries, schema, lease, liveIds, cutoff }) {
|
|
396
|
+
async function findBlockers({ baseId, entries, schema, lease, liveIds, cutoff, models }) {
|
|
368
397
|
const wholeById = await readWholeRecords(baseId, entries, schema, lease);
|
|
369
|
-
const archived =
|
|
370
|
-
|
|
371
|
-
).lean()).map((doc) => [doc._id, doc]));
|
|
372
|
-
const goneIds = await goneLinkedIds({ baseId, entries, wholeById, archived, schema, liveIds, cutoff });
|
|
398
|
+
const archived = await findCopies(models, entries, ARCHIVED_PROJECTION);
|
|
399
|
+
const goneIds = await goneLinkedIds({ entries, wholeById, archived, schema, liveIds, cutoff, models });
|
|
373
400
|
return entries.map((entry) => ({
|
|
374
401
|
entry,
|
|
375
402
|
reason: deleteBlocker({
|
|
376
|
-
whole: wholeById.get(entry.record.id), scanned: entry.record, doc: archived.get(
|
|
403
|
+
whole: wholeById.get(entry.record.id), scanned: entry.record, doc: archived.get(entry.record.id), ...entry, schema, goneIds,
|
|
377
404
|
}),
|
|
378
405
|
})).filter(({ reason }) => reason);
|
|
379
406
|
}
|
|
380
407
|
|
|
381
408
|
// 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();
|
|
409
|
+
async function deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff, models }) {
|
|
384
410
|
const blocked = new Set();
|
|
385
|
-
for (const { entry: { table, record, group }, reason } of await findBlockers({ baseId, entries: batch, schema, lease, liveIds, cutoff })) {
|
|
411
|
+
for (const { entry: { table, record, group }, reason } of await findBlockers({ baseId, entries: batch, schema, lease, liveIds, cutoff, models })) {
|
|
386
412
|
blocked.add(group.groupId);
|
|
387
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 });
|
|
388
414
|
}
|
|
@@ -390,14 +416,16 @@ async function deleteBatch({ baseId, runId, batch, schema, counts, groups, lease
|
|
|
390
416
|
const verified = batch.filter(({ group }) => !blocked.has(group.groupId));
|
|
391
417
|
if (!verified.length) return;
|
|
392
418
|
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
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');
|
|
401
429
|
verified.forEach(({ table }) => { counts[table].stamped += 1; });
|
|
402
430
|
|
|
403
431
|
for (const tableId of ARCHIVE_DELETE_ORDER) {
|
|
@@ -405,7 +433,7 @@ async function deleteBatch({ baseId, runId, batch, schema, counts, groups, lease
|
|
|
405
433
|
for (let i = 0; i < entries.length; i += 10) {
|
|
406
434
|
const chunk = entries.slice(i, i + 10);
|
|
407
435
|
// 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 });
|
|
436
|
+
const changed = await findBlockers({ baseId, entries: chunk, schema, lease, liveIds, cutoff, models });
|
|
409
437
|
if (changed.length) {
|
|
410
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 }));
|
|
411
439
|
throw archiveError('archive_changed_during_delete');
|
|
@@ -480,10 +508,11 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date(), gro
|
|
|
480
508
|
const work = plan.eligible.map((group) => group.records.map(({ table, id, patient }) => ({ table, record: recordsById.get(id), group, patient })));
|
|
481
509
|
work.flat().forEach(({ table }) => { counts[table].eligible += 1; });
|
|
482
510
|
|
|
511
|
+
const models = mode === 'plan' ? null : await tableModels(baseId, schema);
|
|
483
512
|
if (mode === 'copy' && work.length) {
|
|
484
513
|
const schemaId = await storeSchemaSnapshot(baseId, schema.snapshot, now);
|
|
485
514
|
for (const batch of groupBatches(work)) {
|
|
486
|
-
await copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease });
|
|
515
|
+
await copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease, models });
|
|
487
516
|
await renewLease(runId);
|
|
488
517
|
}
|
|
489
518
|
}
|
|
@@ -494,7 +523,7 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date(), gro
|
|
|
494
523
|
groups.notEligible = requested.size - targets.length;
|
|
495
524
|
const liveIds = new Set(recordsById.keys());
|
|
496
525
|
for (const batch of groupBatches(targets)) {
|
|
497
|
-
await deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff });
|
|
526
|
+
await deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff, models });
|
|
498
527
|
await renewLease(runId);
|
|
499
528
|
}
|
|
500
529
|
}
|