@peopl-health/nexus 6.0.28 → 6.0.30

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.
@@ -10,7 +10,7 @@ const { escapeFormulaValue } = require('../../helpers/airtableFormulaHelper');
10
10
  const { createIntervalSweeper } = require('../../utils/intervalSweeper');
11
11
  const { botIsPaused: threadIsPaused } = require('../../helpers/pausedThreadHelper');
12
12
  const { recordUnresolvedRequest } = require('./clinicalAirtableService');
13
- const { handleTriageCompleted } = require('./triageRecommendationService');
13
+ const { handleTriageCompleted, inflightLeases } = require('./triageRecommendationService');
14
14
  const { WriteClaimStore } = require('./writeClaimStore');
15
15
 
16
16
  const TRIAGE_TABLE = 'triaje_symptoms';
@@ -19,9 +19,13 @@ const MIN_AGE_MS = 15 * 60 * 1000;
19
19
  const RETRY_MAX_AGE_MS = 60 * 60 * 1000;
20
20
  const MAX_CANDIDATES = 20;
21
21
  const MAX_RETRIES_PER_PASS = 3;
22
+ const TRANSIENT_DISPATCH_FAILURES = new Set(['triage_read_failed', 'patient_read_failed', 'item_read_failed']);
22
23
  const CLAIM_TTL_MS = 60 * 60 * 1000;
23
24
  const DEFAULT_SWEEP_INTERVAL_MS = 10 * 60 * 1000;
24
25
  const RETRY_SETTLE_MS = 5 * 60 * 1000;
26
+ const DEFAULT_FAST_SWEEP_INTERVAL_MS = 60 * 1000;
27
+ // The interrupted process may still finish its run while it drains (auna hard-exits by ~29 s).
28
+ const INTERRUPT_SETTLE_MS = 30 * 1000;
25
29
 
26
30
  const retryClaims = new WriteClaimStore({ namespace: 'recom-orphan-retry', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
27
31
  const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttlMs: SCAN_WINDOW_MS, maxSize: 500 });
@@ -41,6 +45,7 @@ const FAILURE_REASONS = {
41
45
  profile_read_failed: 'no se pudo leer el perfil clínico',
42
46
  no_clinical_profile: 'la paciente no tiene perfil clínico',
43
47
  error: 'el generador falló inesperadamente',
48
+ shutdown_interrupted: 'el servidor se reinició mientras se generaban las recomendaciones',
44
49
  };
45
50
 
46
51
  const FIELDS = ['Created', 'triaje_symptoms_id', 'whatsapp_id', 'symptom_name_positive'];
