@peopl-health/nexus 6.0.28 → 6.0.29
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';
|
|
@@ -22,6 +22,9 @@ const MAX_RETRIES_PER_PASS = 3;
|
|
|
22
22
|
const CLAIM_TTL_MS = 60 * 60 * 1000;
|
|
23
23
|
const DEFAULT_SWEEP_INTERVAL_MS = 10 * 60 * 1000;
|
|
24
24
|
const RETRY_SETTLE_MS = 5 * 60 * 1000;
|
|
25
|
+
const DEFAULT_FAST_SWEEP_INTERVAL_MS = 60 * 1000;
|
|
26
|
+
// The interrupted process may still finish its run while it drains (auna hard-exits by ~29 s).
|
|
27
|
+
const INTERRUPT_SETTLE_MS = 30 * 1000;
|
|
25
28
|
|
|
26
29
|
const retryClaims = new WriteClaimStore({ namespace: 'recom-orphan-retry', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
27
30
|
const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttlMs: SCAN_WINDOW_MS, maxSize: 500 });
|
|
@@ -41,6 +44,7 @@ const FAILURE_REASONS = {
|
|
|
41
44
|
profile_read_failed: 'no se pudo leer el perfil clínico',
|
|
42
45
|
no_clinical_profile: 'la paciente no tiene perfil clínico',
|
|
43
46
|
error: 'el generador falló inesperadamente',
|
|
47
|
+
shutdown_interrupted: 'el servidor se reinició mientras se generaban las recomendaciones',
|
|
44
48
|
};
|
|
45
49
|
|
|
46
50
|
const FIELDS = ['Created', 'triaje_symptoms_id', 'whatsapp_id', 'symptom_name_positive'];
|
|
@@ -208,19 +212,72 @@ async function sweepUnrecoveredTriages({
|
|
|
208
212
|
return { scanned: orphans.length, retried, alerted, skipped };
|
|
209
213
|
}
|
|
210
214
|
|
|
211
|
-
function
|
|
212
|
-
|
|
213
|
-
|
|
215
|
+
async function sweepInterruptedTriages({
|
|
216
|
+
now = new Date(),
|
|
217
|
+
leases = inflightLeases,
|
|
218
|
+
retrigger = retriggerTriage,
|
|
219
|
+
retryLive = recommendationRetryLive,
|
|
220
|
+
claims = retryClaims,
|
|
221
|
+
isPaused = botIsPaused,
|
|
222
|
+
} = {}) {
|
|
223
|
+
const result = { found: 0, retried: 0, skipped: 0 };
|
|
224
|
+
if (!retryLive()) return result;
|
|
225
|
+
const active = await leases.listActive();
|
|
226
|
+
if (!active) return result;
|
|
227
|
+
|
|
228
|
+
const due = active.filter(({ value }) => value.source === programSource()
|
|
229
|
+
&& now.getTime() - Date.parse(value.startedAt) <= RETRY_MAX_AGE_MS
|
|
230
|
+
&& now.getTime() - Date.parse(value.interruptedAt) >= INTERRUPT_SETTLE_MS);
|
|
231
|
+
result.found = due.length;
|
|
232
|
+
|
|
233
|
+
for (const { key: triageRecordId, value } of due) {
|
|
234
|
+
const run = { triageRecordId, code: value.code, startedAt: value.startedAt };
|
|
235
|
+
if (result.retried >= MAX_RETRIES_PER_PASS || await isPaused(run.code)) {
|
|
236
|
+
result.skipped += 1;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const claim = await claims.acquire(`${triageRecordId}:${value.startedAt}`, 'retried');
|
|
240
|
+
if (claim !== 'acquired') {
|
|
241
|
+
result.skipped += 1;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
logger.error('[recommendationRecovery] triage run was interrupted by a shutdown, retrying', run);
|
|
245
|
+
try {
|
|
246
|
+
await retrigger(run);
|
|
247
|
+
result.retried += 1;
|
|
248
|
+
} catch (error) {
|
|
249
|
+
await claims.release(`${triageRecordId}:${value.startedAt}`);
|
|
250
|
+
logger.error('[recommendationRecovery] retry of an interrupted run could not be dispatched', { ...run, error: error.message });
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function configuredIntervalMs(key, fallback) {
|
|
257
|
+
const raw = Number(runtimeConfig.get(key));
|
|
258
|
+
return Number.isFinite(raw) && raw > 0 ? raw : fallback;
|
|
214
259
|
}
|
|
215
260
|
|
|
216
261
|
const sweeper = createIntervalSweeper({
|
|
217
262
|
label: '[recommendationRecovery]',
|
|
218
263
|
sweep: () => sweepUnrecoveredTriages(),
|
|
219
|
-
defaultIntervalMs:
|
|
264
|
+
defaultIntervalMs: () => configuredIntervalMs('RECOMMENDATION_RECOVERY_SWEEP_INTERVAL_MS', DEFAULT_SWEEP_INTERVAL_MS),
|
|
220
265
|
});
|
|
221
266
|
|
|
222
|
-
const
|
|
223
|
-
|
|
267
|
+
const fastSweeper = createIntervalSweeper({
|
|
268
|
+
label: '[recommendationRecovery:fast]',
|
|
269
|
+
sweep: () => sweepInterruptedTriages(),
|
|
270
|
+
defaultIntervalMs: () => DEFAULT_FAST_SWEEP_INTERVAL_MS,
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
function startRecommendationRecoverySweep(options) {
|
|
274
|
+
fastSweeper.start();
|
|
275
|
+
return sweeper.start(options);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function stopRecommendationRecoverySweep() {
|
|
279
|
+
return Promise.all([sweeper.stop(), fastSweeper.stop()]).then(() => undefined);
|
|
280
|
+
}
|
|
224
281
|
|
|
225
282
|
module.exports = {
|
|
226
283
|
botIsPaused,
|
|
@@ -228,6 +285,7 @@ module.exports = {
|
|
|
228
285
|
stopRecommendationRecoverySweep,
|
|
229
286
|
DEFAULT_SWEEP_INTERVAL_MS,
|
|
230
287
|
sweepUnrecoveredTriages,
|
|
288
|
+
sweepInterruptedTriages,
|
|
231
289
|
orphanFormula,
|
|
232
290
|
_fileOpsTicket: fileOpsTicket,
|
|
233
291
|
_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,7 +140,20 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, sup
|
|
|
133
140
|
}
|
|
134
141
|
generationState.set(payload.triageRecordId, true);
|
|
135
142
|
const startedAt = Date.now();
|
|
136
|
-
|
|
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;
|
|
156
|
+
inflight.leaseWritten
|
|
137
157
|
.then(() => generateTriageRecommendations({ payload, provider: requireGatewayProvider(), runId, supportRouting }))
|
|
138
158
|
.then((settle) => {
|
|
139
159
|
logger.info('[triageRecommendation] settled', { code: payload.patientCode, triageRecordId: payload.triageRecordId, status: settle.status, reason: settle.reason });
|
|
@@ -157,9 +177,37 @@ 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.interrupted;
|
|
185
|
+
await inflightLeases.release(payload.triageRecordId);
|
|
160
186
|
});
|
|
161
187
|
}
|
|
162
188
|
|
|
189
|
+
async function interruptInflightTriageRuns() {
|
|
190
|
+
shuttingDown = true;
|
|
191
|
+
const runs = [...inflightRuns.values()].filter((run) => !run.interrupted);
|
|
192
|
+
if (!runs.length) return 0;
|
|
193
|
+
logger.warn('[triageRecommendation] shutdown interrupted runs in flight', {
|
|
194
|
+
count: runs.length, triageRecordIds: runs.map((run) => run.payload.triageRecordId),
|
|
195
|
+
});
|
|
196
|
+
for (const run of runs) {
|
|
197
|
+
run.interrupted = run.leaseWritten
|
|
198
|
+
.then(() => inflightLeases.set(run.payload.triageRecordId, { ...run.lease, interrupted: true, interruptedAt: new Date().toISOString() }));
|
|
199
|
+
}
|
|
200
|
+
const written = Promise.allSettled(runs.flatMap((run) => [
|
|
201
|
+
run.interrupted,
|
|
202
|
+
recordSettleEvent({
|
|
203
|
+
payload: run.payload, trigger: run.trigger, runId: run.lease.runId, status: 'failed', stage: 'error', reason: 'shutdown_interrupted',
|
|
204
|
+
}),
|
|
205
|
+
]));
|
|
206
|
+
await withTimeout(written, INTERRUPT_TIMEOUT_MS, 'triage.interrupt')
|
|
207
|
+
.catch((error) => logger.warn('[triageRecommendation] could not record every interrupted run', { error: error.message }));
|
|
208
|
+
return runs.length;
|
|
209
|
+
}
|
|
210
|
+
|
|
163
211
|
function defaultRunId(payload) {
|
|
164
212
|
return `${TRIAGE_RUN_PREFIX}${payload.triageRecordId}`;
|
|
165
213
|
}
|
|
@@ -1230,5 +1278,8 @@ module.exports = {
|
|
|
1230
1278
|
backoffSchedule,
|
|
1231
1279
|
settleLossIsCritical,
|
|
1232
1280
|
handleTriageCompleted,
|
|
1281
|
+
interruptInflightTriageRuns,
|
|
1233
1282
|
generateTriageRecommendations,
|
|
1283
|
+
inflightLeases,
|
|
1284
|
+
_resetShutdown: () => { shuttingDown = false; },
|
|
1234
1285
|
};
|
|
@@ -108,6 +108,18 @@ class WriteClaimStore {
|
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
async listActive() {
|
|
112
|
+
if (!this._durable()) return null;
|
|
113
|
+
try {
|
|
114
|
+
const claims = await WriteClaim.find({ key: new RegExp(`^${this.namespace}:`), expiresAt: { $gt: new Date() } })
|
|
115
|
+
.limit(100).lean();
|
|
116
|
+
return claims.map((claim) => ({ key: claim.key.slice(this.namespace.length + 1), value: claim.value }));
|
|
117
|
+
} catch (error) {
|
|
118
|
+
logger.warn('[writeClaimStore] Claims could not be listed', { namespace: this.namespace, error: error.message });
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
111
123
|
async release(key) {
|
|
112
124
|
this.memory.delete(key);
|
|
113
125
|
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 }));
|