@peopl-health/nexus 5.53.3 → 5.53.4
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/clinical/flags/inboundRecoveryFlags.js +9 -0
- package/lib/clinical/services/recommendationRecoveryService.js +3 -12
- package/lib/config/lifecycle.js +2 -1
- package/lib/core/NexusMessaging.js +66 -45
- package/lib/helpers/pausedThreadHelper.js +15 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.js +14 -0
- package/lib/services/inboundRecoveryService.js +209 -0
- package/package.json +1 -1
|
@@ -3,9 +3,9 @@ const { Symptoms_ID } = require('../../config/airtableConfig');
|
|
|
3
3
|
const { logger } = require('../../utils/logger');
|
|
4
4
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
5
5
|
const { recommendationRetryLive } = require('../flags/recommendationRecoveryFlags');
|
|
6
|
-
const { Thread } = require('../../models/threadModel');
|
|
7
6
|
const runtimeConfig = require('../../config/runtimeConfig');
|
|
8
7
|
const { createIntervalSweeper } = require('../../utils/intervalSweeper');
|
|
8
|
+
const { botIsPaused: threadIsPaused } = require('../../helpers/pausedThreadHelper');
|
|
9
9
|
const { recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
10
10
|
const { handleTriageCompleted } = require('./triageRecommendationService');
|
|
11
11
|
const { WriteClaimStore } = require('./writeClaimStore');
|
|
@@ -25,6 +25,8 @@ const ticketClaims = new WriteClaimStore({ namespace: 'recom-orphan-ticket', ttl
|
|
|
25
25
|
|
|
26
26
|
const FIELDS = ['Created', 'triaje_symptoms_id', 'whatsapp_id', 'symptom_name_positive'];
|
|
27
27
|
|
|
28
|
+
const botIsPaused = (code) => threadIsPaused(code, { label: '[recommendationRecovery]' });
|
|
29
|
+
|
|
28
30
|
function orphanFormula(now) {
|
|
29
31
|
const newest = new Date(now.getTime() - MIN_AGE_MS).toISOString();
|
|
30
32
|
const oldest = new Date(now.getTime() - SCAN_WINDOW_MS).toISOString();
|
|
@@ -53,17 +55,6 @@ function describe(row) {
|
|
|
53
55
|
};
|
|
54
56
|
}
|
|
55
57
|
|
|
56
|
-
async function botIsPaused(code) {
|
|
57
|
-
if (!code) return false;
|
|
58
|
-
try {
|
|
59
|
-
const paused = await Thread.findOne({ code, stopped: true }, { _id: 1 }).lean();
|
|
60
|
-
return Boolean(paused);
|
|
61
|
-
} catch (error) {
|
|
62
|
-
logger.warn('[recommendationRecovery] thread state unreadable; treating the bot as paused', { code, error: error.message });
|
|
63
|
-
return true;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
58
|
async function fileOpsTicket(orphan) {
|
|
68
59
|
if (!orphan.code) return false;
|
|
69
60
|
return recordUnresolvedRequest({
|
package/lib/config/lifecycle.js
CHANGED
|
@@ -5,6 +5,7 @@ const { logger } = require('../utils/logger');
|
|
|
5
5
|
const { _clearClinicalContextCache } = require('../helpers/patientInformationHelper');
|
|
6
6
|
const { setPreprocessingHandler } = require('../services/preprocessingService');
|
|
7
7
|
const { clearTriageHistoryCache } = require('../services/triageHistoryService');
|
|
8
|
+
const { stopInboundRecoverySweep } = require('../services/inboundRecoveryService');
|
|
8
9
|
const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
|
|
9
10
|
const { _resetDefaultInstance } = require('../core/NexusMessaging');
|
|
10
11
|
const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
|
|
@@ -19,7 +20,7 @@ const { _resetState: _resetLLMState } = require('../clinical/config/llmConfig');
|
|
|
19
20
|
const SWEEP_STOP_MS = 2000;
|
|
20
21
|
|
|
21
22
|
function stopAllSweeps({ timeoutMs = SWEEP_STOP_MS, label = '[lifecycle]' } = {}) {
|
|
22
|
-
const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep()]);
|
|
23
|
+
const stopped = Promise.allSettled([stopSafetyNetSweep(), stopRecommendationRecoverySweep(), stopInboundRecoverySweep()]);
|
|
23
24
|
return withTimeout(stopped, timeoutMs, 'sweeps.stop')
|
|
24
25
|
.catch(error => logger.warn(`${label} A sweep was still running`, { error: error.message }));
|
|
25
26
|
}
|
|
@@ -674,54 +674,75 @@ class NexusMessaging {
|
|
|
674
674
|
|
|
675
675
|
async _handleWithCheckAfter(chatId) {
|
|
676
676
|
return await this._executeWithPipeline(chatId, 'message', 'preempt',
|
|
677
|
-
async (preProcessResult, shouldContinue, runId) =>
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
return null;
|
|
682
|
-
});
|
|
683
|
-
if (!resolved) {
|
|
684
|
-
await coverUnansweredPatient({ code: chatId });
|
|
685
|
-
return null;
|
|
686
|
-
}
|
|
677
|
+
async (preProcessResult, shouldContinue, runId) =>
|
|
678
|
+
this._runPatientTurn(chatId, preProcessResult, shouldContinue, runId)
|
|
679
|
+
);
|
|
680
|
+
}
|
|
687
681
|
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
{ message_id: u.message_id },
|
|
695
|
-
{ $set: {
|
|
696
|
-
assistant_id: u.assistantId,
|
|
697
|
-
thread_id: u.threadId,
|
|
698
|
-
'media.metadata.processedContent': encoded,
|
|
699
|
-
}}
|
|
700
|
-
),
|
|
701
|
-
() => null,
|
|
702
|
-
)
|
|
703
|
-
));
|
|
704
|
-
|
|
705
|
-
if (!preProcessed.shouldProcess) return null;
|
|
706
|
-
|
|
707
|
-
const result = await this.assistantProcessor.executeLLM(
|
|
708
|
-
resolved.thread, resolved.assistant,
|
|
709
|
-
{ prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
|
|
710
|
-
preProcessed.messages[0]
|
|
711
|
-
);
|
|
682
|
+
async recoverInboundTurn(code, { confirmStillUnanswered = null } = {}) {
|
|
683
|
+
return await this._executeWithPipeline(code, 'message', 'queue',
|
|
684
|
+
async (preProcessResult, shouldContinue, runId) =>
|
|
685
|
+
this._runPatientTurn(code, preProcessResult, shouldContinue, runId, { confirmStillUnanswered })
|
|
686
|
+
);
|
|
687
|
+
}
|
|
712
688
|
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
}, shouldContinue, runId);
|
|
689
|
+
async _runPatientTurn(chatId, preProcessResult, shouldContinue, runId, { confirmStillUnanswered = null } = {}) {
|
|
690
|
+
return await this._processMessages(chatId, async () => {
|
|
691
|
+
const resolved = await this.assistantProcessor.resolveThread(chatId).catch((error) => {
|
|
692
|
+
logger.warn('[NexusMessaging] Could not resolve an assistant for this patient', { code: chatId, error: error.message });
|
|
693
|
+
return null;
|
|
694
|
+
});
|
|
695
|
+
if (!resolved) {
|
|
696
|
+
await coverUnansweredPatient({ code: chatId });
|
|
697
|
+
return null;
|
|
723
698
|
}
|
|
724
|
-
|
|
699
|
+
|
|
700
|
+
const preProcessed = await preProcessMessages(chatId, null, resolved.thread);
|
|
701
|
+
|
|
702
|
+
await Promise.all((preProcessed.pendingMediaUpdates ?? []).map(u =>
|
|
703
|
+
this.phiProcessor.inData(
|
|
704
|
+
{ body: u.processedContent, code: chatId },
|
|
705
|
+
({ body: encoded }) => updateMessage(
|
|
706
|
+
{ message_id: u.message_id },
|
|
707
|
+
{ $set: {
|
|
708
|
+
assistant_id: u.assistantId,
|
|
709
|
+
thread_id: u.threadId,
|
|
710
|
+
'media.metadata.processedContent': encoded,
|
|
711
|
+
}}
|
|
712
|
+
),
|
|
713
|
+
() => null,
|
|
714
|
+
)
|
|
715
|
+
));
|
|
716
|
+
|
|
717
|
+
if (!preProcessed.shouldProcess) return null;
|
|
718
|
+
|
|
719
|
+
if (typeof confirmStillUnanswered === 'function' && !(await confirmStillUnanswered(chatId))) {
|
|
720
|
+
logger.info('[inboundRecovery] a reply landed while the replay was queued; standing down', { code: chatId });
|
|
721
|
+
return null;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const result = await this.assistantProcessor.executeLLM(
|
|
725
|
+
resolved.thread, resolved.assistant,
|
|
726
|
+
{ prePromptResult: preProcessResult, shouldContinue, runId, signal: this.batchingManager.getAbortSignal(runId) },
|
|
727
|
+
preProcessed.messages[0]
|
|
728
|
+
);
|
|
729
|
+
|
|
730
|
+
if (typeof confirmStillUnanswered === 'function' && !(await confirmStillUnanswered(chatId))) {
|
|
731
|
+
logger.info('[inboundRecovery] a reply landed while the replay was generating; discarding it', { code: chatId });
|
|
732
|
+
await this.assistantProcessor.discardResponse?.(chatId, result);
|
|
733
|
+
return null;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
try {
|
|
737
|
+
if (storeRunMetrics) {
|
|
738
|
+
await storeRunMetrics(chatId, resolved.thread, result, preProcessed.timings);
|
|
739
|
+
}
|
|
740
|
+
} catch (error) {
|
|
741
|
+
await this.assistantProcessor.discardResponse?.(chatId, result);
|
|
742
|
+
throw error;
|
|
743
|
+
}
|
|
744
|
+
return { ...result, timings: preProcessed.timings };
|
|
745
|
+
}, shouldContinue, runId);
|
|
725
746
|
}
|
|
726
747
|
|
|
727
748
|
async processInstruction(code, instruction, role = 'developer', { triggeredBy } = {}) {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { Thread } = require('../models/threadModel');
|
|
3
|
+
|
|
4
|
+
async function botIsPaused(code, { label = '[pausedThread]' } = {}) {
|
|
5
|
+
if (!code) return false;
|
|
6
|
+
try {
|
|
7
|
+
const paused = await Thread.findOne({ code, stopped: true }, { _id: 1 }).lean();
|
|
8
|
+
return Boolean(paused);
|
|
9
|
+
} catch (error) {
|
|
10
|
+
logger.warn(`${label} thread state unreadable; treating the bot as paused`, { code, error: error.message });
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = { botIsPaused };
|
package/lib/index.d.ts
CHANGED
|
@@ -331,6 +331,7 @@ declare module '@peopl-health/nexus' {
|
|
|
331
331
|
parserConfig?: ParserConfig;
|
|
332
332
|
ner?: NerOptions;
|
|
333
333
|
recommendationRecovery?: RecommendationRecoveryOptions;
|
|
334
|
+
inboundRecovery?: InboundRecoveryOptions;
|
|
334
335
|
}
|
|
335
336
|
|
|
336
337
|
export interface RecommendationRecoveryOptions {
|
|
@@ -338,6 +339,11 @@ declare module '@peopl-health/nexus' {
|
|
|
338
339
|
intervalMs?: number;
|
|
339
340
|
}
|
|
340
341
|
|
|
342
|
+
export interface InboundRecoveryOptions {
|
|
343
|
+
enabled: boolean;
|
|
344
|
+
intervalMs?: number;
|
|
345
|
+
}
|
|
346
|
+
|
|
341
347
|
export interface NerEntity {
|
|
342
348
|
start: number;
|
|
343
349
|
end: number;
|
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 { startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
|
|
33
33
|
const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
|
|
34
|
+
const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
|
|
34
35
|
const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
|
|
35
36
|
const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
|
|
36
37
|
const { createWorkflowRunner } = require('./core/workflowRunner');
|
|
@@ -199,6 +200,19 @@ class Nexus {
|
|
|
199
200
|
logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
|
|
200
201
|
}
|
|
201
202
|
|
|
203
|
+
try {
|
|
204
|
+
if (options.inboundRecovery?.enabled === true) {
|
|
205
|
+
startInboundRecoverySweep({
|
|
206
|
+
recover: (code, opts) => this.messaging.recoverInboundTurn(code, opts),
|
|
207
|
+
isProcessing: (code) => this.messaging.isProcessing(code),
|
|
208
|
+
intervalMs: options.inboundRecovery.intervalMs,
|
|
209
|
+
});
|
|
210
|
+
logger.info('[Nexus] inbound recovery sweep armed');
|
|
211
|
+
}
|
|
212
|
+
} catch (e) {
|
|
213
|
+
logger.warn('Warning: failed to arm the inbound recovery sweep:', e?.message || e);
|
|
214
|
+
}
|
|
215
|
+
|
|
202
216
|
try {
|
|
203
217
|
if (options.recommendationRecovery?.enabled === true) {
|
|
204
218
|
startRecommendationRecoverySweep({ intervalMs: options.recommendationRecovery.intervalMs });
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
|
+
const { logger } = require('../utils/logger');
|
|
3
|
+
const { isWithinHourWindow } = require('../utils/scheduleUtils');
|
|
4
|
+
const { createIntervalSweeper } = require('../utils/intervalSweeper');
|
|
5
|
+
const { Thread } = require('../models/threadModel');
|
|
6
|
+
const { botIsPaused } = require('../helpers/pausedThreadHelper');
|
|
7
|
+
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
8
|
+
const { inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
|
|
9
|
+
const { recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
10
|
+
const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
|
|
11
|
+
const { getMessages, countMessages } = require('./messageService');
|
|
12
|
+
|
|
13
|
+
const MIN_AGE_MS = 5 * 60 * 1000;
|
|
14
|
+
const MAX_AGE_MS = 60 * 60 * 1000;
|
|
15
|
+
const SCAN_LIMIT = 200;
|
|
16
|
+
const MAX_CANDIDATES = 20;
|
|
17
|
+
const MAX_RECOVERIES_PER_PASS = 3;
|
|
18
|
+
const CLAIM_TTL_MS = 24 * 60 * 60 * 1000;
|
|
19
|
+
const REPLAY_SETTLE_MS = 5 * 60 * 1000;
|
|
20
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
|
21
|
+
const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Monterrey', startHour: 8, endHour: 21 };
|
|
22
|
+
|
|
23
|
+
const recoveryClaims = new WriteClaimStore({ namespace: 'inbound-recovery', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
24
|
+
const ticketClaims = new WriteClaimStore({ namespace: 'inbound-recovery-ticket', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
|
|
25
|
+
|
|
26
|
+
async function unansweredThreads(now) {
|
|
27
|
+
return Thread.find(
|
|
28
|
+
{
|
|
29
|
+
stopped: false,
|
|
30
|
+
lastMessageFromMe: false,
|
|
31
|
+
lastMessageAt: { $gte: new Date(now.getTime() - MAX_AGE_MS), $lte: new Date(now.getTime() - MIN_AGE_MS) },
|
|
32
|
+
},
|
|
33
|
+
{ code: 1, lastMessageAt: 1 },
|
|
34
|
+
).sort({ lastMessageAt: 1 }).limit(SCAN_LIMIT).lean();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
|
|
38
|
+
|
|
39
|
+
async function stillUnanswered(code, now = new Date()) {
|
|
40
|
+
const [newest] = await getMessages(
|
|
41
|
+
{ numero: code, from_me: false, interactive_type: null },
|
|
42
|
+
{ select: { _id: 1, createdAt: 1, message_id: 1 }, sort: { createdAt: -1 }, limit: 1 },
|
|
43
|
+
);
|
|
44
|
+
if (!newest) return null;
|
|
45
|
+
|
|
46
|
+
const ageMs = now.getTime() - new Date(newest.createdAt).getTime();
|
|
47
|
+
if (!Number.isFinite(ageMs) || ageMs < MIN_AGE_MS || ageMs > MAX_AGE_MS) return null;
|
|
48
|
+
|
|
49
|
+
const replies = await countMessages({ numero: code, from_me: true, createdAt: { $gt: newest.createdAt } });
|
|
50
|
+
return replies === 0 ? newest : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function fileTicket(code, alert) {
|
|
54
|
+
try {
|
|
55
|
+
return Boolean(await alert({ code, category: 'contact_team_member', question: 'El paciente escribió y no recibió respuesta.' }));
|
|
56
|
+
} catch (error) {
|
|
57
|
+
logger.error('[inboundRecovery] could not file the ops ticket', { code, error: error.message });
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function sweepUnansweredInbound({
|
|
63
|
+
now = new Date(),
|
|
64
|
+
recover = null,
|
|
65
|
+
isProcessing = () => false,
|
|
66
|
+
live = inboundRecoveryLive,
|
|
67
|
+
claims = recoveryClaims,
|
|
68
|
+
ticketGate = ticketClaims,
|
|
69
|
+
isPaused = threadIsOwnedByAHuman,
|
|
70
|
+
alert = recordUnresolvedRequest,
|
|
71
|
+
} = {}) {
|
|
72
|
+
let threads;
|
|
73
|
+
try {
|
|
74
|
+
threads = await unansweredThreads(now);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
logger.error('[inboundRecovery] unanswered scan failed', { error: error.message });
|
|
77
|
+
return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const candidates = [];
|
|
81
|
+
for (const thread of threads) {
|
|
82
|
+
if (!thread.code) continue;
|
|
83
|
+
if (isProcessing(thread.code)) continue;
|
|
84
|
+
try {
|
|
85
|
+
const inbound = await stillUnanswered(thread.code, now);
|
|
86
|
+
if (inbound) candidates.push({ code: thread.code, inbound });
|
|
87
|
+
} catch (error) {
|
|
88
|
+
logger.error('[inboundRecovery] could not read one conversation; leaving it for the next pass', {
|
|
89
|
+
code: thread.code, error: error.message,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (!candidates.length) return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
|
|
95
|
+
|
|
96
|
+
if (candidates.length > MAX_CANDIDATES) {
|
|
97
|
+
logger.error('[inboundRecovery] too many patients look unanswered; acting on none', {
|
|
98
|
+
found: candidates.length, ceiling: MAX_CANDIDATES,
|
|
99
|
+
});
|
|
100
|
+
return { scanned: candidates.length, recovered: 0, alerted: 0, skipped: candidates.length };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const canRecover = live() && typeof recover === 'function';
|
|
104
|
+
let recovered = 0;
|
|
105
|
+
let alerted = 0;
|
|
106
|
+
let skipped = 0;
|
|
107
|
+
|
|
108
|
+
for (const { code, inbound } of candidates) {
|
|
109
|
+
const key = String(inbound._id);
|
|
110
|
+
const ageMs = now.getTime() - new Date(inbound.createdAt).getTime();
|
|
111
|
+
|
|
112
|
+
if (await isPaused(code)) { skipped += 1; continue; }
|
|
113
|
+
|
|
114
|
+
const claim = await claims.acquire(key, 'handled');
|
|
115
|
+
if (claim === 'unavailable') {
|
|
116
|
+
skipped += 1;
|
|
117
|
+
logger.error('[inboundRecovery] patient looks unanswered and could not be claimed', { code, ageMs });
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (claim === 'taken') {
|
|
122
|
+
const claimedAt = typeof claims.claimedAtMs === 'function' ? await claims.claimedAtMs(key) : null;
|
|
123
|
+
if (claimedAt === null || (now.getTime() - claimedAt) < REPLAY_SETTLE_MS) { skipped += 1; continue; }
|
|
124
|
+
|
|
125
|
+
const ticket = await ticketGate.acquire(key, 'alerted');
|
|
126
|
+
if (ticket !== 'acquired') { skipped += 1; continue; }
|
|
127
|
+
|
|
128
|
+
logger.error('[inboundRecovery] a replay already ran and the patient is still unanswered', { code, ageMs });
|
|
129
|
+
if (await fileTicket(code, alert)) {
|
|
130
|
+
alerted += 1;
|
|
131
|
+
} else {
|
|
132
|
+
await ticketGate.release(key);
|
|
133
|
+
}
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const reachable = isWithinHourWindow(now, PATIENT_CONTACT_WINDOW) && await isWithin24HourWindow(code);
|
|
138
|
+
|
|
139
|
+
if (canRecover && reachable && recovered < MAX_RECOVERIES_PER_PASS) {
|
|
140
|
+
logger.error('[inboundRecovery] patient was left unanswered, replaying the turn', { code, ageMs });
|
|
141
|
+
try {
|
|
142
|
+
await recover(code);
|
|
143
|
+
recovered += 1;
|
|
144
|
+
continue;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
await claims.release(key);
|
|
147
|
+
logger.error('[inboundRecovery] replay could not be dispatched', { code, ageMs, error: error.message });
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
logger.error('[inboundRecovery] patient was left unanswered', {
|
|
153
|
+
code, ageMs, recoveryLive: canRecover, reachable,
|
|
154
|
+
});
|
|
155
|
+
if (await fileTicket(code, alert)) {
|
|
156
|
+
alerted += 1;
|
|
157
|
+
} else {
|
|
158
|
+
await claims.release(key);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return { scanned: candidates.length, recovered, alerted, skipped };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function sweepIntervalMs() {
|
|
166
|
+
const raw = Number(runtimeConfig.get('INBOUND_RECOVERY_SWEEP_INTERVAL_MS'));
|
|
167
|
+
return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SWEEP_INTERVAL_MS;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
let sweeper = null;
|
|
171
|
+
|
|
172
|
+
function startInboundRecoverySweep({ recover, isProcessing, intervalMs } = {}) {
|
|
173
|
+
if (!sweeper) {
|
|
174
|
+
sweeper = createIntervalSweeper({
|
|
175
|
+
label: '[inboundRecovery]',
|
|
176
|
+
sweep: () => sweepUnansweredInbound({
|
|
177
|
+
recover: typeof recover === 'function'
|
|
178
|
+
? (code) => recover(code, { confirmStillUnanswered: async (c) => Boolean(await stillUnanswered(c)) })
|
|
179
|
+
: null,
|
|
180
|
+
isProcessing,
|
|
181
|
+
}),
|
|
182
|
+
defaultIntervalMs: sweepIntervalMs,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return sweeper.start({ intervalMs });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function stopInboundRecoverySweep() {
|
|
189
|
+
if (!sweeper) return Promise.resolve();
|
|
190
|
+
const stopping = sweeper.stop();
|
|
191
|
+
sweeper = null;
|
|
192
|
+
return stopping;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
module.exports = {
|
|
196
|
+
startInboundRecoverySweep,
|
|
197
|
+
stopInboundRecoverySweep,
|
|
198
|
+
sweepUnansweredInbound,
|
|
199
|
+
DEFAULT_SWEEP_INTERVAL_MS,
|
|
200
|
+
stillUnanswered,
|
|
201
|
+
threadIsOwnedByAHuman,
|
|
202
|
+
_claims: recoveryClaims,
|
|
203
|
+
_ticketClaims: ticketClaims,
|
|
204
|
+
MIN_AGE_MS,
|
|
205
|
+
MAX_AGE_MS,
|
|
206
|
+
MAX_CANDIDATES,
|
|
207
|
+
MAX_RECOVERIES_PER_PASS,
|
|
208
|
+
SCAN_LIMIT,
|
|
209
|
+
};
|