@@ -208,19 +213,72 @@ async function sweepUnrecoveredTriages({
208
213
  return { scanned: orphans.length, retried, alerted, skipped };
209
214
  }
210
215
 
211
- function sweepIntervalMs() {
212
- const raw = Number(runtimeConfig.get('RECOMMENDATION_RECOVERY_SWEEP_INTERVAL_MS'));
213
- return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SWEEP_INTERVAL_MS;
216
+ async function sweepInterruptedTriages({
217
+ now = new Date(),
218
+ leases = inflightLeases,
219
+ retrigger = retriggerTriage,
220
+ retryLive = recommendationRetryLive,
221
+ claims = retryClaims,
222
+ isPaused = botIsPaused,
223
+ } = {}) {
224
+ const result = { found: 0, retried: 0, skipped: 0 };
225
+ if (!retryLive()) return result;
226
+ const active = await leases.listActive({ interrupted: true, source: programSource() });
227
+ if (!active) return result;
228
+
229
+ const due = active.filter(({ value }) => value.source === programSource()
230
+ && now.getTime() - Date.parse(value.startedAt) <= RETRY_MAX_AGE_MS
231
+ && now.getTime() - Date.parse(value.interruptedAt) >= INTERRUPT_SETTLE_MS);
232
+ result.found = due.length;
233
+
234
+ for (const { key: triageRecordId, value } of due) {
235
+ const run = { triageRecordId, code: value.code, startedAt: value.startedAt };
236
+ if (result.retried >= MAX_RETRIES_PER_PASS || await isPaused(run.code)) {
237
+ result.skipped += 1;
238
+ continue;
239
+ }
240
+ const claim = await claims.acquire(`${triageRecordId}:${value.startedAt}`, 'retried');
241
+ if (claim !== 'acquired') {
242
+ result.skipped += 1;
243
+ continue;
244
+ }
245
+ logger.error('[recommendationRecovery] triage run was interrupted by a shutdown, retrying', run);
246
+ try {
247
+ await retrigger(run);
248
+ result.retried += 1;
249
+ } catch (error) {
250
+ if (TRANSIENT_DISPATCH_FAILURES.has(error.message)) await claims.release(`${triageRecordId}:${value.startedAt}`);
251
+ logger.error('[recommendationRecovery] retry of an interrupted run could not be dispatched', { ...run, error: error.message });
252
+ }
253
+ }
254
+ return result;
255
+ }
256
+
257
+ function configuredIntervalMs(key, fallback) {
258
+ const raw = Number(runtimeConfig.get(key));
259
+ return Number.isFinite(raw) && raw > 0 ? raw : fallback;
214
260
  }
215
261
 
216
262
  const sweeper = createIntervalSweeper({
217
263
  label: '[recommendationRecovery]',
218
264
  sweep: () => sweepUnrecoveredTriages(),
219
- defaultIntervalMs: sweepIntervalMs,
265
+ defaultIntervalMs: () => configuredIntervalMs('RECOMMENDATION_RECOVERY_SWEEP_INTERVAL_MS', DEFAULT_SWEEP_INTERVAL_MS),
220
266
  });
221
267
 
222
- const startRecommendationRecoverySweep = (options) => sweeper.start(options);
223
- const stopRecommendationRecoverySweep = () => sweeper.stop();
268
+ const fastSweeper = createIntervalSweeper({
269
+ label: '[recommendationRecovery:fast]',
270
+ sweep: () => sweepInterruptedTriages(),
271
+ defaultIntervalMs: () => DEFAULT_FAST_SWEEP_INTERVAL_MS,
272
+ });
273
+
274
+ function startRecommendationRecoverySweep(options) {
275
+ fastSweeper.start();
276
+ return sweeper.start(options);
277
+ }
278
+
279
+ function stopRecommendationRecoverySweep() {
280
+ return Promise.all([sweeper.stop(), fastSweeper.stop()]).then(() => undefined);
281
+ }
224
282
 
225
283
  module.exports = {
226
284
  botIsPaused,
@@ -228,6 +286,7 @@ module.exports = {
228
286
  stopRecommendationRecoverySweep,
229
287
  DEFAULT_SWEEP_INTERVAL_MS,
230
288
  sweepUnrecoveredTriages,
289
+ sweepInterruptedTriages,
231
290
  orphanFormula,
232
291
  _fileOpsTicket: fileOpsTicket,
233
292
  _handledClaims: retryClaims,
@@ -29,6 +29,7 @@ const { mexicoDay } = require('../../utils/dateUtils');
29
29
  const runtimeConfig = require('../../config/runtimeConfig');
30
30
  const { triageRecommendationLive } = require('../flags/triageRecommendationFlags');
31
31
  const { Symptoms_ID } = require('../../config/airtableConfig');
32
+ const { programSource } = require('../../config/programConfig');
32
33
  const { TRIAGE_RUN_PREFIX } = require('../../fhir/helpers/recommendationIds');
33
34
  const {
34
35
  storeTriage,
@@ -58,6 +59,7 @@ const {
58
59
  safeParse, isPlainObject, objectArg, arrayArg,
59
60
  } = require('../../utils/jsonUtils');
60
61
  const { logger } = require('../../utils/logger');
62
+ const { withTimeout } = require('../../utils/timeoutUtils');
61
63
  const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
62
64
  const {
63
65
  symptomKeySet,
@@ -73,6 +75,7 @@ const { recordClusterRecommendationsMirror } = require('./clinicalAirtableServic
73
75
  const { evaluateSupportRouting } = require('./supportRoutingAgentService');
74
76
  const { recordSupportRoutingRecommendation, settleInvitation, updateSupportOperationalReview } = require('./supportCandidateService');
75
77
  const { prepareSupportAction } = require('./supportActionService');
78
+ const { WriteClaimStore } = require('./writeClaimStore');
76
79
 
77
80
  const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
78
81
  const GATE_MAX_ATTEMPTS = 2;
@@ -89,6 +92,10 @@ const PRIOR_TRIAGE_RX = /^rec[A-Za-z0-9]{14,}$/;
89
92
  const PATIENT_LOOKUP_FIELD = 'patient_id (from triaje_symptoms) (from cluster_recommendations)';
90
93
 
91
94
  const generationState = new MapCache({ maxSize: 2000, ttl: GENERATION_BACKOFF_MS });
95
+ const inflightRuns = new Map();
96
+ let shuttingDown = false;
97
+ const inflightLeases = new WriteClaimStore({ namespace: 'triage-inflight', ttlMs: 2 * 60 * 60 * 1000, maxSize: 2000 });
98
+ const INTERRUPT_TIMEOUT_MS = 1500;
92
99
  const FREE_TEXT_SYMPTOM_FIELDS = ['freetext_derived', 'corresponding_CTCAE', 'grade_num'];
93
100
 
94
101
  function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, supportRouting = {} } = {}) {
@@ -133,6 +140,19 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, sup
133
140
  }
134
141
  generationState.set(payload.triageRecordId, true);
135
142
  const startedAt = Date.now();
143
+ const lease = {
144
+ runId: runId || defaultRunId(payload),
145
+ trigger,
146
+ code: payload.patientCode,
147
+ source: programSource(),
148
+ startedAt: new Date(startedAt).toISOString(),
149
+ interrupted: shuttingDown,
150
+ ...(shuttingDown ? { interruptedAt: new Date(startedAt).toISOString() } : {}),
151
+ };
152
+ const inflight = { payload, trigger, lease };
153
+ inflightRuns.set(payload.triageRecordId, inflight);
154
+ inflight.leaseWritten = inflightLeases.set(payload.triageRecordId, lease);
155
+ if (shuttingDown) inflight.interrupted = inflight.leaseWritten;
136
156
  Promise.resolve()
137
157
  .then(() => generateTriageRecommendations({ payload, provider: requireGatewayProvider(), runId, supportRouting }))
138
158
  .then((settle) => {
@@ -157,9 +177,38 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, sup
157
177
  stage: 'error',
158
178
  reason: 'error',
159
179
  });
180
+ })
181
+ .finally(async () => {
182
+ if (inflightRuns.get(payload.triageRecordId) !== inflight) return;
183
+ inflightRuns.delete(payload.triageRecordId);
184
+ await inflight.leaseWritten;
185
+ await inflight.interrupted;
186
+ await inflightLeases.release(payload.triageRecordId);
160
187
  });
161
188
  }
162
189
 
190
+ async function interruptInflightTriageRuns() {
191
+ shuttingDown = true;
192
+ const runs = [...inflightRuns.values()].filter((run) => !run.interrupted);
193
+ if (!runs.length) return 0;
194
+ logger.warn('[triageRecommendation] shutdown interrupted runs in flight', {
195
+ count: runs.length, triageRecordIds: runs.map((run) => run.payload.triageRecordId),
196
+ });
197
+ for (const run of runs) {
198
+ run.interrupted = run.leaseWritten
199
+ .then(() => inflightLeases.set(run.payload.triageRecordId, { ...run.lease, interrupted: true, interruptedAt: new Date().toISOString() }));
200
+ }
201
+ const written = Promise.allSettled(runs.flatMap((run) => [
202
+ run.interrupted,
203
+ recordSettleEvent({
204
+ payload: run.payload, trigger: run.trigger, runId: run.lease.runId, status: 'failed', stage: 'error', reason: 'shutdown_interrupted',
205
+ }),
206
+ ]));
207
+ await withTimeout(written, INTERRUPT_TIMEOUT_MS, 'triage.interrupt')
208
+ .catch((error) => logger.warn('[triageRecommendation] could not record every interrupted run', { error: error.message }));
209
+ return runs.length;
210
+ }
211
+
163
212
  function defaultRunId(payload) {
164
213
  return `${TRIAGE_RUN_PREFIX}${payload.triageRecordId}`;
165
214
  }
@@ -1230,5 +1279,8 @@ module.exports = {
1230
1279
  backoffSchedule,
1231
1280
  settleLossIsCritical,
1232
1281
  handleTriageCompleted,
1282
+ interruptInflightTriageRuns,
1233
1283
  generateTriageRecommendations,
1284
+ inflightLeases,
1285
+ _resetShutdown: () => { shuttingDown = false; },
1234
1286
  };
@@ -108,6 +108,19 @@ class WriteClaimStore {
108
108
  }
109
109
  }
110
110
 
111
+ async listActive(valueMatch = {}) {
112
+ if (!this._durable()) return null;
113
+ const query = { key: new RegExp(`^${this.namespace}:`), expiresAt: { $gt: new Date() } };
114
+ for (const [field, expected] of Object.entries(valueMatch)) query[`value.${field}`] = expected;
115
+ try {
116
+ const claims = await WriteClaim.find(query).sort({ createdAt: -1 }).limit(100).lean();
117
+ return claims.map((claim) => ({ key: claim.key.slice(this.namespace.length + 1), value: claim.value }));
118
+ } catch (error) {
119
+ logger.warn('[writeClaimStore] Claims could not be listed', { namespace: this.namespace, error: error.message });
120
+ return null;
121
+ }
122
+ }
123
+
111
124
  async release(key) {
112
125
  this.memory.delete(key);
113
126
  if (!this._durable()) return;
package/lib/index.js CHANGED
@@ -31,6 +31,7 @@ const { configureSafetyNet } = require('./clinical/config/safetyNetConfig');
31
31
  const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNetService');
32
32
  const { ensureOnePledgePerContact, startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
33
33
  const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
34
+ const { interruptInflightTriageRuns } = require('./clinical/services/triageRecommendationService');
34
35
  const { configureProgram } = require('./config/programConfig');
35
36
  const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
36
37
  const { startReviewDraftSweep } = require('./services/reviewDraftSweepService');
@@ -326,9 +327,10 @@ class Nexus {
326
327
  async shutdown({ drainMs, abortGraceMs, teardownMs, sweepStopMs = 2000, closeStorage = true } = {}) {
327
328
  if (this._shutdownPromise) return this._shutdownPromise;
328
329
  const sweepsSettled = stopAllSweeps({ timeoutMs: sweepStopMs, label: '[Nexus]' });
330
+ const triageRunsInterrupted = interruptInflightTriageRuns();
329
331
  this._shutdownPromise = (async () => {
330
332
  const result = await this.messaging.shutdown({ drainMs, abortGraceMs, teardownMs });
331
- await sweepsSettled;
333
+ await Promise.all([sweepsSettled, triageRunsInterrupted]);
332
334
  if (closeStorage && this.storage) {
333
335
  await withTimeout(this.storage.disconnect(), teardownMs ?? 5000, 'storage.disconnect')
334
336
  .catch(error => logger.warn('[Nexus] Storage disconnect did not finish', { error: error.message }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.28",
3
+ "version": "6.0.30",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",