@peopl-health/nexus 5.54.0-dev.7843 → 5.54.0-dev.7847

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/README.md CHANGED
@@ -116,38 +116,6 @@ const bus = nexus.getMessaging().getEventBus();
116
116
  bus.on('message:received', (m) => console.log('rx', m.id));
117
117
  ```
118
118
 
119
- ## Workflows (Optional)
120
-
121
- Register a named unit of work, deduplicated by a key you derive from the trigger.
122
-
123
- ```js
124
- const runner = nexus.getMessaging().getWorkflowRunner();
125
-
126
- await runner.register({
127
- kind: 'triage-projection',
128
- dedupeKey: (trigger) => String(trigger.submissionId),
129
- prepare: async (trigger, checkpoints, save) => { /* ... */ },
130
- retrySchedule: [5, 10, 20, 40], // minutes; omit for fire-and-forget
131
- });
132
-
133
- await runner.enqueue('triage-projection', { submissionId });
134
- ```
135
-
136
- With `retrySchedule` the trigger and a checkpoint journal are stored in Mongo and the schedule runs
137
- on an in-process timer — deferred workflows never touch the queue adapter, so they add no Redis load.
138
- `prepare` resumes from `checkpoints`; call `save(patch)` before each external call so a retry does
139
- not repeat completed work. Throw an error carrying `permanent: true` to give up immediately instead
140
- of walking the schedule; the Airtable helpers tag their own permanent 4xx errors that way, in
141
- `withAirtableRetry`, which all five of them route through. They rethrow on failure too, so an
142
- Airtable outage reaches `prepare` as an exception and walks the retry schedule on its own rather
143
- than reading as success.
144
-
145
- Recovery is automatic: registering sweeps for work left behind by a previous process, and the runner
146
- keeps sweeping so work whose worker died mid-`prepare` is reclaimed once its claim goes stale.
147
- `enqueue` on an abandoned key revives it, keeping its checkpoints. Work is retained for 24 hours
148
- after its last update and then expires — the dedupe key expires with it, so idempotency has the
149
- same horizon as retention.
150
-
151
119
  ## Assistants (Optional)
152
120
 
153
121
  Register assistant classes and (optionally) a custom resolver. OpenAI is supported via `llm: 'openai'`.
@@ -4,6 +4,8 @@ const { logger } = require('../../utils/logger');
4
4
  const { getRecordByFilter } = require('../../services/airtableService');
5
5
  const { recommendationRetryLive } = require('../flags/recommendationRecoveryFlags');
6
6
  const { Thread } = require('../../models/threadModel');
7
+ const runtimeConfig = require('../../config/runtimeConfig');
8
+ const { createIntervalSweeper } = require('../../utils/intervalSweeper');
7
9
  const { recordUnresolvedRequest } = require('./clinicalAirtableService');
8
10
  const { handleTriageCompleted } = require('./triageRecommendationService');
9
11
  const { WriteClaimStore } = require('./writeClaimStore');
@@ -15,6 +17,8 @@ const RETRY_MAX_AGE_MS = 60 * 60 * 1000;
15
17
  const MAX_CANDIDATES = 20;
16
18
  const MAX_RETRIES_PER_PASS = 3;
17
19
  const CLAIM_TTL_MS = 60 * 60 * 1000;
20
+ const DEFAULT_SWEEP_INTERVAL_MS = 10 * 60 * 1000;
21
+ const RETRY_SETTLE_MS = 5 * 60 * 1000;
18
22
 
19
23
  const retryClaims = new WriteClaimStore({ namespace: 'recom-orphan-retry', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
20
24
  const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttlMs: SCAN_WINDOW_MS, maxSize: 500 });
@@ -118,21 +122,30 @@ async function sweepUnrecoveredTriages({
118
122
 
119
123
  if (fresh && canRetry && !paused && retried < MAX_RETRIES_PER_PASS) {
120
124
  const claim = await claims.acquire(orphan.triageRecordId, 'retried');
121
- if (claim === 'taken') { skipped += 1; continue; }
122
125
  if (claim === 'unavailable') {
123
126
  skipped += 1;
124
127
  logger.error('[recommendationRecovery] triage produced no recommendations and could not be claimed', { ...orphan, ageMs });
125
128
  continue;
126
129
  }
127
- logger.error('[recommendationRecovery] triage produced no recommendations, retrying', { ...orphan, ageMs });
128
- try {
129
- await retrigger(orphan);
130
- retried += 1;
131
- } catch (error) {
132
- await claims.release(orphan.triageRecordId);
133
- logger.error('[recommendationRecovery] retry could not be dispatched', { ...orphan, error: error.message });
130
+ if (claim === 'acquired') {
131
+ logger.error('[recommendationRecovery] triage produced no recommendations, retrying', { ...orphan, ageMs });
132
+ try {
133
+ await retrigger(orphan);
134
+ retried += 1;
135
+ } catch (error) {
136
+ await claims.release(orphan.triageRecordId);
137
+ logger.error('[recommendationRecovery] retry could not be dispatched', { ...orphan, error: error.message });
138
+ }
139
+ continue;
140
+ }
141
+
142
+ const claimedAt = typeof claims.claimedAtMs === 'function'
143
+ ? await claims.claimedAtMs(orphan.triageRecordId)
144
+ : null;
145
+ if (claimedAt === null || (now.getTime() - claimedAt) < RETRY_SETTLE_MS) {
146
+ skipped += 1;
147
+ continue;
134
148
  }
135
- continue;
136
149
  }
137
150
 
138
151
  const ticket = await ticketGate.acquire(orphan.triageRecordId, 'alerted');
@@ -161,8 +174,25 @@ async function sweepUnrecoveredTriages({
161
174
  return { scanned: orphans.length, retried, alerted, skipped };
162
175
  }
163
176
 
177
+ function sweepIntervalMs() {
178
+ const raw = Number(runtimeConfig.get('RECOMMENDATION_RECOVERY_SWEEP_INTERVAL_MS'));
179
+ return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SWEEP_INTERVAL_MS;
180
+ }
181
+
182
+ const sweeper = createIntervalSweeper({
183
+ label: '[recommendationRecovery]',
184
+ sweep: () => sweepUnrecoveredTriages(),
185
+ defaultIntervalMs: sweepIntervalMs,
186
+ });
187
+
188
+ const startRecommendationRecoverySweep = (options) => sweeper.start(options);
189
+ const stopRecommendationRecoverySweep = () => sweeper.stop();
190
+
164
191
  module.exports = {
165
192
  botIsPaused,
193
+ startRecommendationRecoverySweep,
194
+ stopRecommendationRecoverySweep,
195
+ DEFAULT_SWEEP_INTERVAL_MS,
166
196
  sweepUnrecoveredTriages,
167
197
  orphanFormula,
168
198
  _handledClaims: retryClaims,
@@ -172,4 +202,5 @@ module.exports = {
172
202
  RETRY_MAX_AGE_MS,
173
203
  MAX_CANDIDATES,
174
204
  MAX_RETRIES_PER_PASS,
205
+ RETRY_SETTLE_MS,
175
206
  };
@@ -1,4 +1,5 @@
1
1
  const { CONTACT_WINDOW, getPledgeMs, getSweepIntervalMs, humanReplyFilter } = require('../config/safetyNetConfig');
2
+ const { createIntervalSweeper } = require('../../utils/intervalSweeper');
2
3
  const { logger } = require('../../utils/logger');
3
4
  const { clampToHourWindow } = require('../../utils/scheduleUtils');
4
5
 
@@ -91,23 +92,14 @@ async function sweepSafetyNetPledges() {
91
92
  return breached;
92
93
  }
93
94
 
94
- let sweepTimer = null;
95
+ const sweeper = createIntervalSweeper({
96
+ label: '[SafetyNetPledge]',
97
+ sweep: () => sweepSafetyNetPledges(),
98
+ defaultIntervalMs: getSweepIntervalMs,
99
+ });
95
100
 
96
- function startSafetyNetSweep({ intervalMs = getSweepIntervalMs() } = {}) {
97
- if (sweepTimer) return sweepTimer;
98
- sweepTimer = setInterval(() => {
99
- sweepSafetyNetPledges().catch((error) =>
100
- logger.error('[SafetyNetPledge] Sweep failed', { error: error.message }));
101
- }, intervalMs);
102
- if (typeof sweepTimer.unref === 'function') sweepTimer.unref();
103
- return sweepTimer;
104
- }
105
-
106
- function stopSafetyNetSweep() {
107
- if (!sweepTimer) return;
108
- clearInterval(sweepTimer);
109
- sweepTimer = null;
110
- }
101
+ const startSafetyNetSweep = (options) => sweeper.start(options);
102
+ const stopSafetyNetSweep = () => sweeper.stop();
111
103
 
112
104
  module.exports = {
113
105
  startSafetyNetSweep,
@@ -73,6 +73,18 @@ class WriteClaimStore {
73
73
  }
74
74
  }
75
75
 
76
+ async claimedAtMs(key) {
77
+ if (!this._durable()) return null;
78
+ try {
79
+ const claim = await WriteClaim.findOne({ key: this._key(key) }, { expiresAt: 1 }).lean();
80
+ if (!claim?.expiresAt) return null;
81
+ return new Date(claim.expiresAt).getTime() - this.ttlMs;
82
+ } catch (error) {
83
+ logger.warn('[writeClaimStore] Claim age could not be read', { namespace: this.namespace, error: error.message });
84
+ return null;
85
+ }
86
+ }
87
+
76
88
  async release(key) {
77
89
  this.memory.delete(key);
78
90
  if (!this._durable()) return;
@@ -1,5 +1,7 @@
1
1
  const { _resetOverrides } = require('../config/runtimeConfig');
2
2
  const { _resetMetaConfig } = require('../config/metaConfig');
3
+ const { withTimeout } = require('../utils/timeoutUtils');
4
+ const { logger } = require('../utils/logger');
3
5
  const { _clearClinicalContextCache } = require('../helpers/patientInformationHelper');
4
6
  const { setPreprocessingHandler } = require('../services/preprocessingService');
5
7
  const { clearTriageHistoryCache } = require('../services/triageHistoryService');
@@ -8,12 +10,23 @@ const { _resetDefaultInstance } = require('../core/NexusMessaging');
8
10
  const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
9
11
  const { _resetSafetyNetState } = require('../clinical/services/pausedSafetyNetService');
10
12
  const { stopSafetyNetSweep } = require('../clinical/services/safetyNetPledgeService');
13
+ const { stopRecommendationRecoverySweep } = require('../clinical/services/recommendationRecoveryService');
11
14
  const { _clearRecentIntakeCache } = require('../clinical/services/clinicalAirtableService');
12
15
  const { _clearExtractorConfigCache } = require('../clinical/services/clinicalExtractionService');
13
16
  const { _resetRegistry } = require('../clinical/services/assistantResolver');
14
17
  const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
15
18
 
19
+ const SWEEP_STOP_MS = 2000;
20
+
21
+ function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
22
+ const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep()]);
23
+ return withTimeout(stopped, timeoutMs, 'sweeps.stop')
24
+ .catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
25
+ }
26
+
16
27
  function resetAll() {
28
+ const sweepsStopped = stopAllSweeps();
29
+
17
30
  _resetDefaultInstance();
18
31
  _resetRegistry();
19
32
  _resetLLMState();
@@ -21,13 +34,14 @@ function resetAll() {
21
34
  clearInteractiveRoutes();
22
35
  _resetSafetyNetConfig();
23
36
  _resetSafetyNetState();
24
- stopSafetyNetSweep();
25
37
  _resetOverrides();
26
38
  _resetMetaConfig();
27
39
  _clearClinicalContextCache();
28
40
  _clearRecentIntakeCache();
29
41
  _clearExtractorConfigCache();
30
42
  clearTriageHistoryCache();
43
+
44
+ return sweepsStopped;
31
45
  }
32
46
 
33
- module.exports = { resetAll };
47
+ module.exports = { resetAll, stopAllSweeps, SWEEP_STOP_MS };
@@ -30,7 +30,6 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
30
30
 
31
31
  const { BatchingManager } = require('../core/BatchingManager');
32
32
  const { ProcessingPipeline } = require('../core/ProcessingPipeline');
33
- const { sweepUnrecoveredTriages } = require('../clinical/services/recommendationRecoveryService');
34
33
  const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
35
34
  const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
36
35
  const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
@@ -46,7 +45,6 @@ const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
46
45
  const { createQueueAdapter } = require('../queue');
47
46
  const { ScheduledMessageJob } = require('../jobs/ScheduledMessageJob');
48
47
  const { TemplateApprovalJob } = require('../jobs/TemplateApprovalJob');
49
- const { WorkflowRunner } = require('./DeferredWorkRunner');
50
48
  const { invokeInteractiveRoute } = require('./interactiveRouteService');
51
49
 
52
50
  const { PhiProcessor } = require('./PhiProcessor');
@@ -136,8 +134,6 @@ class NexusMessaging {
136
134
  queueAdapter: this.queueAdapter,
137
135
  });
138
136
 
139
- this.workflowRunner = new WorkflowRunner({ queueAdapter: this.queueAdapter });
140
-
141
137
  this.phiProcessor = new PhiProcessor({
142
138
  encode: config.phi?.encode || false,
143
139
  ner: config.phi?.ner || null,
@@ -174,7 +170,6 @@ class NexusMessaging {
174
170
  ...(config.queueReconciliation || {}),
175
171
  scheduleMessage: (options) => this.scheduledMessageJob.schedule(options),
176
172
  scheduleTemplateApproval: (options) => this.scheduleTemplateApproval(options),
177
- sweepUnrecoveredTriages: () => sweepUnrecoveredTriages(),
178
173
  sweepHeldMessages: () => sweepHeldMessages()
179
174
  });
180
175
 
@@ -323,7 +318,6 @@ class NexusMessaging {
323
318
  getAssistantProcessor() { return this.assistantProcessor; }
324
319
  getLlmMonitor() { return this.llmMonitor; }
325
320
  getQueueAdapter() { return this.queueAdapter; }
326
- getWorkflowRunner() { return this.workflowRunner; }
327
321
  getPhiProcessor() { return this.phiProcessor; }
328
322
  isConnected() { return this.provider?.getConnectionStatus() ?? false; }
329
323
  isProcessing(chatId) { return this.batchingManager.isProcessing(chatId); }
@@ -1076,8 +1070,6 @@ class NexusMessaging {
1076
1070
  await withTimeout(this._reconciliationStopped, teardownMs, 'queueReconciliation.stop')
1077
1071
  .catch(error => logger.warn('[NexusMessaging] Reconciliation sweep did not settle in time', { error: error.message }));
1078
1072
 
1079
- if (this.workflowRunner) this.workflowRunner.stop();
1080
-
1081
1073
  if (this.queueAdapter) {
1082
1074
  await withTimeout(this.queueAdapter.shutdown(), teardownMs, 'queueAdapter.shutdown')
1083
1075
  .catch(error => logger.warn('[NexusMessaging] Queue shutdown did not finish', { error: error.message }));
package/lib/index.d.ts CHANGED
@@ -254,7 +254,6 @@ declare module '@peopl-health/nexus' {
254
254
  getAssistantProcessor(): AssistantProcessor;
255
255
  getLlmMonitor(): { start(options?: { scheduleDaily?: boolean }): Promise<{ enabled: boolean }> } | null;
256
256
  initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
257
- getWorkflowRunner(): WorkflowRunner;
258
257
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string }): Promise<void>;
259
258
  processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
260
259
  processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
@@ -331,6 +330,12 @@ declare module '@peopl-health/nexus' {
331
330
  parser?: boolean;
332
331
  parserConfig?: ParserConfig;
333
332
  ner?: NerOptions;
333
+ recommendationRecovery?: RecommendationRecoveryOptions;
334
+ }
335
+
336
+ export interface RecommendationRecoveryOptions {
337
+ enabled: boolean;
338
+ intervalMs?: number;
334
339
  }
335
340
 
336
341
  export interface NerEntity {
@@ -536,17 +541,16 @@ declare module '@peopl-health/nexus' {
536
541
  export interface Workflow {
537
542
  kind: string;
538
543
  dedupeKey: (trigger: any) => string;
539
- prepare: (trigger: any, checkpoints?: any, save?: (patch: any) => Promise<void>) => Promise<any>;
540
- retrySchedule?: number[];
544
+ prepare: (trigger: any) => Promise<any>;
541
545
  }
542
546
 
543
547
  export interface WorkflowRunner {
544
548
  register(workflow: Workflow): Promise<Workflow>;
545
- enqueue(kind: string, trigger: any, options?: QueueJobOptions): Promise<string | null>;
546
- sweep(only?: string[]): Promise<string[]>;
547
- stop(): void;
549
+ enqueue(kind: string, trigger: any, options?: QueueJobOptions): Promise<string>;
548
550
  }
549
551
 
552
+ export function createWorkflowRunner(options: { queueAdapter: QueueAdapter }): WorkflowRunner;
553
+
550
554
  // Memory System
551
555
  export interface PatientMemoryDocument {
552
556
  _id: any;
@@ -1011,6 +1015,8 @@ declare module '@peopl-health/nexus' {
1011
1015
  drainMs?: number;
1012
1016
  abortGraceMs?: number;
1013
1017
  teardownMs?: number;
1018
+ sweepStopMs?: number;
1019
+ closeStorage?: boolean;
1014
1020
  }
1015
1021
 
1016
1022
  export class DrainingError extends Error {
package/lib/index.js CHANGED
@@ -29,13 +29,14 @@ const { setPreprocessingHandler, hasPreprocessingHandler, invokePreprocessingHan
29
29
  const { registerInteractiveRoute, clearInteractiveRoutes } = require('./core/interactiveRouteService');
30
30
  const { configureSafetyNet } = require('./clinical/config/safetyNetConfig');
31
31
  const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNetService');
32
- const { startSafetyNetSweep, stopSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
32
+ const { startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
33
+ const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
33
34
  const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
34
35
  const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
35
36
  const { createWorkflowRunner } = require('./core/workflowRunner');
36
37
  const { DrainingError } = require('./core/BatchingManager');
37
38
  const routes = require('./routes');
38
- const { resetAll } = require('./config/lifecycle');
39
+ const { resetAll, stopAllSweeps } = require('./config/lifecycle');
39
40
  const { EvalProvider } = require('./eval/EvalProvider');
40
41
  const { syncContextFacts } = require('./clinical/services/contextSyncService');
41
42
  const { retractContentlessFacts } = require('./clinical/services/contextCleanupService');
@@ -198,6 +199,15 @@ class Nexus {
198
199
  logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
199
200
  }
200
201
 
202
+ try {
203
+ if (options.recommendationRecovery?.enabled === true) {
204
+ startRecommendationRecoverySweep({ intervalMs: options.recommendationRecovery.intervalMs });
205
+ logger.info('[Nexus] recommendation recovery sweep armed');
206
+ }
207
+ } catch (e) {
208
+ logger.warn('Warning: failed to arm the recommendation recovery sweep:', e?.message || e);
209
+ }
210
+
201
211
  await this.messaging.initializeLlmMonitor();
202
212
 
203
213
  this.isInitialized = true;
@@ -251,11 +261,12 @@ class Nexus {
251
261
  return this.messaging.getBatchingManager().isDraining();
252
262
  }
253
263
 
254
- async shutdown({ drainMs, abortGraceMs, teardownMs, closeStorage = true } = {}) {
255
- stopSafetyNetSweep();
264
+ async shutdown({ drainMs, abortGraceMs, teardownMs, sweepStopMs = 2000, closeStorage = true } = {}) {
256
265
  if (this._shutdownPromise) return this._shutdownPromise;
266
+ const sweepsSettled = stopAllSweeps({ timeoutMs: sweepStopMs, label: '[Nexus]' });
257
267
  this._shutdownPromise = (async () => {
258
268
  const result = await this.messaging.shutdown({ drainMs, abortGraceMs, teardownMs });
269
+ await sweepsSettled;
259
270
  if (closeStorage && this.storage) {
260
271
  await withTimeout(this.storage.disconnect(), teardownMs ?? 5000, 'storage.disconnect')
261
272
  .catch(error => logger.warn('[Nexus] Storage disconnect did not finish', { error: error.message }));
@@ -276,6 +287,7 @@ class Nexus {
276
287
  }
277
288
 
278
289
  module.exports = {
290
+ createWorkflowRunner,
279
291
  Nexus,
280
292
  DrainingError,
281
293
  TwilioProvider,
@@ -15,11 +15,6 @@ const AIRTABLE_API_URL = 'https://api.airtable.com/v0';
15
15
  const AXIOS_TIMEOUT_CODE = 'ECONNABORTED';
16
16
  const RETRY_BASE_DELAY_MS = 1000;
17
17
 
18
- function isPermanentAirtableError(error) {
19
- const status = error?.statusCode;
20
- return typeof status === 'number' && status >= 400 && status < 500 && status !== 429;
21
- }
22
-
23
18
  let isEvalMode = false;
24
19
 
25
20
  function setEvalMode(enabled) {
@@ -47,7 +42,6 @@ async function withAirtableRetry(operation, label, { retryNetworkErrors = true }
47
42
  const isTransient = TRANSIENT_STATUS_CODES.includes(error.statusCode)
48
43
  || (retryNetworkErrors && isTransientNetworkError(error));
49
44
  if (!isTransient || attempt === MAX_ATTEMPTS) {
50
- if (isPermanentAirtableError(error)) error.permanent = true;
51
45
  throw error;
52
46
  }
53
47
  const baseDelay = error.statusCode === RATE_LIMITED_STATUS ? RATE_LIMIT_DELAY_MS : RETRY_BASE_DELAY_MS;
@@ -242,7 +236,6 @@ async function upsertRecord(baseID, tableName, fields, options = {}, context = n
242
236
 
243
237
  module.exports = {
244
238
  setEvalMode,
245
- isPermanentAirtableError,
246
239
  addRecord,
247
240
  getRecords,
248
241
  getRecordByFilter,
@@ -14,7 +14,6 @@ class QueueReconciliationService {
14
14
  scheduleMessage,
15
15
  scheduleTemplateApproval,
16
16
  sweepHeldMessages,
17
- sweepUnrecoveredTriages,
18
17
  intervalMs = DEFAULT_INTERVAL_MS,
19
18
  lookbackMs = DEFAULT_LOOKBACK_MS,
20
19
  staleAfterMs = DEFAULT_STALE_AFTER_MS,
@@ -24,7 +23,6 @@ class QueueReconciliationService {
24
23
  this.scheduleMessage = scheduleMessage;
25
24
  this.scheduleTemplateApproval = scheduleTemplateApproval;
26
25
  this.sweepHeldMessages = sweepHeldMessages;
27
- this.sweepUnrecoveredTriages = sweepUnrecoveredTriages;
28
26
  this.intervalMs = intervalMs;
29
27
  this.lookbackMs = lookbackMs;
30
28
  this.staleAfterMs = staleAfterMs;
@@ -70,31 +68,19 @@ class QueueReconciliationService {
70
68
  }
71
69
 
72
70
  async runOnce() {
73
- if (this.stopped) return { scheduledMessages: 0, recoveries: 0, heldMessages: 0, unrecoveredTriages: 0 };
71
+ if (this.stopped) return { scheduledMessages: 0, recoveries: 0, heldMessages: 0 };
74
72
  const since = new Date(Date.now() - this.lookbackMs);
75
- const [scheduledMessages, recoveries, heldMessages, unrecoveredTriages] = await Promise.all([
73
+ const [scheduledMessages, recoveries, heldMessages] = await Promise.all([
76
74
  this._reEnqueueScheduledMessages(since),
77
75
  this._reArmTemplateApprovals(since),
78
- this._releaseHeldMessages(),
79
- this._recoverUnrecoveredTriages()
76
+ this._releaseHeldMessages()
80
77
  ]);
81
78
 
82
79
  if (scheduledMessages || recoveries || heldMessages) {
83
80
  logger.warn('[QueueReconciliation] Re-armed dropped jobs', { scheduledMessages, recoveries, heldMessages });
84
81
  }
85
82
 
86
- return { scheduledMessages, recoveries, heldMessages, unrecoveredTriages };
87
- }
88
-
89
- async _recoverUnrecoveredTriages() {
90
- if (typeof this.sweepUnrecoveredTriages !== 'function') return 0;
91
- try {
92
- const result = await this.sweepUnrecoveredTriages();
93
- return (result?.retried || 0) + (result?.alerted || 0);
94
- } catch (error) {
95
- logger.error('[QueueReconciliation] Recommendation recovery sweep failed', { error: error.message });
96
- return 0;
97
- }
83
+ return { scheduledMessages, recoveries, heldMessages };
98
84
  }
99
85
 
100
86
  async _releaseHeldMessages() {
@@ -0,0 +1,75 @@
1
+ const { logger } = require('./logger');
2
+
3
+ const MAX_INTERVAL_MS = 2147483647;
4
+ const SAFE_INTERVAL_MS = 600000;
5
+ const DEFAULT_PASS_TIMEOUT_MS = 300000;
6
+
7
+ function isUsableInterval(ms) {
8
+ return Number.isFinite(ms) && ms > 0 && ms <= MAX_INTERVAL_MS;
9
+ }
10
+
11
+ function createIntervalSweeper({ label, sweep, defaultIntervalMs, passTimeoutMs = DEFAULT_PASS_TIMEOUT_MS }) {
12
+ let timer = null;
13
+ let inFlight = null;
14
+
15
+ function resolveInterval(requested) {
16
+ if (requested !== undefined) {
17
+ const asked = Number(requested);
18
+ if (isUsableInterval(asked)) return asked;
19
+ logger.warn(`${label} Ignoring an unusable sweep interval`, { requested, usingDefault: true });
20
+ }
21
+
22
+ const configured = Number(defaultIntervalMs());
23
+ if (isUsableInterval(configured)) return configured;
24
+
25
+ logger.error(`${label} Configured sweep interval is unusable`, { configured, usingMs: SAFE_INTERVAL_MS });
26
+ return SAFE_INTERVAL_MS;
27
+ }
28
+
29
+ function tick() {
30
+ const now = Date.now();
31
+ if (inFlight && (now - inFlight.startedAt) < passTimeoutMs) {
32
+ logger.warn(`${label} Previous sweep is still running; skipping this tick`, {
33
+ runningForMs: now - inFlight.startedAt,
34
+ });
35
+ return;
36
+ }
37
+
38
+ const pass = { startedAt: now };
39
+ let started;
40
+ try {
41
+ started = Promise.resolve(sweep());
42
+ } catch (error) {
43
+ started = Promise.reject(error);
44
+ }
45
+ pass.promise = started
46
+ .catch((error) => logger.error(`${label} Sweep failed`, { error: error.message }))
47
+ .finally(() => { if (inFlight === pass) inFlight = null; });
48
+ inFlight = pass;
49
+ }
50
+
51
+ return {
52
+ start({ intervalMs } = {}) {
53
+ if (timer) return timer;
54
+ timer = setInterval(tick, resolveInterval(intervalMs));
55
+ if (typeof timer.unref === 'function') timer.unref();
56
+ return timer;
57
+ },
58
+
59
+ stop() {
60
+ if (timer) {
61
+ clearInterval(timer);
62
+ timer = null;
63
+ }
64
+ return Promise.resolve(inFlight?.promise);
65
+ },
66
+ };
67
+ }
68
+
69
+ module.exports = {
70
+ createIntervalSweeper,
71
+ isUsableInterval,
72
+ MAX_INTERVAL_MS,
73
+ SAFE_INTERVAL_MS,
74
+ DEFAULT_PASS_TIMEOUT_MS,
75
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.54.0-dev.7843",
3
+ "version": "5.54.0-dev.7847",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,265 +0,0 @@
1
- const { describeThrown } = require('../utils/errorUtils');
2
- const { logger } = require('../utils/logger');
3
-
4
- const { DeferredWork, RETENTION_MS } = require('../models/deferredWorkModel');
5
-
6
- const STALE_CLAIM_MS = 5 * 60 * 1000;
7
- const MINUTE_MS = 60 * 1000;
8
- const INDEX_TIMEOUT_MS = 1000;
9
- const SWEEP_INTERVAL_MS = 60 * 1000;
10
-
11
- let indexesReady = null;
12
-
13
- function ensureIndexes() {
14
- if (!indexesReady) {
15
- indexesReady = DeferredWork.init().catch((error) => {
16
- indexesReady = null;
17
- logger.error('[WorkflowRunner] Index build failed, dedupe and retention are not guaranteed', { error: error.message });
18
- });
19
- }
20
- return indexesReady;
21
- }
22
-
23
- function withIndexTimeout(promise) {
24
- let timer;
25
- const timeout = new Promise((resolve) => {
26
- timer = setTimeout(resolve, INDEX_TIMEOUT_MS);
27
- timer.unref();
28
- });
29
- return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
30
- }
31
-
32
- class WorkflowRunner {
33
- constructor({ queueAdapter, sweepIntervalMs = SWEEP_INTERVAL_MS } = {}) {
34
- if (!queueAdapter) throw new Error('WorkflowRunner requires a queueAdapter');
35
- this.queueAdapter = queueAdapter;
36
- this.sweepIntervalMs = sweepIntervalMs;
37
- this.sweepTimer = null;
38
- this.timers = new Map();
39
- this.workflows = new Map();
40
- this.stopped = false;
41
- }
42
-
43
- async register(workflow = {}) {
44
- if (!workflow.kind || typeof workflow.kind !== 'string') throw new Error('workflow requires a kind');
45
- if (workflow.kind.includes('__')) throw new Error(`workflow '${workflow.kind}' must not contain '__' (reserved as the jobId delimiter)`);
46
- if (typeof workflow.dedupeKey !== 'function') throw new Error(`workflow '${workflow.kind}' requires a dedupeKey function`);
47
- if (typeof workflow.prepare !== 'function') throw new Error(`workflow '${workflow.kind}' requires a prepare function`);
48
- if (this.workflows.has(workflow.kind)) throw new Error(`workflow '${workflow.kind}' is already registered`);
49
- if (workflow.retrySchedule !== undefined) {
50
- if (!Array.isArray(workflow.retrySchedule) || !workflow.retrySchedule.length) {
51
- throw new Error(`workflow '${workflow.kind}' requires a non-empty retrySchedule array`);
52
- }
53
- if (workflow.retrySchedule.some((minutes) => !Number.isFinite(minutes) || minutes <= 0)) {
54
- throw new Error(`workflow '${workflow.kind}' requires retrySchedule entries to be positive minutes`);
55
- }
56
- if (workflow.retrySchedule.some((minutes) => minutes * MINUTE_MS >= RETENTION_MS)) {
57
- throw new Error(`workflow '${workflow.kind}' requires retrySchedule entries under the ${RETENTION_MS / MINUTE_MS}m retention, or the record expires before the attempt fires`);
58
- }
59
- }
60
-
61
- this.workflows.set(workflow.kind, workflow);
62
- if (workflow.retrySchedule) {
63
- await this.sweep([workflow.kind]).catch((error) => {
64
- logger.error('[WorkflowRunner] Sweep on register failed', { kind: workflow.kind, error: error.message });
65
- });
66
- this._startSweeping();
67
- return workflow;
68
- }
69
-
70
- try {
71
- await this.queueAdapter.process(workflow.kind, (trigger) => workflow.prepare(trigger));
72
- } catch (error) {
73
- this.workflows.delete(workflow.kind);
74
- throw error;
75
- }
76
- return workflow;
77
- }
78
-
79
- enqueue(kind, trigger, options = {}) {
80
- const workflow = this.workflows.get(kind);
81
- if (!workflow) throw new Error(`no workflow registered for '${kind}'`);
82
- const dedupeKey = workflow.dedupeKey(trigger);
83
- if (dedupeKey == null || (typeof dedupeKey === 'string' && !dedupeKey.trim())) {
84
- throw new Error(`workflow '${kind}' produced an empty dedupe key`);
85
- }
86
- if (typeof dedupeKey !== 'string') throw new Error(`workflow '${kind}' produced a non-string dedupe key`);
87
- if (!workflow.retrySchedule) {
88
- return this.queueAdapter.enqueue(kind, trigger, { ...options, jobId: `${kind}__${dedupeKey}` });
89
- }
90
- return this._armDeferred(workflow, trigger, dedupeKey);
91
- }
92
-
93
- async sweep(only = null) {
94
- const deferredKinds = [...this.workflows.values()].filter((w) => w.retrySchedule).map((w) => w.kind);
95
- const kinds = only ? deferredKinds.filter((kind) => only.includes(kind)) : deferredKinds;
96
- if (!kinds.length) return [];
97
-
98
- const orphaned = await DeferredWork.find({
99
- kind: { $in: kinds },
100
- $or: [
101
- { status: 'pending' },
102
- { status: 'processing', claimedAt: { $lt: new Date(Date.now() - STALE_CLAIM_MS) } }
103
- ]
104
- });
105
-
106
- const rearmed = orphaned.map((work) => this._arm(
107
- this.workflows.get(work.kind),
108
- work._id,
109
- this._delayUntilDue(work),
110
- ));
111
- if (rearmed.length) logger.info('[WorkflowRunner] Swept', { kinds, rearmed: rearmed.length });
112
- return rearmed;
113
- }
114
-
115
- _startSweeping() {
116
- if (this.stopped || this.sweepTimer || !this.sweepIntervalMs) return;
117
- this.sweepTimer = setInterval(() => {
118
- this.sweep().catch((error) => logger.error('[WorkflowRunner] Periodic sweep failed', { error: error.message }));
119
- }, this.sweepIntervalMs);
120
- this.sweepTimer.unref();
121
- }
122
-
123
- stop() {
124
- this.stopped = true;
125
- if (this.sweepTimer) clearInterval(this.sweepTimer);
126
- this.sweepTimer = null;
127
- for (const timer of this.timers.values()) clearTimeout(timer);
128
- this.timers.clear();
129
- }
130
-
131
- async _armDeferred(workflow, trigger, dedupeKey) {
132
- const { kind } = workflow;
133
- await withIndexTimeout(ensureIndexes());
134
- const work = await DeferredWork.findOne({ kind, dedupeKey })
135
- || await DeferredWork.create({ kind, dedupeKey, trigger }).catch(async (error) => {
136
- if (error.code !== 11000) throw error;
137
- return await DeferredWork.findOne({ kind, dedupeKey });
138
- });
139
- if (work.status === 'abandoned') {
140
- const { modifiedCount } = await DeferredWork.updateOne(
141
- { _id: work._id, status: 'abandoned' },
142
- { $set: { status: 'pending', attempt: 0, nextAttemptAt: new Date(), lastError: null, claimedAt: null } }
143
- );
144
- if (!modifiedCount) return null;
145
- logger.info('[WorkflowRunner] Re-arming abandoned work', { kind, dedupeKey });
146
- return this._arm(workflow, work._id, 0);
147
- }
148
- if (work.status !== 'pending') {
149
- logger.info('[WorkflowRunner] Skipping, work is in flight or complete', { kind, dedupeKey, status: work.status });
150
- return null;
151
- }
152
- return this._arm(workflow, work._id, this._delayUntilDue(work));
153
- }
154
-
155
- _delayUntilDue(work) {
156
- return Math.max(0, new Date(work.nextAttemptAt).getTime() - Date.now());
157
- }
158
-
159
- _arm(workflow, workId, delayMs) {
160
- const id = String(workId);
161
- // An attempt still in flight when stop() lands must not re-arm after shutdown. The
162
- // record stays pending in Mongo, so the next process recovers it on its sweep.
163
- if (this.stopped) return id;
164
- clearTimeout(this.timers.get(id));
165
- const timer = setTimeout(() => {
166
- this.timers.delete(id);
167
- this._runDeferred(workflow, id).catch((error) => {
168
- logger.error('[WorkflowRunner] Deferred run failed', { kind: workflow.kind, deferredWorkId: id, error: error.message });
169
- });
170
- }, delayMs);
171
- timer.unref();
172
- this.timers.set(id, timer);
173
- return id;
174
- }
175
-
176
- async _runDeferred(workflow, deferredWorkId) {
177
- const claimedAt = new Date();
178
- const prior = await DeferredWork.findOneAndUpdate(
179
- {
180
- _id: deferredWorkId,
181
- $or: [
182
- { status: 'pending', nextAttemptAt: { $lte: claimedAt } },
183
- { status: 'processing', claimedAt: { $lt: new Date(claimedAt.getTime() - STALE_CLAIM_MS) } }
184
- ]
185
- },
186
- { $set: { status: 'processing', claimedAt } },
187
- { new: false }
188
- );
189
- if (!prior) {
190
- logger.info('[WorkflowRunner] Claimed elsewhere or not due', { kind: workflow.kind, deferredWorkId });
191
- return { claimed: false };
192
- }
193
-
194
- const reclaimed = prior.status === 'processing';
195
- const work = { ...prior.toObject(), attempt: prior.attempt + (reclaimed ? 1 : 0) };
196
- if (reclaimed) await this._write(work, claimedAt, { attempt: work.attempt });
197
-
198
- const checkpoints = { ...(work.checkpoints || {}) };
199
- const save = async (patch) => {
200
- Object.assign(checkpoints, patch);
201
- const $set = {};
202
- for (const [key, value] of Object.entries(patch || {})) $set[`checkpoints.${key}`] = value;
203
- if (Object.keys($set).length) await this._write(work, claimedAt, $set);
204
- };
205
-
206
- try {
207
- await workflow.prepare(work.trigger, checkpoints, save);
208
- } catch (error) {
209
- return await this._rescheduleOrAbandon(workflow, work, claimedAt, error);
210
- }
211
- await this._write(work, claimedAt, { status: 'done', claimedAt: null });
212
- return { status: 'done' };
213
- }
214
-
215
- // matchedCount, not modifiedCount: the fence is "do we still hold the claim", and
216
- // modifiedCount is also 0 for a write that matched but set an identical value - a
217
- // save() rewriting an unchanged checkpoint is not a lost claim.
218
- async _write(work, claimedAt, $set) {
219
- const { matchedCount } = await DeferredWork.updateOne({ _id: work._id, claimedAt }, { $set });
220
- if (!matchedCount) logger.warn('[WorkflowRunner] Claim lost, write discarded', { deferredWorkId: String(work._id) });
221
- return matchedCount > 0;
222
- }
223
-
224
- async _rescheduleOrAbandon(workflow, work, claimedAt, error) {
225
- // prepare() is consumer code and can throw anything, including null. Dereferencing
226
- // it here used to raise a TypeError out of this handler, so neither branch ran and
227
- // the record stayed `processing` until stale recovery hit the same failure again.
228
- const lastError = describeThrown(error);
229
- const delayMinutes = workflow.retrySchedule[work.attempt];
230
- if (error?.permanent === true || delayMinutes === undefined) {
231
- await this._write(work, claimedAt, { status: 'abandoned', lastError, claimedAt: null });
232
- logger.error('[WorkflowRunner] Abandoned', {
233
- kind: workflow.kind,
234
- dedupeKey: work.dedupeKey,
235
- attempt: work.attempt,
236
- permanent: error?.permanent === true,
237
- error: lastError
238
- });
239
- return { status: 'abandoned' };
240
- }
241
-
242
- const attempt = work.attempt + 1;
243
- const delayMs = delayMinutes * MINUTE_MS;
244
- const kept = await this._write(work, claimedAt, {
245
- status: 'pending',
246
- attempt,
247
- nextAttemptAt: new Date(Date.now() + delayMs),
248
- lastError,
249
- claimedAt: null
250
- });
251
- if (!kept) return { claimed: false };
252
-
253
- logger.warn('[WorkflowRunner] Rescheduled', {
254
- kind: workflow.kind,
255
- dedupeKey: work.dedupeKey,
256
- attempt,
257
- delayMinutes,
258
- error: lastError
259
- });
260
- this._arm(workflow, work._id, delayMs);
261
- return { status: 'pending', attempt };
262
- }
263
- }
264
-
265
- module.exports = { WorkflowRunner };
@@ -1,24 +0,0 @@
1
- const mongoose = require('mongoose');
2
-
3
- const STATUS_VALUES = ['pending', 'processing', 'done', 'abandoned'];
4
- const RETENTION_MS = 24 * 60 * 60 * 1000;
5
-
6
- const deferredWorkSchema = new mongoose.Schema({
7
- kind: { type: String, required: true },
8
- dedupeKey: { type: String, required: true },
9
- trigger: { type: mongoose.Schema.Types.Mixed, default: null },
10
- checkpoints: { type: mongoose.Schema.Types.Mixed, default: () => ({}) },
11
- status: { type: String, enum: STATUS_VALUES, default: 'pending' },
12
- attempt: { type: Number, default: 0 },
13
- nextAttemptAt: { type: Date, default: Date.now },
14
- claimedAt: { type: Date, default: null },
15
- lastError: { type: String, default: null }
16
- }, { timestamps: true });
17
-
18
- deferredWorkSchema.index({ kind: 1, dedupeKey: 1 }, { unique: true, name: 'dedupe_idx' });
19
- deferredWorkSchema.index({ status: 1, nextAttemptAt: 1 }, { name: 'due_idx' });
20
- deferredWorkSchema.index({ updatedAt: 1 }, { expireAfterSeconds: RETENTION_MS / 1000, name: 'ttl_idx' });
21
-
22
- const DeferredWork = mongoose.model('DeferredWork', deferredWorkSchema);
23
-
24
- module.exports = { DeferredWork, RETENTION_MS };