@peopl-health/nexus 5.78.0-dev.16671 → 5.78.0

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,7 +130,6 @@ 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
133
  const ARCHIVE_DELETE_MAX_GROUPS = 1000;
135
134
  // Parents first: a surviving parent never sees its children vanish, which would match the base's send automations.
136
135
  const ARCHIVE_DELETE_ORDER = Object.freeze([
@@ -140,9 +139,7 @@ const ARCHIVE_DELETE_ORDER = Object.freeze([
140
139
  const ARCHIVE_DELETE_SPACING_MS = 250;
141
140
  // Airtable deletes at most 10 records per request.
142
141
  const ARCHIVE_DELETE_CHUNK_SIZE = 10;
143
- // The patients table: a mirrored record's patient is its link to it and the WhatsApp id looked up through that link.
144
142
  const PATIENT_TABLE = Object.freeze({ ID: 'tblUi9KbsefAbrvK2', WHATSAPP: 'fldMfzbVbAxIJ9345' });
145
- // Attachments re-hosted per mirror run; the rest wait for the next run, so the first runs over a full base stay bounded.
146
143
  const MIRROR_MAX_ATTACHMENTS_PER_RUN = 2000;
147
144
  // More records missing from a full scan than this is taken for a bad read, not deletions: none are marked gone.
148
145
  const MIRROR_GONE_MAX_SHARE = 0.02;
@@ -6,7 +6,6 @@ const ARCHIVE_SCHEMA_VERSION = 1;
6
6
  const ARCHIVE_RUN_MODES = ['plan', 'copy', 'delete', 'mirror'];
7
7
  const ARCHIVE_RUN_STATUSES = ['running', 'succeeded', 'failed'];
8
8
  const ARCHIVE_SOURCE_KINDS = ['live', 'copy', 'export'];
9
- // Database and collection names: lowercase letters, digits and underscores, as derived by `storeName`.
10
9
  const STORE_NAME_PATTERN = /^[a-z0-9_]{1,63}$/;
11
10
 
12
11
  const archivedAttachmentSchema = new mongoose.Schema({
@@ -33,12 +32,10 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
33
32
  recordId: { type: String, default: null },
34
33
  whatsappId: { type: String, default: null },
35
34
  },
36
- // Set when the planner archived the record with its triage group; rows copied whole carry none.
37
35
  groupId: { type: String, default: null },
38
36
  // The schema snapshot whose field names key `fields`, so a later rename can be mapped back by field id.
39
37
  schemaId: { type: String, required: true },
40
38
  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
39
  source: {
43
40
  kind: { type: String, enum: ARCHIVE_SOURCE_KINDS, default: 'live' },
44
41
  baseId: { type: String, default: null },
@@ -50,7 +47,6 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
50
47
  schemaVersion: { type: Number, required: true, default: ARCHIVE_SCHEMA_VERSION },
51
48
  }, { minimize: false, versionKey: false });
52
49
 
53
- // One collection per table, so no index needs the base or the table.
54
50
  airtableArchiveRecordSchema.index({ 'patient.whatsappId': 1, createdTime: -1 });
55
51
  airtableArchiveRecordSchema.index({ 'patient.recordId': 1, createdTime: -1 });
56
52
  airtableArchiveRecordSchema.index({ createdTime: -1 });
@@ -74,7 +70,6 @@ const tableCountsSchema = new mongoose.Schema({
74
70
  attachmentsPending: { type: Number, default: 0 },
75
71
  }, { _id: false });
76
72
 
77
- // One eligible group as the plan saw it, so a later delete can name exactly the groups that were reviewed.
78
73
  const plannedGroupSchema = new mongoose.Schema({
79
74
  groupId: { type: String, required: true },
80
75
  // Every patient of the group's records: a shared questionnaire can join two patients.
@@ -88,7 +83,6 @@ const airtableArchiveRunSchema = new mongoose.Schema({
88
83
  runId: { type: String, required: true },
89
84
  baseId: { type: String, required: true },
90
85
  mode: { type: String, enum: ARCHIVE_RUN_MODES, required: true },
91
- // A mirror copies the base as it is, so it has no cutoff.
92
86
  cutoff: { type: Date, default: null },
93
87
  status: { type: String, enum: ARCHIVE_RUN_STATUSES, required: true, default: 'running' },
94
88
  startedAt: { type: Date, required: true },
@@ -126,7 +120,6 @@ const airtableArchiveTableSchema = new mongoose.Schema({
126
120
  _id: { type: String, required: true },
127
121
  baseId: { type: String, required: true },
128
122
  tableId: { type: String, required: true },
129
- // The table's current Airtable name, kept up to date by writers so readers find a renamed table.
130
123
  tableName: { type: String, default: null },
131
124
  dbName: { type: String, required: true },
132
125
  collectionName: { type: String, required: true },
@@ -159,11 +152,9 @@ const getAirtableArchiveTable = () => {
159
152
  const DUPLICATE_KEY_ERROR = 11000;
160
153
  const storeError = (code) => Object.assign(new Error(code), { code });
161
154
 
162
- // Airtable names as Mongo names: accents dropped, lowercase, every run of other characters one underscore.
163
155
  const storeName = (name) => String(name).normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase()
164
156
  .replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
165
157
 
166
- // The host names each base's database, e.g. `AirtableBase:appX` → `symptoms`; an unmapped base has nowhere to go.
167
158
  const baseDatabaseKey = (baseId) => `AirtableBase:${baseId}`;
168
159
 
169
160
  function baseDatabase(baseId) {
@@ -200,7 +191,6 @@ async function pinCollection({ baseId, tableId, tableName, db }) {
200
191
  return pinned.collectionName;
201
192
  }
202
193
 
203
- // The collection a writer stores one table's records in, pinning it on first use.
204
194
  async function getAirtableTableRecords({ baseId, tableId, tableName }) {
205
195
  const db = baseDatabase(baseId);
206
196
  const key = `${db}:${baseId}:${tableId}:${tableName}`;
@@ -213,7 +203,6 @@ async function getAirtableTableRecords({ baseId, tableId, tableName }) {
213
203
  return recordModel(db, await pinnedCollections.get(key));
214
204
  }
215
205
 
216
- // Readers name a table as Airtable does now; one never written has no collection, so nothing of it is archived.
217
206
  async function findAirtableTableRecords({ baseId, tableName }) {
218
207
  const db = baseDatabase(baseId);
219
208
  const pinned = await getAirtableArchiveTable().findOne({ baseId, dbName: db, tableName }, { collectionName: 1 }).lean();
@@ -181,7 +181,6 @@ 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
184
  async function tableModels(baseId, schema) {
186
185
  const models = new Map();
187
186
  for (const table of Object.values(schema.tables)) {
@@ -196,7 +195,6 @@ const idsByTableOf = (entries) => {
196
195
  return idsByTable;
197
196
  };
198
197
 
199
- // The stored copies of a batch spanning tables, keyed by record id.
200
198
  async function findCopies(models, entries, projection, filter = {}) {
201
199
  const copies = new Map();
202
200
  for (const [table, ids] of idsByTableOf(entries)) {
@@ -344,7 +342,6 @@ function restoreDeletedLinks(fields, reference, linkNames, goneIds) {
344
342
  return restored;
345
343
  }
346
344
 
347
- // Why a record must stay in Airtable, or null when its archived copy can stand in for it.
348
345
  function deleteBlocker({ whole, scanned, doc, table, group, patient, schema, goneIds }) {
349
346
  if (!whole) return 'gone_from_source';
350
347
  const linkNames = linkNamesOf(schema, table);
@@ -385,7 +382,6 @@ async function goneLinkedIds({ entries, wholeById, archived, schema, liveIds, cu
385
382
  }
386
383
  }
387
384
  if (!missing.size) return new Set();
388
- // A link names no table, so every archived table is asked.
389
385
  const gone = new Set();
390
386
  for (const Records of models.values()) {
391
387
  (await Records.find({ _id: { $in: [...missing] }, sourceDeletedAt: { $ne: null }, createdTime: { $lt: cutoff } }, { _id: 1 }).lean()).forEach((doc) => gone.add(doc._id));
@@ -531,7 +527,6 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date(), gro
531
527
  // Only a plan stores its groups: a copy run's list would include groups it held back, so slices are picked from plans.
532
528
  const eligibleGroups = mode === 'plan' ? plan.eligible.map((group) => plannedGroup(group, patientsWithRecent)) : [];
533
529
  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
530
  const errorCode = (failed && 'records_failed') || ((groups.notEligible || groups.unverified) && 'groups_not_deleted') || null;
536
531
  const summary = {
537
532
  runId, mode, cutoff, status: errorCode ? 'failed' : 'succeeded',
@@ -555,7 +550,6 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date(), gro
555
550
 
556
551
  module.exports = {
557
552
  runArchive,
558
- // Shared with the mirror, which runs under the same single-flight lease per base.
559
553
  archiveError,
560
554
  acquireRun,
561
555
  leaseFor,
@@ -31,7 +31,6 @@ function patientFieldsOf(table) {
31
31
  if (PATIENT_FIELDS[table.id]) return { link: PATIENT_FIELDS[table.id], whatsapp: WHATSAPP_FIELDS[table.id] || null };
32
32
  const links = table.fields.filter((f) => LINK_FIELD_TYPES.includes(f.type) && f.options?.linkedTableId === PATIENT_TABLE.ID);
33
33
  if (links.length !== 1) return null;
34
- // With one link to the patients table, a lookup of their WhatsApp id can only go through it.
35
34
  const whatsapp = table.fields.find((f) => f.options?.fieldIdInLinkedTable === PATIENT_TABLE.WHATSAPP);
36
35
  return { link: links[0].id, whatsapp: whatsapp?.id || null };
37
36
  }
@@ -51,7 +50,6 @@ function patientFor(previous, current) {
51
50
  return current;
52
51
  }
53
52
 
54
- // Stamps a mirror set because a scan missed the record; those are undone when it shows up again.
55
53
  async function mirrorStampsOf(docs) {
56
54
  const stampRunIds = [...new Set(docs.filter((doc) => doc.sourceDeletedAt && doc.deleteRunId).map((doc) => doc.deleteRunId))];
57
55
  if (!stampRunIds.length) return new Set();
@@ -91,7 +89,6 @@ async function mirrorPage({ baseId, runId, table, page, Records, names, computed
91
89
  counts.unchanged += 1;
92
90
  continue;
93
91
  }
94
- // Attachments past the run's budget stay unhosted, so the record is rewritten by the next run that has room.
95
92
  const hostable = attachments.filter(({ item }) => {
96
93
  if (alreadyHosted.has(item.id)) return true;
97
94
  if (budget.attachments <= 0) return false;
@@ -103,7 +100,6 @@ async function mirrorPage({ baseId, runId, table, page, Records, names, computed
103
100
  try {
104
101
  hosted = await rehostAttachments({ baseId, tableId: table.id, recordId: record.id, attachments: hostable, alreadyHosted });
105
102
  } catch (error) {
106
- // The fields are copied anyway; the attachments left unhosted are retried by the next run.
107
103
  hosted = hostable.filter(({ item }) => alreadyHosted.has(item.id)).map(({ item }) => alreadyHosted.get(item.id));
108
104
  counts.attachmentsPending += hostable.length - hosted.length;
109
105
  logger.error('[airtableMirror] Attachments not hosted', { runId, table: table.name, recordId: record.id, errorCode: error?.code || 'UNKNOWN' });
@@ -144,7 +140,6 @@ async function mirrorPage({ baseId, runId, table, page, Records, names, computed
144
140
  }
145
141
  }
146
142
 
147
- // Copies the scan missed after a full read were deleted from Airtable; too many at once reads as a bad scan instead.
148
143
  async function markGone({ Records, runId, table, seen, counts, now }) {
149
144
  const stored = await Records.find({ sourceDeletedAt: null, 'source.kind': 'live' }, { _id: 1 }).lean();
150
145
  const gone = stored.map((doc) => doc._id).filter((id) => !seen.has(id));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.78.0-dev.16671",
3
+ "version": "5.78.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",