@peopl-health/nexus 5.73.0-dev.15248 → 5.73.0-dev.15250
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.
- package/lib/config/airtableArchiveConfig.js +87 -0
- package/lib/helpers/airtableArchiveHelper.js +30 -0
- package/lib/helpers/airtableFormulaHelper.js +6 -0
- package/lib/services/airtableArchivePlanService.js +149 -0
- package/lib/services/airtableArchiveService.js +260 -0
- package/lib/services/airtableService.js +52 -9
- package/lib/utils/jsonUtils.js +11 -0
- package/package.json +1 -1
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
const ARCHIVE_TABLES = Object.freeze({
|
|
2
|
+
QUESTIONNAIRES: 'weekly_questionnaires',
|
|
3
|
+
TRIAGES: 'triaje_symptoms',
|
|
4
|
+
SYMPTOMS: 'symptoms',
|
|
5
|
+
ADDITIONAL_ANSWERS: 'additional_answers',
|
|
6
|
+
RECOMMENDATIONS: 'cluster_recommendations',
|
|
7
|
+
RESOLUTIONS: 'cluster_resolutions',
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
// Links inside one triage group: their records are archived together or not at all.
|
|
11
|
+
const GROUP_LINKS = Object.freeze({
|
|
12
|
+
[ARCHIVE_TABLES.QUESTIONNAIRES]: ['triage_symptoms_id', 'additional_answers'],
|
|
13
|
+
[ARCHIVE_TABLES.TRIAGES]: ['questionnaire_id', 'symptoms', 'cluster_recommendations'],
|
|
14
|
+
[ARCHIVE_TABLES.SYMPTOMS]: ['triaje_id', 'cluster_recommendations'],
|
|
15
|
+
[ARCHIVE_TABLES.ADDITIONAL_ANSWERS]: ['questionnaire_id'],
|
|
16
|
+
[ARCHIVE_TABLES.RECOMMENDATIONS]: ['triaje_symptoms', 'symptoms', 'cluster_resolutions'],
|
|
17
|
+
[ARCHIVE_TABLES.RESOLUTIONS]: ['cluster_recommendations'],
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
// Links from an older group to the newer questionnaire generated from it.
|
|
21
|
+
const CARRY_OVER_LINKS = Object.freeze({
|
|
22
|
+
[ARCHIVE_TABLES.TRIAGES]: ['weekly_questionnaires_prev'],
|
|
23
|
+
[ARCHIVE_TABLES.SYMPTOMS]: ['weekly_questionnaires'],
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// Questionnaire links back to the group it continues: they keep a group only when they reach outside the scan.
|
|
27
|
+
const BACKWARD_LINKS = Object.freeze({
|
|
28
|
+
[ARCHIVE_TABLES.QUESTIONNAIRES]: ['prev_triaje', 'symptoms_ids_grade1'],
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// Links to non-catalog tables that are never archived: a linked group stays in Airtable.
|
|
32
|
+
const EXTERNAL_LINKS = Object.freeze({
|
|
33
|
+
[ARCHIVE_TABLES.QUESTIONNAIRES]: ['physician_report', 'extraction_analysis', 'weekly_first_message'],
|
|
34
|
+
[ARCHIVE_TABLES.TRIAGES]: ['seguimiento_dolor'],
|
|
35
|
+
[ARCHIVE_TABLES.SYMPTOMS]: ['physician_report'],
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const PATIENT_LINK_FIELD = 'patient_id';
|
|
39
|
+
const PATIENT_WHATSAPP_FIELD = 'whatsapp_id';
|
|
40
|
+
const QUESTIONNAIRE_TRIAGE_LINK = 'triage_symptoms_id';
|
|
41
|
+
const QUESTIONNAIRE_APPROVED_FIELD = 'approved';
|
|
42
|
+
const QUESTIONNAIRE_CREATED_FIELD = 'created';
|
|
43
|
+
const FIRST_MONTH_DAYS = 30;
|
|
44
|
+
|
|
45
|
+
const KEEP_REASONS = Object.freeze({
|
|
46
|
+
LINKS_NEWER: 'links_newer',
|
|
47
|
+
LINKS_OUTSIDE: 'links_outside',
|
|
48
|
+
FIRST_QUESTIONNAIRE: 'first_questionnaire',
|
|
49
|
+
FIRST_TRIAGE: 'first_triage',
|
|
50
|
+
FIRST_MONTH: 'first_month',
|
|
51
|
+
LATEST_QUESTIONNAIRE: 'latest_questionnaire',
|
|
52
|
+
LATEST_TRIAGE: 'latest_triage',
|
|
53
|
+
UNAPPROVED_QUESTIONNAIRE: 'unapproved_questionnaire',
|
|
54
|
+
CARRIED_INTO_NEWER: 'carried_into_newer',
|
|
55
|
+
CARRIED_INTO_KEPT: 'carried_into_kept',
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// A guard against a mistyped cutoff: nothing younger than this is ever archived.
|
|
59
|
+
const MIN_ARCHIVE_AGE_DAYS = 90;
|
|
60
|
+
const ARCHIVE_BATCH_SIZE = 100;
|
|
61
|
+
// Airtable field types whose value Airtable computes; they are stored but never decide whether the source changed.
|
|
62
|
+
const COMPUTED_FIELD_TYPES = Object.freeze([
|
|
63
|
+
'formula', 'rollup', 'count', 'multipleLookupValues', 'lastModifiedTime', 'lastModifiedBy',
|
|
64
|
+
'createdTime', 'createdBy', 'autoNumber', 'button', 'aiText',
|
|
65
|
+
]);
|
|
66
|
+
const ARCHIVE_LEASE_MS = 15 * 60 * 1000;
|
|
67
|
+
const ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30000;
|
|
68
|
+
|
|
69
|
+
module.exports = {
|
|
70
|
+
ARCHIVE_TABLES,
|
|
71
|
+
MIN_ARCHIVE_AGE_DAYS,
|
|
72
|
+
ARCHIVE_BATCH_SIZE,
|
|
73
|
+
ARCHIVE_LEASE_MS,
|
|
74
|
+
ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
|
|
75
|
+
COMPUTED_FIELD_TYPES,
|
|
76
|
+
GROUP_LINKS,
|
|
77
|
+
CARRY_OVER_LINKS,
|
|
78
|
+
BACKWARD_LINKS,
|
|
79
|
+
EXTERNAL_LINKS,
|
|
80
|
+
PATIENT_LINK_FIELD,
|
|
81
|
+
PATIENT_WHATSAPP_FIELD,
|
|
82
|
+
QUESTIONNAIRE_TRIAGE_LINK,
|
|
83
|
+
QUESTIONNAIRE_APPROVED_FIELD,
|
|
84
|
+
QUESTIONNAIRE_CREATED_FIELD,
|
|
85
|
+
FIRST_MONTH_DAYS,
|
|
86
|
+
KEEP_REASONS,
|
|
87
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
|
|
3
|
+
const { stableStringify } = require('../utils/jsonUtils');
|
|
4
|
+
|
|
5
|
+
const isAttachment = (item) => item && typeof item === 'object' && typeof item.id === 'string' && item.id.startsWith('att') && typeof item.url === 'string';
|
|
6
|
+
const isAttachmentList = (value) => Array.isArray(value) && value.length > 0 && value.every(isAttachment);
|
|
7
|
+
|
|
8
|
+
// Signed attachment URLs expire and change on every read, so they are neither stored nor hashed.
|
|
9
|
+
function normalizeFields(fields = {}) {
|
|
10
|
+
const normalized = {};
|
|
11
|
+
const attachments = [];
|
|
12
|
+
for (const [name, value] of Object.entries(fields)) {
|
|
13
|
+
if (!isAttachmentList(value)) {
|
|
14
|
+
normalized[name] = value;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
normalized[name] = value.map(({ id, filename = null, type = null, size = null }) => ({ id, filename, type, size }));
|
|
18
|
+
value.forEach((item) => attachments.push({ field: name, item }));
|
|
19
|
+
}
|
|
20
|
+
return { normalized, attachments };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const hashFields = (fields, skip = new Set()) => crypto.createHash('sha256')
|
|
24
|
+
.update(stableStringify(Object.fromEntries(Object.entries(fields).filter(([name]) => !skip.has(name)))))
|
|
25
|
+
.digest('hex');
|
|
26
|
+
|
|
27
|
+
module.exports = {
|
|
28
|
+
normalizeFields,
|
|
29
|
+
hashFields,
|
|
30
|
+
};
|
|
@@ -10,10 +10,16 @@ const recordIdIn = (ids) => (ids.length
|
|
|
10
10
|
|
|
11
11
|
const createdBetween = (since, until) => `AND(IS_AFTER(CREATED_TIME(), '${since.toISOString()}'), IS_BEFORE(CREATED_TIME(), '${until.toISOString()}'))`;
|
|
12
12
|
|
|
13
|
+
const createdBefore = (until) => `IS_BEFORE(CREATED_TIME(), '${until.toISOString()}')`;
|
|
14
|
+
|
|
15
|
+
const createdSince = (since) => `NOT(${createdBefore(since)})`;
|
|
16
|
+
|
|
13
17
|
module.exports = {
|
|
14
18
|
MATCH_ALL,
|
|
15
19
|
escapeFormulaValue,
|
|
16
20
|
fieldEquals,
|
|
17
21
|
recordIdIn,
|
|
18
22
|
createdBetween,
|
|
23
|
+
createdBefore,
|
|
24
|
+
createdSince,
|
|
19
25
|
};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
|
|
3
|
+
const {
|
|
4
|
+
ARCHIVE_TABLES, GROUP_LINKS, CARRY_OVER_LINKS, BACKWARD_LINKS, EXTERNAL_LINKS, PATIENT_LINK_FIELD, PATIENT_WHATSAPP_FIELD,
|
|
5
|
+
QUESTIONNAIRE_TRIAGE_LINK, QUESTIONNAIRE_APPROVED_FIELD, QUESTIONNAIRE_CREATED_FIELD, FIRST_MONTH_DAYS, KEEP_REASONS,
|
|
6
|
+
} = require('../config/airtableArchiveConfig');
|
|
7
|
+
|
|
8
|
+
const linkedIds = (record, fieldNames = []) => fieldNames.flatMap((name) => {
|
|
9
|
+
const value = record.fields?.[name];
|
|
10
|
+
return Array.isArray(value) ? value.filter((id) => typeof id === 'string') : [];
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const firstString = (value) => (Array.isArray(value) ? value.find((v) => typeof v === 'string') : (typeof value === 'string' ? value : null)) || null;
|
|
14
|
+
|
|
15
|
+
function createUnionFind(ids) {
|
|
16
|
+
const parent = new Map(ids.map((id) => [id, id]));
|
|
17
|
+
const find = (id) => {
|
|
18
|
+
let root = id;
|
|
19
|
+
while (parent.get(root) !== root) root = parent.get(root);
|
|
20
|
+
let node = id;
|
|
21
|
+
while (parent.get(node) !== root) {
|
|
22
|
+
const next = parent.get(node);
|
|
23
|
+
parent.set(node, root);
|
|
24
|
+
node = next;
|
|
25
|
+
}
|
|
26
|
+
return root;
|
|
27
|
+
};
|
|
28
|
+
const union = (a, b) => {
|
|
29
|
+
const rootA = find(a);
|
|
30
|
+
const rootB = find(b);
|
|
31
|
+
if (rootA !== rootB) parent.set(rootB, rootA);
|
|
32
|
+
};
|
|
33
|
+
return { find, union };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const groupIdOf = (recordIds) => crypto.createHash('sha256').update([...recordIds].sort().join(',')).digest('hex').slice(0, 24);
|
|
37
|
+
|
|
38
|
+
// The patient rollups read the questionnaire's own `created` date, which can differ from the record's createdTime.
|
|
39
|
+
const createdMs = (entry) => Date.parse(entry.record.fields?.[QUESTIONNAIRE_CREATED_FIELD] || entry.record.createdTime);
|
|
40
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
41
|
+
|
|
42
|
+
function oldestAndNewestByPatient(entries) {
|
|
43
|
+
const byPatient = new Map();
|
|
44
|
+
for (const entry of entries) {
|
|
45
|
+
const patientId = firstString(entry.record.fields?.[PATIENT_LINK_FIELD]);
|
|
46
|
+
if (!patientId) continue;
|
|
47
|
+
const current = byPatient.get(patientId);
|
|
48
|
+
if (!current) {
|
|
49
|
+
byPatient.set(patientId, { oldest: entry, newest: entry });
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (createdMs(entry) < createdMs(current.oldest)) current.oldest = entry;
|
|
53
|
+
if (createdMs(entry) > createdMs(current.newest)) current.newest = entry;
|
|
54
|
+
}
|
|
55
|
+
return byPatient;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Splits records older than the cutoff into triage groups and returns the ones safe to archive.
|
|
59
|
+
function planArchive({ recordsByTable, patientsWithRecent = {} }) {
|
|
60
|
+
const entries = new Map();
|
|
61
|
+
for (const [table, records] of Object.entries(recordsByTable)) {
|
|
62
|
+
for (const record of records || []) entries.set(record.id, { table, record });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const { find, union } = createUnionFind([...entries.keys()]);
|
|
66
|
+
const keepReasons = new Map();
|
|
67
|
+
const markKeep = (recordId, reason) => {
|
|
68
|
+
const root = find(recordId);
|
|
69
|
+
if (!keepReasons.has(root)) keepReasons.set(root, reason);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const touchesNewer = [];
|
|
73
|
+
for (const [id, { table, record }] of entries) {
|
|
74
|
+
for (const linkedId of linkedIds(record, GROUP_LINKS[table])) {
|
|
75
|
+
if (entries.has(linkedId)) union(id, linkedId);
|
|
76
|
+
else touchesNewer.push(id);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const [id, { table, record }] of entries) {
|
|
80
|
+
if (linkedIds(record, BACKWARD_LINKS[table]).some((linkedId) => !entries.has(linkedId))) touchesNewer.push(id);
|
|
81
|
+
}
|
|
82
|
+
touchesNewer.forEach((id) => markKeep(id, KEEP_REASONS.LINKS_NEWER));
|
|
83
|
+
for (const [id, { table, record }] of entries) {
|
|
84
|
+
if (linkedIds(record, EXTERNAL_LINKS[table]).length) markKeep(id, KEEP_REASONS.LINKS_OUTSIDE);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const byTable = (table) => [...entries.values()].filter((entry) => entry.table === table);
|
|
88
|
+
const questionnaires = byTable(ARCHIVE_TABLES.QUESTIONNAIRES);
|
|
89
|
+
|
|
90
|
+
const questionnaireAnchors = oldestAndNewestByPatient(questionnaires);
|
|
91
|
+
for (const [patientId, { oldest, newest }] of questionnaireAnchors) {
|
|
92
|
+
markKeep(oldest.record.id, KEEP_REASONS.FIRST_QUESTIONNAIRE);
|
|
93
|
+
if (!patientsWithRecent[ARCHIVE_TABLES.QUESTIONNAIRES]?.has(patientId)) markKeep(newest.record.id, KEEP_REASONS.LATEST_QUESTIONNAIRE);
|
|
94
|
+
}
|
|
95
|
+
for (const [patientId, { oldest, newest }] of oldestAndNewestByPatient(byTable(ARCHIVE_TABLES.TRIAGES))) {
|
|
96
|
+
markKeep(oldest.record.id, KEEP_REASONS.FIRST_TRIAGE);
|
|
97
|
+
if (!patientsWithRecent[ARCHIVE_TABLES.TRIAGES]?.has(patientId)) markKeep(newest.record.id, KEEP_REASONS.LATEST_TRIAGE);
|
|
98
|
+
}
|
|
99
|
+
for (const entry of questionnaires) {
|
|
100
|
+
const anchor = questionnaireAnchors.get(firstString(entry.record.fields?.[PATIENT_LINK_FIELD]));
|
|
101
|
+
if (anchor && createdMs(entry) - createdMs(anchor.oldest) < FIRST_MONTH_DAYS * DAY_MS) markKeep(entry.record.id, KEEP_REASONS.FIRST_MONTH);
|
|
102
|
+
}
|
|
103
|
+
for (const { record } of questionnaires) {
|
|
104
|
+
if (record.fields?.[QUESTIONNAIRE_APPROVED_FIELD] !== true && !linkedIds(record, [QUESTIONNAIRE_TRIAGE_LINK]).length) {
|
|
105
|
+
markKeep(record.id, KEEP_REASONS.UNAPPROVED_QUESTIONNAIRE);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// One hop only: a kept group protects the group it was generated from, never that group's own predecessor.
|
|
110
|
+
const keptBeforeCarryOver = new Set(keepReasons.keys());
|
|
111
|
+
for (const [id, { table, record }] of entries) {
|
|
112
|
+
for (const linkedId of linkedIds(record, CARRY_OVER_LINKS[table])) {
|
|
113
|
+
if (!entries.has(linkedId)) markKeep(id, KEEP_REASONS.CARRIED_INTO_NEWER);
|
|
114
|
+
else if (keptBeforeCarryOver.has(find(linkedId)) && find(linkedId) !== find(id)) markKeep(id, KEEP_REASONS.CARRIED_INTO_KEPT);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const components = new Map();
|
|
119
|
+
for (const [id, entry] of entries) {
|
|
120
|
+
const root = find(id);
|
|
121
|
+
if (!components.has(root)) components.set(root, []);
|
|
122
|
+
components.get(root).push({ table: entry.table, id });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const eligible = [];
|
|
126
|
+
const keptByReason = {};
|
|
127
|
+
for (const [root, records] of components) {
|
|
128
|
+
const reason = keepReasons.get(root);
|
|
129
|
+
if (reason) {
|
|
130
|
+
keptByReason[reason] = (keptByReason[reason] || 0) + 1;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const patientEntry = records.map(({ id }) => entries.get(id).record).find((r) => firstString(r.fields?.[PATIENT_LINK_FIELD]));
|
|
134
|
+
eligible.push({
|
|
135
|
+
groupId: groupIdOf(records.map(({ id }) => id)),
|
|
136
|
+
patient: {
|
|
137
|
+
recordId: firstString(patientEntry?.fields?.[PATIENT_LINK_FIELD]),
|
|
138
|
+
whatsappId: firstString(patientEntry?.fields?.[PATIENT_WHATSAPP_FIELD]),
|
|
139
|
+
},
|
|
140
|
+
records,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return { eligible, keptByReason, scanned: entries.size };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
module.exports = {
|
|
148
|
+
planArchive,
|
|
149
|
+
};
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
const axios = require('axios');
|
|
2
|
+
const { v4: uuidv4 } = require('uuid');
|
|
3
|
+
|
|
4
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
5
|
+
const { uploadBufferToS3 } = require('../config/awsConfig');
|
|
6
|
+
const {
|
|
7
|
+
ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS, PATIENT_LINK_FIELD, COMPUTED_FIELD_TYPES,
|
|
8
|
+
} = require('../config/airtableArchiveConfig');
|
|
9
|
+
const { logger } = require('../utils/logger');
|
|
10
|
+
const { stableStringify } = require('../utils/jsonUtils');
|
|
11
|
+
const { daysSince } = require('../utils/dateUtils');
|
|
12
|
+
const {
|
|
13
|
+
ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRecord, getAirtableArchiveRun, archiveRecordId,
|
|
14
|
+
} = require('../models/airtableArchiveModel');
|
|
15
|
+
const { createdBefore, createdSince } = require('../helpers/airtableFormulaHelper');
|
|
16
|
+
const { normalizeFields, hashFields } = require('../helpers/airtableArchiveHelper');
|
|
17
|
+
|
|
18
|
+
const { getRecordsWithMetadata, getBaseSchema } = require('./airtableService');
|
|
19
|
+
const { planArchive } = require('./airtableArchivePlanService');
|
|
20
|
+
|
|
21
|
+
const DUPLICATE_KEY_ERROR = 11000;
|
|
22
|
+
const WRITE_CONCERN = { w: 'majority', j: true };
|
|
23
|
+
|
|
24
|
+
const archiveError = (code) => Object.assign(new Error(code), { code });
|
|
25
|
+
|
|
26
|
+
async function readComputedFields(baseId) {
|
|
27
|
+
let tables;
|
|
28
|
+
try {
|
|
29
|
+
tables = await getBaseSchema(baseId);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
throw Object.assign(archiveError('archive_schema_unreadable'), { cause: error });
|
|
32
|
+
}
|
|
33
|
+
const computed = new Map();
|
|
34
|
+
for (const table of Object.values(ARCHIVE_TABLES)) {
|
|
35
|
+
const schema = tables?.find((t) => t.name === table);
|
|
36
|
+
if (!schema) {
|
|
37
|
+
logger.error('[airtableArchive] Archived table missing from the base schema', { table });
|
|
38
|
+
throw archiveError('archive_schema_unreadable');
|
|
39
|
+
}
|
|
40
|
+
computed.set(table, new Set(schema.fields.filter((f) => COMPUTED_FIELD_TYPES.includes(f.type)).map((f) => f.name)));
|
|
41
|
+
}
|
|
42
|
+
return computed;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function scanOldRecords(baseId, cutoff, runId) {
|
|
46
|
+
const recordsByTable = {};
|
|
47
|
+
for (const table of Object.values(ARCHIVE_TABLES)) {
|
|
48
|
+
recordsByTable[table] = await getRecordsWithMetadata(baseId, table, createdBefore(cutoff));
|
|
49
|
+
await renewLease(runId);
|
|
50
|
+
}
|
|
51
|
+
return recordsByTable;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function scanPatientsWithRecent(baseId, cutoff, runId) {
|
|
55
|
+
const patientsWithRecent = {};
|
|
56
|
+
for (const table of [ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_TABLES.TRIAGES]) {
|
|
57
|
+
const records = await getRecordsWithMetadata(baseId, table, createdSince(cutoff), [PATIENT_LINK_FIELD]);
|
|
58
|
+
patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields?.[PATIENT_LINK_FIELD] || []));
|
|
59
|
+
await renewLease(runId);
|
|
60
|
+
}
|
|
61
|
+
return patientsWithRecent;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let runIndexesReady = null;
|
|
65
|
+
|
|
66
|
+
// The single-flight guarantee is the partial unique index, so no run starts before it exists.
|
|
67
|
+
function ensureRunIndexes() {
|
|
68
|
+
if (!runIndexesReady) {
|
|
69
|
+
runIndexesReady = getAirtableArchiveRun().createIndexes().catch((error) => {
|
|
70
|
+
runIndexesReady = null;
|
|
71
|
+
throw error;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return runIndexesReady;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function acquireRun({ baseId, mode, cutoff, now }) {
|
|
78
|
+
await ensureRunIndexes();
|
|
79
|
+
const Run = getAirtableArchiveRun();
|
|
80
|
+
await Run.updateMany(
|
|
81
|
+
{ baseId, status: 'running', leaseExpiresAt: { $lt: now } },
|
|
82
|
+
{ $set: { status: 'failed', errorCode: 'lease_expired', finishedAt: now } },
|
|
83
|
+
);
|
|
84
|
+
try {
|
|
85
|
+
return await Run.create({
|
|
86
|
+
runId: uuidv4(), baseId, mode, cutoff, status: 'running', startedAt: now, leaseExpiresAt: new Date(now.getTime() + ARCHIVE_LEASE_MS),
|
|
87
|
+
});
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (error?.code === DUPLICATE_KEY_ERROR) throw archiveError('archive_run_in_progress');
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// A run whose lease was taken over must stop: another run now owns the base.
|
|
95
|
+
async function renewLease(runId) {
|
|
96
|
+
const result = await getAirtableArchiveRun().updateOne(
|
|
97
|
+
{ runId, status: 'running' },
|
|
98
|
+
{ $set: { leaseExpiresAt: new Date(Date.now() + ARCHIVE_LEASE_MS) } },
|
|
99
|
+
);
|
|
100
|
+
if (!result?.matchedCount) throw archiveError('archive_lease_lost');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function rehostAttachments({ baseId, tableName, recordId, attachments, alreadyHosted }) {
|
|
104
|
+
if (!attachments.length) return [];
|
|
105
|
+
const bucket = runtimeConfig.get('AIRTABLE_ARCHIVE_BUCKET');
|
|
106
|
+
if (!bucket) throw archiveError('archive_bucket_missing');
|
|
107
|
+
const hosted = [];
|
|
108
|
+
for (const { field, item } of attachments) {
|
|
109
|
+
const previous = alreadyHosted.get(item.id);
|
|
110
|
+
if (previous) {
|
|
111
|
+
hosted.push(previous);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const s3Key = `airtable-archive/${baseId}/${tableName}/${recordId}/${item.id}`;
|
|
115
|
+
const response = await axios.get(item.url, { responseType: 'arraybuffer', timeout: ATTACHMENT_DOWNLOAD_TIMEOUT_MS });
|
|
116
|
+
const bytes = response.data?.byteLength;
|
|
117
|
+
if (typeof item.size === 'number' ? bytes !== item.size : !bytes) throw archiveError('attachment_size_mismatch');
|
|
118
|
+
await uploadBufferToS3(Buffer.from(response.data), bucket, s3Key, item.type || 'application/octet-stream');
|
|
119
|
+
hosted.push({ field, id: item.id, filename: item.filename || null, type: item.type || null, size: item.size ?? null, s3Key });
|
|
120
|
+
}
|
|
121
|
+
return hosted;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const emptyCounts = () => ({ scanned: 0, eligible: 0, copied: 0, refreshed: 0, verified: 0, failed: 0 });
|
|
125
|
+
|
|
126
|
+
const WRITE_REJECTIONS = ['MongoBulkWriteError', 'MongooseBulkWriteError', 'MongoInvalidArgumentError'];
|
|
127
|
+
|
|
128
|
+
const writeBatch = (ArchiveRecord, ops) => ArchiveRecord.bulkWrite(ops, { ordered: false, throwOnValidationError: true, writeConcern: WRITE_CONCERN });
|
|
129
|
+
|
|
130
|
+
// A rejected batch is retried op by op, so one bad record cannot block the rest; the read-back decides each record.
|
|
131
|
+
async function writeOps(ArchiveRecord, ops, runId) {
|
|
132
|
+
try {
|
|
133
|
+
await writeBatch(ArchiveRecord, ops);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (!WRITE_REJECTIONS.includes(error?.name)) throw error;
|
|
136
|
+
logger.error('[airtableArchive] Batch write rejected, retrying one by one', { runId, errorName: error?.name || 'UNKNOWN' });
|
|
137
|
+
for (const op of ops) {
|
|
138
|
+
await writeBatch(ArchiveRecord, [op])
|
|
139
|
+
.catch((opError) => logger.error('[airtableArchive] Record write rejected', { runId, _id: op.updateOne.filter._id, errorName: opError?.name || 'UNKNOWN' }));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const placementOf = (groupId, patient, createdTime) => stableStringify({ groupId, patient, createdTime: new Date(createdTime).getTime() });
|
|
145
|
+
|
|
146
|
+
async function copyBatch({ baseId, runId, batch, computed, counts, now }) {
|
|
147
|
+
const ArchiveRecord = getAirtableArchiveRecord();
|
|
148
|
+
const ids = batch.map(({ record }) => archiveRecordId(baseId, record.id));
|
|
149
|
+
const existing = new Map((await ArchiveRecord.find({ _id: { $in: ids } }, { fields: 1, fieldsHash: 1, sourceHash: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1 }).lean())
|
|
150
|
+
.map((doc) => [doc._id, doc]));
|
|
151
|
+
|
|
152
|
+
const expected = new Map();
|
|
153
|
+
const ops = [];
|
|
154
|
+
for (const { table, record, group } of batch) {
|
|
155
|
+
const _id = archiveRecordId(baseId, record.id);
|
|
156
|
+
const { normalized, attachments } = normalizeFields(record.fields);
|
|
157
|
+
const fieldsHash = hashFields(normalized);
|
|
158
|
+
const sourceHash = hashFields(normalized, computed.get(table));
|
|
159
|
+
const placement = placementOf(group.groupId, group.patient, record.createdTime);
|
|
160
|
+
const previous = existing.get(_id);
|
|
161
|
+
const previousIntact = previous && hashFields(previous.fields) === previous.fieldsHash;
|
|
162
|
+
if (previousIntact && previous.sourceHash === sourceHash && placementOf(previous.groupId, previous.patient, previous.createdTime) === placement) {
|
|
163
|
+
expected.set(_id, { table, recordId: record.id, fieldsHash: previous.fieldsHash, placement });
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
const alreadyHosted = new Map((previous?.attachments || []).map((a) => [a.id, a]));
|
|
168
|
+
const hosted = await rehostAttachments({ baseId, tableName: table, recordId: record.id, attachments, alreadyHosted });
|
|
169
|
+
ops.push({
|
|
170
|
+
updateOne: {
|
|
171
|
+
filter: { _id },
|
|
172
|
+
update: {
|
|
173
|
+
$set: {
|
|
174
|
+
baseId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
|
|
175
|
+
fields: normalized, fieldsHash, sourceHash, patient: group.patient, groupId: group.groupId, attachments: hosted,
|
|
176
|
+
schemaVersion: ARCHIVE_SCHEMA_VERSION,
|
|
177
|
+
},
|
|
178
|
+
$setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
|
|
179
|
+
},
|
|
180
|
+
upsert: true,
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
expected.set(_id, { table, recordId: record.id, fieldsHash, placement });
|
|
184
|
+
counts[table][previous ? 'refreshed' : 'copied'] += 1;
|
|
185
|
+
} catch (error) {
|
|
186
|
+
counts[table].failed += 1;
|
|
187
|
+
logger.error('[airtableArchive] Record not copied', { runId, table, recordId: record.id, errorCode: error?.code || 'UNKNOWN' });
|
|
188
|
+
}
|
|
189
|
+
// Downloads can outlast the lease, so a record with attachments renews it before the next one.
|
|
190
|
+
if (attachments.length) await renewLease(runId);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (ops.length) await writeOps(ArchiveRecord, ops, runId);
|
|
194
|
+
|
|
195
|
+
const stored = await ArchiveRecord.find({ _id: { $in: [...expected.keys()] } }, { fields: 1, groupId: 1, patient: 1, createdTime: 1 }).lean();
|
|
196
|
+
const storedById = new Map(stored.map((doc) => [doc._id, doc]));
|
|
197
|
+
for (const [_id, { table, recordId, fieldsHash, placement }] of expected) {
|
|
198
|
+
const doc = storedById.get(_id);
|
|
199
|
+
if (doc && hashFields(doc.fields) === fieldsHash && placementOf(doc.groupId, doc.patient, doc.createdTime) === placement) counts[table].verified += 1;
|
|
200
|
+
else {
|
|
201
|
+
counts[table].failed += 1;
|
|
202
|
+
logger.error('[airtableArchive] Copy did not verify', { runId, table, recordId });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function validateRequest({ baseId, cutoff, mode, now }) {
|
|
208
|
+
if (!baseId) throw archiveError('archive_base_required');
|
|
209
|
+
if (!ARCHIVE_RUN_MODES.includes(mode)) throw archiveError('archive_mode_invalid');
|
|
210
|
+
if (!(cutoff instanceof Date) || Number.isNaN(cutoff.getTime())) throw archiveError('archive_cutoff_invalid');
|
|
211
|
+
if (daysSince(cutoff, now.getTime()) < MIN_ARCHIVE_AGE_DAYS) throw archiveError('archive_cutoff_too_recent');
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Copies archivable groups older than `cutoff` into Mongo and verifies them; never deletes from Airtable.
|
|
215
|
+
async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
|
|
216
|
+
validateRequest({ baseId, cutoff, mode, now });
|
|
217
|
+
const run = await acquireRun({ baseId, mode, cutoff, now });
|
|
218
|
+
const { runId } = run;
|
|
219
|
+
const counts = Object.fromEntries(Object.values(ARCHIVE_TABLES).map((table) => [table, emptyCounts()]));
|
|
220
|
+
|
|
221
|
+
try {
|
|
222
|
+
const computed = await readComputedFields(baseId);
|
|
223
|
+
const recordsByTable = await scanOldRecords(baseId, cutoff, runId);
|
|
224
|
+
const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, runId);
|
|
225
|
+
const plan = planArchive({ recordsByTable, patientsWithRecent });
|
|
226
|
+
|
|
227
|
+
Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
|
|
228
|
+
const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
|
|
229
|
+
const work = plan.eligible.flatMap((group) => group.records.map(({ table, id }) => ({ table, record: recordsById.get(id), group })));
|
|
230
|
+
work.forEach(({ table }) => { counts[table].eligible += 1; });
|
|
231
|
+
|
|
232
|
+
if (mode === 'copy') {
|
|
233
|
+
for (let i = 0; i < work.length; i += ARCHIVE_BATCH_SIZE) {
|
|
234
|
+
await copyBatch({ baseId, runId, batch: work.slice(i, i + ARCHIVE_BATCH_SIZE), computed, counts, now });
|
|
235
|
+
await renewLease(runId);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const failed = Object.values(counts).reduce((sum, c) => sum + c.failed, 0);
|
|
240
|
+
const summary = {
|
|
241
|
+
runId, mode, cutoff, status: failed ? 'failed' : 'succeeded',
|
|
242
|
+
components: { eligible: plan.eligible.length, kept: plan.keptByReason }, tables: counts,
|
|
243
|
+
};
|
|
244
|
+
const finished = await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, {
|
|
245
|
+
$set: { status: summary.status, finishedAt: new Date(), components: summary.components, tables: counts, errorCode: failed ? 'records_failed' : null },
|
|
246
|
+
});
|
|
247
|
+
if (!finished?.matchedCount) throw archiveError('archive_lease_lost');
|
|
248
|
+
logger.info('[airtableArchive] Run finished', summary);
|
|
249
|
+
return summary;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
const errorCode = error?.code && typeof error.code === 'string' ? error.code : 'UNKNOWN';
|
|
252
|
+
await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, errorCode } });
|
|
253
|
+
logger.error('[airtableArchive] Run failed', { runId, mode, errorCode });
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
module.exports = {
|
|
259
|
+
runArchive,
|
|
260
|
+
};
|
|
@@ -127,6 +127,43 @@ async function getRecordByFilter(baseID, tableName, filter, view = 'Grid view',
|
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
+
async function getRecordsWithMetadata(baseID, tableName, filter, fields) {
|
|
131
|
+
try {
|
|
132
|
+
const selectOptions = { filterByFormula: filter };
|
|
133
|
+
if (fields && fields.length) selectOptions.fields = fields;
|
|
134
|
+
return await withAirtableRetry(
|
|
135
|
+
() => collectRecords(getBase(baseID)(tableName).select(selectOptions), (r) => ({ id: r.id, createdTime: r._rawJson?.createdTime, fields: r.fields })),
|
|
136
|
+
'getRecordsWithMetadata'
|
|
137
|
+
);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
logger.error('[getRecordsWithMetadata] Failed', safeAirtableFailure(error));
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Needs the schema.bases:read scope; returns [{ name, fields: [{ name, type }] }] per table.
|
|
145
|
+
async function getBaseSchema(baseID) {
|
|
146
|
+
const apiKey = getApiKey();
|
|
147
|
+
if (!apiKey) throw new Error('Airtable not configured. Set AIRTABLE_API_KEY');
|
|
148
|
+
try {
|
|
149
|
+
const data = await withAirtableRetry(async () => {
|
|
150
|
+
try {
|
|
151
|
+
const response = await axios.get(`${AIRTABLE_API_URL}/meta/bases/${baseID}/tables`, {
|
|
152
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
153
|
+
timeout: getRequestTimeoutMs(),
|
|
154
|
+
});
|
|
155
|
+
return response.data;
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw toAirtableHttpError(error);
|
|
158
|
+
}
|
|
159
|
+
}, 'getBaseSchema');
|
|
160
|
+
return data.tables;
|
|
161
|
+
} catch (error) {
|
|
162
|
+
logger.error('[getBaseSchema] Failed', safeAirtableFailure(error));
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
130
167
|
async function updateRecordByFilter(baseID, tableName, filter, updateFields, context = null) {
|
|
131
168
|
if (isShadowRun() || isBenchMode(context)) {
|
|
132
169
|
logger.info(`[updateRecordByFilter:${isShadowRun() ? 'shadow' : 'bench'}] Suppressed`, { tableName, filter, code: context });
|
|
@@ -187,6 +224,18 @@ async function addLinkedRecord(baseID, targetTable, fields, linkConfig, context
|
|
|
187
224
|
}
|
|
188
225
|
}
|
|
189
226
|
|
|
227
|
+
function toAirtableHttpError(error) {
|
|
228
|
+
const status = error.response?.status;
|
|
229
|
+
if (status === undefined) {
|
|
230
|
+
if (error.code === AXIOS_TIMEOUT_CODE) error.code = 'ETIMEDOUT';
|
|
231
|
+
return error;
|
|
232
|
+
}
|
|
233
|
+
return Object.assign(new Error(error.response?.data?.error?.message || error.message), {
|
|
234
|
+
statusCode: status,
|
|
235
|
+
error: error.response?.data?.error?.type,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
190
239
|
async function patchUpsert(baseID, tableName, fields, mergeOn, apiKey) {
|
|
191
240
|
try {
|
|
192
241
|
const { data } = await axios.patch(
|
|
@@ -199,15 +248,7 @@ async function patchUpsert(baseID, tableName, fields, mergeOn, apiKey) {
|
|
|
199
248
|
);
|
|
200
249
|
return data;
|
|
201
250
|
} catch (error) {
|
|
202
|
-
|
|
203
|
-
if (status === undefined) {
|
|
204
|
-
if (error.code === AXIOS_TIMEOUT_CODE) error.code = 'ETIMEDOUT';
|
|
205
|
-
throw error;
|
|
206
|
-
}
|
|
207
|
-
throw Object.assign(new Error(error.response?.data?.error?.message || error.message), {
|
|
208
|
-
statusCode: status,
|
|
209
|
-
error: error.response?.data?.error?.type,
|
|
210
|
-
});
|
|
251
|
+
throw toAirtableHttpError(error);
|
|
211
252
|
}
|
|
212
253
|
}
|
|
213
254
|
|
|
@@ -256,6 +297,8 @@ module.exports = {
|
|
|
256
297
|
addRecord,
|
|
257
298
|
getRecords,
|
|
258
299
|
getRecordByFilter,
|
|
300
|
+
getRecordsWithMetadata,
|
|
301
|
+
getBaseSchema,
|
|
259
302
|
updateRecordByFilter,
|
|
260
303
|
addLinkedRecord,
|
|
261
304
|
upsertRecord
|
package/lib/utils/jsonUtils.js
CHANGED
|
@@ -61,8 +61,19 @@ function cleanForJson(value) {
|
|
|
61
61
|
return value;
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
// Same value, same string: object keys are sorted at every depth so the output can be hashed.
|
|
65
|
+
function stableStringify(value) {
|
|
66
|
+
if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item === undefined ? null : item)).join(',')}]`;
|
|
67
|
+
if (isPlainObject(value)) {
|
|
68
|
+
const entries = Object.keys(value).sort().filter((key) => value[key] !== undefined);
|
|
69
|
+
return `{${entries.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
|
|
70
|
+
}
|
|
71
|
+
return JSON.stringify(value);
|
|
72
|
+
}
|
|
73
|
+
|
|
64
74
|
module.exports = {
|
|
65
75
|
jsonStringifyWithUnicodeEscapes,
|
|
76
|
+
stableStringify,
|
|
66
77
|
safeParse,
|
|
67
78
|
safeParseArray,
|
|
68
79
|
objectArg,
|