@prunellejs/jobs 0.0.0-stage → 0.7.3

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/src/index.ts ADDED
@@ -0,0 +1,291 @@
1
+ // @prunellejs/jobs — Zero-dependency durable SQLite job queue and cron scheduler plugin for Prunelle.
2
+ // Built strictly on the public PrunellePlugin API (`server(api).provide(JOBS_SERVICE)`, `api.healthCheck`, `api.onShutdown`).
3
+
4
+ import type { Database } from 'bun:sqlite'
5
+ import type { StandardSchemaV1 } from 'prunelle/server'
6
+ import type { JobsRuntime, RegisteredQueue, RegisteredSchedule } from './runner'
7
+ import type {
8
+ DrainOptions,
9
+ DrainTarget,
10
+ EnqueueOptions,
11
+ JobHandler,
12
+ JobListFilter,
13
+ JobRecord,
14
+ Jobs,
15
+ JobsOptions,
16
+ JobStats,
17
+ QueueBaseOptions,
18
+ QueueOptions,
19
+ ScheduleHandler,
20
+ ScheduleOptions,
21
+ } from './types'
22
+ import { isAbsolute, resolve } from 'node:path'
23
+ import { definePlugin, JOBS_SERVICE } from 'prunelle/config'
24
+ import { nodeEnv } from 'prunelle/server'
25
+ import { assertValidTimeZone, parseCron } from './cron'
26
+ import { createJobsRuntime } from './runner'
27
+ import { createSqliteJobsStore, isInMemoryDb } from './store'
28
+ import { isStandardSchema, normalizeAttempts, normalizeBackoff } from './types'
29
+
30
+ export { assertValidTimeZone, floorToMinute, getZonedParts, matchesCron, nextCronTick, parseCron } from './cron'
31
+ export type { ParsedCron, ZonedDateParts } from './cron'
32
+ export { computeBackoffDelay, JobValidationError, parseDuration } from './types'
33
+ export type {
34
+ BackoffStrategy,
35
+ DrainOptions,
36
+ DrainTarget,
37
+ Duration,
38
+ DurationString,
39
+ DurationUnit,
40
+ EnqueueOptions,
41
+ EnqueueResult,
42
+ JobContext,
43
+ JobErrorInfo,
44
+ JobHandler,
45
+ JobListFilter,
46
+ JobRecord,
47
+ Jobs,
48
+ JobsOptions,
49
+ JobStats,
50
+ JobStatus,
51
+ QueueBaseOptions,
52
+ QueueOptions,
53
+ ScheduleContext,
54
+ ScheduleHandler,
55
+ ScheduleOptions,
56
+ } from './types'
57
+
58
+ const DEFAULT_POLL_INTERVAL_MS = 500
59
+ const DEFAULT_SCHEDULE_INTERVAL_MS = 1000
60
+ const DEFAULT_CONCURRENCY = 4
61
+ const DEFAULT_LEASE_MS = 60_000
62
+ const DEFAULT_SHUTDOWN_TIMEOUT_MS = 5000
63
+ const DEFAULT_ATTEMPTS = 3
64
+ const DEFAULT_BACKOFF = 'exponential' as const
65
+ const DEFAULT_BACKOFF_BASE_MS = 1000
66
+ const DEFAULT_MAX_BACKOFF_MS = 3_600_000
67
+
68
+ function validatePositiveNumber(value: number | undefined, fallback: number, name: string): number {
69
+ const resolved = value ?? fallback
70
+ if (!Number.isFinite(resolved) || resolved <= 0)
71
+ throw new RangeError(`@prunellejs/jobs: invalid ${name} ${String(resolved)}: pass a finite number > 0.`)
72
+ return resolved
73
+ }
74
+
75
+ function validateNonNegativeNumber(value: number | undefined, fallback: number, name: string): number {
76
+ const resolved = value ?? fallback
77
+ if (!Number.isFinite(resolved) || resolved < 0)
78
+ throw new RangeError(`@prunellejs/jobs: invalid ${name} ${String(resolved)}: pass a finite number >= 0.`)
79
+ return resolved
80
+ }
81
+
82
+ function resolveDbOption(db: string | Database | undefined, root: string | undefined): string | Database {
83
+ if (db === undefined)
84
+ return ':memory:'
85
+ if (typeof db !== 'string')
86
+ return db
87
+ if (isInMemoryDb(db) || db.startsWith('file:') || isAbsolute(db) || root === undefined)
88
+ return db
89
+ return resolve(root, db)
90
+ }
91
+
92
+ function parseQueueArgs(
93
+ name: string,
94
+ schemaOrHandler: StandardSchemaV1 | JobHandler<unknown>,
95
+ handlerOrOptions?: JobHandler<unknown> | QueueOptions<StandardSchemaV1 | undefined>,
96
+ maybeOptions?: QueueBaseOptions,
97
+ ): { schema: StandardSchemaV1 | undefined, handler: JobHandler<unknown>, options: QueueBaseOptions | undefined } {
98
+ if (name.trim() === '')
99
+ throw new RangeError('@prunellejs/jobs: queue() requires a non-empty queue name.')
100
+
101
+ if (isStandardSchema(schemaOrHandler)) {
102
+ if (typeof handlerOrOptions !== 'function')
103
+ throw new TypeError(`@prunellejs/jobs: queue("${name}", schema, handler) requires a handler function.`)
104
+ return { schema: schemaOrHandler, handler: handlerOrOptions, options: maybeOptions }
105
+ }
106
+
107
+ if (typeof schemaOrHandler !== 'function')
108
+ throw new TypeError(`@prunellejs/jobs: queue("${name}", handler) requires a handler function or Standard Schema.`)
109
+
110
+ const opts = handlerOrOptions as QueueOptions<StandardSchemaV1 | undefined> | undefined
111
+ return { schema: opts?.schema, handler: schemaOrHandler, options: opts }
112
+ }
113
+
114
+ /**
115
+ * Drains queued jobs deterministically in-process.
116
+ * Accepts a `Jobs` handle, a `TestApp` (`{ app }`), or a `PrunelleApp` (`{ inject }`).
117
+ */
118
+ export async function drainJobs(target: DrainTarget, options?: DrainOptions): Promise<number> {
119
+ if ('drain' in target && typeof target.drain === 'function')
120
+ return target.drain(options)
121
+ const inject = 'app' in target
122
+ ? target.app.inject
123
+ : ('inject' in target ? target.inject : undefined)
124
+ const service = inject?.(JOBS_SERVICE)
125
+ if (service === undefined)
126
+ throw new Error('@prunellejs/jobs: drainJobs() found no @prunellejs/jobs service on the app: register `createJobs()` in `plugins`.')
127
+ if (typeof service.drain !== 'function')
128
+ throw new Error('@prunellejs/jobs: registered JOBS_SERVICE does not expose drain().')
129
+ return service.drain(options)
130
+ }
131
+
132
+ export function createJobs(options: JobsOptions = {}): Jobs {
133
+ const pollIntervalMs = validatePositiveNumber(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 'pollIntervalMs')
134
+ const scheduleIntervalMs = validatePositiveNumber(options.scheduleIntervalMs, DEFAULT_SCHEDULE_INTERVAL_MS, 'scheduleIntervalMs')
135
+ const concurrency = Math.max(1, Math.floor(validatePositiveNumber(options.concurrency, DEFAULT_CONCURRENCY, 'concurrency')))
136
+ const leaseMs = validatePositiveNumber(options.leaseMs, DEFAULT_LEASE_MS, 'leaseMs')
137
+ const shutdownTimeoutMs = validateNonNegativeNumber(options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 'shutdownTimeoutMs')
138
+ const defaultAttempts = normalizeAttempts(options.defaultAttempts, DEFAULT_ATTEMPTS)
139
+ const defaultBackoff = normalizeBackoff(options.defaultBackoff, DEFAULT_BACKOFF)
140
+ const backoffBaseMs = validateNonNegativeNumber(options.backoffBaseMs, DEFAULT_BACKOFF_BASE_MS, 'backoffBaseMs')
141
+ const maxBackoffMs = validateNonNegativeNumber(options.maxBackoffMs, DEFAULT_MAX_BACKOFF_MS, 'maxBackoffMs')
142
+ const clock = options.now ?? Date.now
143
+
144
+ const handleQueues = new Map<string, RegisteredQueue>()
145
+ const handleSchedules = new Map<string, RegisteredSchedule>()
146
+
147
+ let activeRuntime: JobsRuntime | undefined
148
+ let activeIsStandalone = false
149
+
150
+ function buildRuntime(root: string | undefined): JobsRuntime {
151
+ const store = createSqliteJobsStore(resolveDbOption(options.db, root))
152
+ return createJobsRuntime({
153
+ store,
154
+ handleQueues,
155
+ handleSchedules,
156
+ pollIntervalMs,
157
+ scheduleIntervalMs,
158
+ concurrency,
159
+ leaseMs,
160
+ shutdownTimeoutMs,
161
+ defaultAttempts,
162
+ defaultBackoff,
163
+ backoffBaseMs,
164
+ maxBackoffMs,
165
+ now: clock,
166
+ onError: options.onError,
167
+ })
168
+ }
169
+
170
+ function ensureRuntime(): JobsRuntime {
171
+ if (activeRuntime === undefined || activeRuntime.store.isClosed()) {
172
+ activeRuntime = buildRuntime(undefined)
173
+ activeIsStandalone = true
174
+ }
175
+ return activeRuntime
176
+ }
177
+
178
+ const plugin = definePlugin({
179
+ name: '@prunellejs/jobs',
180
+ enforce: 'pre',
181
+ requires() {
182
+ if (isInMemoryDb(options.db) && options.allowMemoryInProd !== true)
183
+ return ['in-memory SQLite store loses queued jobs and schedule locks on restart: pass a file path like `createJobs({ db: \'data/jobs.db\' })` (or set `allowMemoryInProd: true`).']
184
+ return []
185
+ },
186
+ async server(api) {
187
+ let runtime: JobsRuntime
188
+ if (activeIsStandalone && activeRuntime !== undefined && !activeRuntime.store.isClosed()) {
189
+ if (isInMemoryDb(options.db)) {
190
+ // Adopt jobs already enqueued into the in-memory store before server(api) ran.
191
+ runtime = activeRuntime
192
+ activeIsStandalone = false
193
+ }
194
+ else {
195
+ await activeRuntime.shutdown()
196
+ activeRuntime = undefined
197
+ activeIsStandalone = false
198
+ runtime = buildRuntime(api.root)
199
+ }
200
+ }
201
+ else {
202
+ runtime = buildRuntime(api.root)
203
+ }
204
+
205
+ activeRuntime = runtime
206
+ activeIsStandalone = false
207
+
208
+ api.provide(JOBS_SERVICE, runtime.service)
209
+ api.healthCheck('jobs', () => runtime.healthCheck())
210
+
211
+ const shouldAutoStart = options.autoStart ?? (nodeEnv() !== 'test')
212
+ if (shouldAutoStart)
213
+ runtime.start()
214
+
215
+ api.onShutdown(async () => {
216
+ await runtime.shutdown()
217
+ if (activeRuntime === runtime)
218
+ activeRuntime = undefined
219
+ })
220
+ },
221
+ })
222
+
223
+ async function dispose(): Promise<void> {
224
+ const runtime = activeRuntime
225
+ if (runtime === undefined)
226
+ return
227
+ activeRuntime = undefined
228
+ activeIsStandalone = false
229
+ await runtime.shutdown()
230
+ }
231
+
232
+ const instance: Jobs = {
233
+ ...plugin,
234
+ queue(
235
+ name: string,
236
+ schemaOrHandler: StandardSchemaV1 | JobHandler<unknown>,
237
+ handlerOrOptions?: JobHandler<unknown> | QueueOptions<StandardSchemaV1 | undefined>,
238
+ maybeOptions?: QueueBaseOptions,
239
+ ) {
240
+ const { schema, handler, options: qOpts } = parseQueueArgs(name, schemaOrHandler, handlerOrOptions, maybeOptions)
241
+ handleQueues.set(name, {
242
+ name,
243
+ handler,
244
+ attempts: normalizeAttempts(qOpts?.attempts, defaultAttempts),
245
+ backoff: normalizeBackoff(qOpts?.backoff, defaultBackoff),
246
+ ...(schema !== undefined ? { schema } : {}),
247
+ })
248
+ return instance
249
+ },
250
+ enqueue<T = unknown>(name: string, data: T, enqueueOptions?: EnqueueOptions) {
251
+ return ensureRuntime().enqueue(name, data, enqueueOptions)
252
+ },
253
+ schedule(name: string, cronExpr: string, handler: ScheduleHandler, scheduleOptions?: ScheduleOptions) {
254
+ if (name.trim() === '')
255
+ throw new RangeError('@prunellejs/jobs: schedule() requires a non-empty schedule name.')
256
+ const parsed = parseCron(cronExpr)
257
+ const timeZone = scheduleOptions?.timeZone ?? 'UTC'
258
+ assertValidTimeZone(timeZone)
259
+ handleSchedules.set(name, {
260
+ name,
261
+ cron: cronExpr,
262
+ parsed,
263
+ handler,
264
+ timeZone,
265
+ })
266
+ return instance
267
+ },
268
+ drain(drainOptions?: DrainOptions) {
269
+ return ensureRuntime().drain(drainOptions)
270
+ },
271
+ runDueSchedules(overrideNow?: number) {
272
+ return ensureRuntime().runDueSchedules(overrideNow)
273
+ },
274
+ start() {
275
+ ensureRuntime().start()
276
+ },
277
+ get<T = unknown>(id: string): JobRecord<T> | undefined {
278
+ return ensureRuntime().get<T>(id)
279
+ },
280
+ list<T = unknown>(filter?: JobListFilter): JobRecord<T>[] {
281
+ return ensureRuntime().list<T>(filter)
282
+ },
283
+ stats(): JobStats {
284
+ return ensureRuntime().stats()
285
+ },
286
+ dispose,
287
+ [Symbol.asyncDispose]: dispose,
288
+ }
289
+
290
+ return instance
291
+ }