@peopl-health/nexus 5.53.0 → 5.53.1
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/services/recommendationRecoveryService.js +40 -9
- package/lib/clinical/services/safetyNetPledgeService.js +8 -16
- package/lib/clinical/services/writeClaimStore.js +12 -0
- package/lib/config/lifecycle.js +16 -2
- package/lib/core/NexusMessaging.js +0 -2
- package/lib/index.d.ts +8 -0
- package/lib/index.js +15 -4
- package/lib/services/queueReconciliationService.js +4 -18
- package/lib/utils/intervalSweeper.js +75 -0
- package/package.json +1 -1
|
@@ -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
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
|
|
95
|
+
const sweeper = createIntervalSweeper({
|
|
96
|
+
label: '[SafetyNetPledge]',
|
|
97
|
+
sweep: () => sweepSafetyNetPledges(),
|
|
98
|
+
defaultIntervalMs: getSweepIntervalMs,
|
|
99
|
+
});
|
|
95
100
|
|
|
96
|
-
|
|
97
|
-
|
|
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;
|
package/lib/config/lifecycle.js
CHANGED
|
@@ -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');
|
|
@@ -171,7 +170,6 @@ class NexusMessaging {
|
|
|
171
170
|
...(config.queueReconciliation || {}),
|
|
172
171
|
scheduleMessage: (options) => this.scheduledMessageJob.schedule(options),
|
|
173
172
|
scheduleTemplateApproval: (options) => this.scheduleTemplateApproval(options),
|
|
174
|
-
sweepUnrecoveredTriages: () => sweepUnrecoveredTriages(),
|
|
175
173
|
sweepHeldMessages: () => sweepHeldMessages()
|
|
176
174
|
});
|
|
177
175
|
|
package/lib/index.d.ts
CHANGED
|
@@ -330,6 +330,12 @@ declare module '@peopl-health/nexus' {
|
|
|
330
330
|
parser?: boolean;
|
|
331
331
|
parserConfig?: ParserConfig;
|
|
332
332
|
ner?: NerOptions;
|
|
333
|
+
recommendationRecovery?: RecommendationRecoveryOptions;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export interface RecommendationRecoveryOptions {
|
|
337
|
+
enabled: boolean;
|
|
338
|
+
intervalMs?: number;
|
|
333
339
|
}
|
|
334
340
|
|
|
335
341
|
export interface NerEntity {
|
|
@@ -1009,6 +1015,8 @@ declare module '@peopl-health/nexus' {
|
|
|
1009
1015
|
drainMs?: number;
|
|
1010
1016
|
abortGraceMs?: number;
|
|
1011
1017
|
teardownMs?: number;
|
|
1018
|
+
sweepStopMs?: number;
|
|
1019
|
+
closeStorage?: boolean;
|
|
1012
1020
|
}
|
|
1013
1021
|
|
|
1014
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
|
|
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 }));
|
|
@@ -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
|
|
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
|
|
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
|
|
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
|
+
};
|