forked from Disciplr-Org/Disciplr-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem.ts
More file actions
380 lines (337 loc) · 11.4 KB
/
Copy pathsystem.ts
File metadata and controls
380 lines (337 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import { createDefaultJobHandlers, type EmbeddingReindexDependencies } from './handlers.js'
import {
InMemoryJobQueue,
type QueueMetrics,
type QueuedJobReceipt,
type QueueDepthReport,
type SweepResult,
} from './queue.js'
import { type EnqueueOptions, type JobPayloadByType, type JobType } from './types.js'
import { recoverPendingExportJobs } from '../services/exportQueue.js'
import {
createNotificationService,
type NotificationService,
} from '../services/notifications/factory.js'
import db from '../db/index.js'
import { getPgPool } from '../db/pool.js'
import { MilestoneRepository } from '../repositories/milestoneRepository.js'
import { BackfillCursorStore } from '../services/backfillCursorStore.js'
import { createEmbeddingProvider } from '../services/embeddingProvider.js'
const parsePositiveInteger = (value: string | undefined, fallback: number): number => {
if (!value) {
return fallback
}
const parsed = Number(value)
if (!Number.isFinite(parsed) || parsed <= 0) {
return fallback
}
return Math.floor(parsed)
}
/**
* Generates a deterministic advisory lock key from a job name string.
* Uses a simple hash to convert the string to two 32-bit integers for PostgreSQL advisory locks.
*/
function jobNameToAdvisoryLockKey(jobName: string): [number, number] {
let h1 = 0xdeadbeef
let h2 = 0xcafebabe
for (let i = 0; i < jobName.length; i++) {
h1 = Math.imul(31, h1) + jobName.charCodeAt(i)
h2 = Math.imul(17, h2) + jobName.charCodeAt(i)
}
return [h1 | 0, h2 | 0]
}
interface ScheduledJobConfig {
name: string
intervalMs: number
execute: () => Promise<void> | void
immediate?: boolean
initialDelayMs?: number
}
class SchedulerRegistry {
private readonly scheduledJobs: Map<string, ScheduledJobConfig> = new Map()
private readonly timers: Map<string, NodeJS.Timeout> = new Map()
private readonly runningJobs: Set<string> = new Set()
registerJob(config: ScheduledJobConfig): void {
this.scheduledJobs.set(config.name, config)
}
async tryAcquireLock(jobName: string): Promise<boolean> {
const pool = getPgPool()
if (!pool) {
return true
}
const [key1, key2] = jobNameToAdvisoryLockKey(jobName)
const client = await pool.connect()
try {
const result = await client.query(
'SELECT pg_try_advisory_lock($1, $2) as acquired',
[key1, key2]
)
return result.rows[0].acquired as boolean
} catch (error) {
console.error(`[SchedulerRegistry] Failed to acquire advisory lock for ${jobName}:`, error)
return false
} finally {
client.release()
}
}
async releaseLock(jobName: string): Promise<void> {
const pool = getPgPool()
if (!pool) {
return
}
const [key1, key2] = jobNameToAdvisoryLockKey(jobName)
const client = await pool.connect()
try {
await client.query('SELECT pg_advisory_unlock($1, $2)', [key1, key2])
} catch (error) {
console.error(`[SchedulerRegistry] Failed to release advisory lock for ${jobName}:`, error)
} finally {
client.release()
}
}
private async runJobWithOverlapGuard(config: ScheduledJobConfig): Promise<void> {
if (this.runningJobs.has(config.name)) {
console.log(`[SchedulerRegistry] Job ${config.name} already running locally, skipping`)
return
}
const lockAcquired = await this.tryAcquireLock(config.name)
if (!lockAcquired) {
console.log(`[SchedulerRegistry] Could not acquire lock for ${config.name}, skipping (another replica holds the lock)`)
return
}
this.runningJobs.add(config.name)
const now = new Date()
try {
await config.execute()
await db('scheduler_heartbeats')
.insert({
name: config.name,
last_run_at: now,
})
.onConflict('name')
.merge({
last_run_at: now,
})
} catch (error) {
console.error(`[SchedulerRegistry] Job ${config.name} failed:`, error)
} finally {
this.runningJobs.delete(config.name)
await this.releaseLock(config.name)
}
}
start(): void {
for (const config of this.scheduledJobs.values()) {
if (config.immediate) {
const delay = config.initialDelayMs ?? 0
setTimeout(() => {
void this.runJobWithOverlapGuard(config)
}, delay)
}
const timer = setInterval(() => {
void this.runJobWithOverlapGuard(config)
}, config.intervalMs)
if (typeof timer.unref === 'function') {
timer.unref()
}
this.timers.set(config.name, timer)
}
}
stop(): void {
for (const timer of this.timers.values()) {
clearInterval(timer)
}
this.timers.clear()
}
}
export class BackgroundJobSystem {
private readonly queue: InMemoryJobQueue
private readonly schedulerRegistry: SchedulerRegistry
private started = false
private shuttingDown = false
constructor(
notificationService?: NotificationService,
embeddingReindex?: EmbeddingReindexDependencies,
) {
this.queue = new InMemoryJobQueue({
concurrency: parsePositiveInteger(process.env.JOB_WORKER_CONCURRENCY, 2),
pollIntervalMs: parsePositiveInteger(process.env.JOB_QUEUE_POLL_INTERVAL_MS, 250),
historyLimit: parsePositiveInteger(process.env.JOB_HISTORY_LIMIT, 50),
staleLeaseMs: parsePositiveInteger(process.env.JOB_STALE_LEASE_MS, 300_000),
})
this.schedulerRegistry = new SchedulerRegistry()
const resolvedNotificationService =
notificationService ?? createNotificationService(process.env.NOTIFICATION_PROVIDER ?? 'console')
const resolvedEmbeddingReindex = embeddingReindex ?? {
source: new MilestoneRepository(db),
cursorStore: new BackfillCursorStore(db),
embeddingProvider: createEmbeddingProvider(),
}
const handlers = createDefaultJobHandlers(resolvedNotificationService, resolvedEmbeddingReindex)
this.queue.registerHandler('notification.send', handlers['notification.send'])
this.queue.registerHandler('deadline.check', handlers['deadline.check'])
this.queue.registerHandler('oracle.call', handlers['oracle.call'])
this.queue.registerHandler('analytics.recompute', handlers['analytics.recompute'])
this.queue.registerHandler('analytics.report.generate', handlers['analytics.report.generate'])
this.queue.registerHandler('export.generate', handlers['export.generate'])
this.queue.registerHandler('sessions.cleanup', handlers['sessions.cleanup'])
this.queue.registerHandler('outbox.relay', handlers['outbox.relay'])
this.queue.registerHandler('embeddings.reindex', handlers['embeddings.reindex'])
this.queue.registerHandler('saved-search.evaluate', handlers['saved-search.evaluate'])
}
start(): void {
if (this.started) {
return
}
this.started = true
this.shuttingDown = false
this.queue.start()
this.scheduleRecurringJobs()
this.schedulerRegistry.start()
void recoverPendingExportJobs(this).catch((error) => {
const message = error instanceof Error ? error.message : String(error)
console.error(`[jobs:export.generate] failed to recover pending exports: ${message}`)
})
}
async stop(): Promise<void> {
this.shuttingDown = true
this.schedulerRegistry.stop()
this.started = false
await this.queue.stop()
}
enqueue(
type: JobType,
payload: JobPayloadByType[JobType],
options: EnqueueOptions = {},
): QueuedJobReceipt<JobType> {
if (this.shuttingDown) {
throw new Error('Cannot enqueue job: system is shutting down')
}
return this.queue.enqueue(type, payload, options)
}
getDeadLetters() {
return this.queue.getDeadLetters()
}
getDeadLetter(jobId: string) {
return this.queue.getDeadLetter(jobId)
}
replayDeadLetter(jobId: string): QueuedJobReceipt<JobType> {
if (this.shuttingDown) {
throw new Error('Cannot replay dead-letter job: system is shutting down')
}
return this.queue.replayDeadLetter(jobId)
}
retryJob(jobId: string, force: boolean = false): QueuedJobReceipt<JobType> {
if (this.shuttingDown) {
throw new Error('Cannot retry job: system is shutting down')
}
return this.queue.retryJob(jobId, force)
}
getMetrics(): QueueMetrics {
return this.queue.getMetrics()
}
getQueueDepthReport(staleLeaseMs?: number): QueueDepthReport {
return this.queue.getQueueDepthReport(staleLeaseMs)
}
sweepStaleLeases(staleLeaseMs?: number): SweepResult {
if (this.shuttingDown) {
throw new Error('Cannot sweep jobs: system is shutting down')
}
return this.queue.sweepStaleLeases(staleLeaseMs)
}
private scheduleRecurringJobs(): void {
if (process.env.ENABLE_JOB_SCHEDULER === 'false') {
return
}
const deadlineCheckIntervalMs = parsePositiveInteger(
process.env.DEADLINE_CHECK_INTERVAL_MS,
60_000,
)
const analyticsIntervalMs = parsePositiveInteger(
process.env.ANALYTICS_RECOMPUTE_INTERVAL_MS,
300_000,
)
const sessionsCleanupIntervalMs = parsePositiveInteger(
process.env.SESSIONS_CLEANUP_INTERVAL_MS,
86_400_000, // 24 hours
)
const outboxRelayIntervalMs = parsePositiveInteger(
process.env.OUTBOX_RELAY_INTERVAL_MS,
5_000,
)
const embeddingReindexIntervalMs = parsePositiveInteger(
process.env.EMBEDDING_REINDEX_INTERVAL_MS,
600_000, // 10 minutes
)
const savedSearchEvalIntervalMs = parsePositiveInteger(
process.env.SAVED_SEARCH_EVAL_INTERVAL_MS,
15 * 60_000, // 15 minutes
)
const analyticsReportIntervalMs = parsePositiveInteger(
process.env.ANALYTICS_REPORT_INTERVAL_MS,
24 * 60 * 60_000, // 24 hours
)
this.schedulerRegistry.registerJob({
name: 'deadline.check',
intervalMs: deadlineCheckIntervalMs,
immediate: true,
execute: () => {
this.enqueue('deadline.check', { triggerSource: 'scheduler' })
},
})
this.schedulerRegistry.registerJob({
name: 'analytics.recompute',
intervalMs: analyticsIntervalMs,
immediate: true,
initialDelayMs: 5_000,
execute: () => {
this.enqueue('analytics.recompute', {
scope: 'global',
reason: this.started ? 'scheduled-refresh' : 'startup-bootstrap',
})
},
})
this.schedulerRegistry.registerJob({
name: 'sessions.cleanup',
intervalMs: sessionsCleanupIntervalMs,
immediate: true,
initialDelayMs: 10_000,
execute: () => {
this.enqueue('sessions.cleanup', {})
},
})
this.schedulerRegistry.registerJob({
name: 'outbox.relay',
intervalMs: outboxRelayIntervalMs,
immediate: true,
initialDelayMs: 1_000,
execute: () => {
this.enqueue('outbox.relay', {})
},
})
this.schedulerRegistry.registerJob({
name: 'embeddings.reindex',
intervalMs: embeddingReindexIntervalMs,
immediate: true,
initialDelayMs: 15_000,
execute: () => {
this.enqueue('embeddings.reindex', {})
},
})
this.schedulerRegistry.registerJob({
name: 'saved-search.evaluate',
intervalMs: savedSearchEvalIntervalMs,
immediate: false,
execute: () => {
this.enqueue('saved-search.evaluate', {})
},
})
this.schedulerRegistry.registerJob({
name: 'analytics.report.generate',
intervalMs: analyticsReportIntervalMs,
immediate: false,
execute: () => {
this.enqueue('analytics.report.generate', {})
},
})
}
}