@prunellejs/jobs 0.0.0-stage → 0.7.0
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/LICENSE +21 -0
- package/llms.txt +76 -0
- package/package.json +24 -4
- package/src/cron.ts +321 -0
- package/src/index.ts +291 -0
- package/src/runner.ts +424 -0
- package/src/store.ts +391 -0
- package/src/types.ts +260 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaynooo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/llms.txt
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# @prunellejs/jobs Reference
|
|
2
|
+
|
|
3
|
+
> Zero-dependency durable SQLite job queue and cron scheduler for Prunelle (`bun:sqlite`, retries with exponential/fixed backoff, deduplication keys, Standard Schema validation, IANA timezone cron with multi-process single-execution lock, graceful shutdown, `@prunellejs/mail` integration, and deterministic `drainJobs()` test helper).
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/jobs`:
|
|
8
|
+
- Core: `createJobs`, `drainJobs`, `JobValidationError`
|
|
9
|
+
- Cron & Duration helpers: `parseCron`, `matchesCron`, `nextCronTick`, `assertValidTimeZone`, `getZonedParts`, `floorToMinute`, `parseDuration`, `computeBackoffDelay`
|
|
10
|
+
- Types: `Jobs`, `JobsOptions`, `QueueBaseOptions`, `QueueOptions`, `EnqueueOptions`, `EnqueueResult`, `ScheduleOptions`, `JobContext`, `ScheduleContext`, `JobHandler`, `ScheduleHandler`, `JobRecord`, `JobStatus`, `JobStats`, `JobListFilter`, `DrainOptions`, `DrainTarget`, `JobErrorInfo`, `BackoffStrategy`, `Duration`, `DurationString`, `DurationUnit`, `ParsedCron`, `ZonedDateParts`.
|
|
11
|
+
|
|
12
|
+
## Setup (`createJobs(options?)`)
|
|
13
|
+
|
|
14
|
+
`createJobs()` returns a single object that is both the `PrunellePlugin` (`enforce: 'pre'`, register in `prunelle.config.ts`) and the handle routes/actions call `jobs.enqueue()` on:
|
|
15
|
+
|
|
16
|
+
- `db`: SQLite file path or existing `bun:sqlite` `Database` instance (default `':memory:'`). Relative paths resolve against the app root inside `server(api)`. A production start refuses an in-memory store with an actionable fix naming `createJobs({ db: 'data/jobs.db' })` unless `allowMemoryInProd: true`.
|
|
17
|
+
- `pollIntervalMs`: background worker poll interval in ms (default `500`).
|
|
18
|
+
- `scheduleIntervalMs`: background cron check interval in ms (default `1000`).
|
|
19
|
+
- `concurrency`: max concurrent jobs per worker (default `4`).
|
|
20
|
+
- `leaseMs`: running-job lease duration in ms before a crashed worker's job is reclaimed (default `60_000`).
|
|
21
|
+
- `shutdownTimeoutMs`: max ms `onShutdown()` waits for in-flight jobs before releasing remaining claims back to `pending` (default `5000`).
|
|
22
|
+
- `defaultAttempts`: default max attempts per job (default `3`).
|
|
23
|
+
- `defaultBackoff`: `'exponential' | 'fixed' | number` (default `'exponential'`, base `backoffBaseMs` `1000` ms, capped at `maxBackoffMs` `3_600_000` ms).
|
|
24
|
+
- `autoStart`: starts background poll/schedule loops inside `server(api)` (defaults to `true` outside `NODE_ENV=test`; disabled in tests so `drainJobs(app)` is deterministic).
|
|
25
|
+
- `now`: optional clock function (`() => number`) for deterministic time control.
|
|
26
|
+
- `onError`: optional callback notified whenever a job or schedule handler throws.
|
|
27
|
+
|
|
28
|
+
## Queues & Standard Schema Validation
|
|
29
|
+
|
|
30
|
+
- Untyped/explicitly typed: `jobs.queue<Payload>('emails', handler, { attempts, backoff })`
|
|
31
|
+
- Standard Schema (Zod, Valibot, ArkType, etc.), both forms supported with full static input inference and runtime validation on `enqueue()` and execution:
|
|
32
|
+
- `jobs.queue('emails', emailSchema, (data, ctx) => { ... }, { attempts: 5, backoff: 'exponential' })`
|
|
33
|
+
- `jobs.queue('emails', (data, ctx) => { ... }, { schema: emailSchema, attempts: 5, backoff: 'fixed' })`
|
|
34
|
+
- Invalid payloads throw `JobValidationError` (with `.issues` and `.fieldErrors`).
|
|
35
|
+
- `await jobs.enqueue(name, data, { delay, key })`:
|
|
36
|
+
- `delay`: milliseconds or duration string (`'500ms'`, `'5s'`, `'10m'`, `'2h'`, `'1d'`).
|
|
37
|
+
- `key`: per-queue deduplication key enforced by a SQLite unique index across `pending`/`running`/`completed`/`failed` rows (survives restarts; re-enqueuing returns `{ id, queue, runAt, deduplicated: true }`).
|
|
38
|
+
|
|
39
|
+
## Cron Schedules & Multi-Process Lock
|
|
40
|
+
|
|
41
|
+
- `jobs.schedule(name, cronExpr, handler, { timeZone })`:
|
|
42
|
+
- Standard 5-field cron (`minute hour dom month dow`: `*`, `*/n`, `a-b`, `a-b/n`, lists `a,b,c`, month/weekday names `JAN-DEC`/`SUN-SAT`, macros `@hourly`/`@daily`/`@weekly`/`@monthly`/`@yearly`).
|
|
43
|
+
- Evaluated in `timeZone` (default `'UTC'`) via `Intl.DateTimeFormat`; both `cronExpr` and `timeZone` are validated eagerly.
|
|
44
|
+
- Each `(schedule_name, tick_ms)` is claimed atomically in SQLite (`WAL` + `BEGIN IMMEDIATE` + primary key), guaranteeing two processes sharing the same SQLite file never run the same tick twice.
|
|
45
|
+
|
|
46
|
+
## Server Lifecycle, Health & Mail Integration
|
|
47
|
+
|
|
48
|
+
- Inside `server(api)`: opens the SQLite store, provides `JOBS_SERVICE` (so `@prunellejs/mail` automatically registers `mail.deliver` and retries failed deliveries durably), registers `api.healthCheck('jobs', ...)`, and registers `api.onShutdown()` to stop new claims, drain in-flight work up to `shutdownTimeoutMs`, release uncompleted claims back to `pending`, and close the DB it opened.
|
|
49
|
+
- Standalone usage outside a server opens the store lazily on first call; call `await jobs.dispose()` when done.
|
|
50
|
+
|
|
51
|
+
## Testing (`drainJobs`)
|
|
52
|
+
|
|
53
|
+
- `await drainJobs(app, { includeDelayed?, now?, maxJobs? })` accepts a `Jobs` handle, a `TestApp` (`testApp()`), or a `PrunelleApp` (`createServer()`), resolving `JOBS_SERVICE` automatically across bundled server modules and returning the number of executed jobs.
|
|
54
|
+
|
|
55
|
+
## Snippet
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
// src/jobs.ts (and register `plugins: [jobs]` in prunelle.config.ts)
|
|
59
|
+
import { createJobs } from '@prunellejs/jobs'
|
|
60
|
+
|
|
61
|
+
export const jobs = createJobs({ db: 'data/jobs.db' })
|
|
62
|
+
|
|
63
|
+
jobs.queue<{ userId: string }>('welcome', async (data) => {
|
|
64
|
+
await sendWelcome(data.userId)
|
|
65
|
+
}, { attempts: 5, backoff: 'exponential' })
|
|
66
|
+
|
|
67
|
+
jobs.schedule('nightly-cleanup', '0 3 * * *', async () => {
|
|
68
|
+
await pruneExpiredTokens()
|
|
69
|
+
}, { timeZone: 'Europe/Paris' })
|
|
70
|
+
|
|
71
|
+
// In an action or route:
|
|
72
|
+
await jobs.enqueue('welcome', { userId: 'u_1' }, { delay: '5s', key: 'welcome:u_1' })
|
|
73
|
+
|
|
74
|
+
// In a test with testApp():
|
|
75
|
+
// await drainJobs(app, { includeDelayed: true })
|
|
76
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/jobs",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "Zero-dependency durable SQLite job queue and cron scheduler plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"bun": ">=1.4.0"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
21
|
+
"directory": "packages/plugin-jobs"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"prunelle": "^0.7.0"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/cron.ts
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
// Zero-dependency 5-field cron parser and IANA timezone evaluator backed by Intl.DateTimeFormat.
|
|
2
|
+
|
|
3
|
+
export interface ParsedCron {
|
|
4
|
+
readonly expression: string
|
|
5
|
+
readonly minutes: ReadonlySet<number>
|
|
6
|
+
readonly hours: ReadonlySet<number>
|
|
7
|
+
readonly dom: ReadonlySet<number>
|
|
8
|
+
readonly months: ReadonlySet<number>
|
|
9
|
+
readonly dow: ReadonlySet<number>
|
|
10
|
+
readonly domRestricted: boolean
|
|
11
|
+
readonly dowRestricted: boolean
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ZonedDateParts {
|
|
15
|
+
readonly year: number
|
|
16
|
+
readonly month: number
|
|
17
|
+
readonly day: number
|
|
18
|
+
readonly hour: number
|
|
19
|
+
readonly minute: number
|
|
20
|
+
readonly dow: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const MACROS: Readonly<Record<string, string>> = {
|
|
24
|
+
'@yearly': '0 0 1 1 *',
|
|
25
|
+
'@annually': '0 0 1 1 *',
|
|
26
|
+
'@monthly': '0 0 1 * *',
|
|
27
|
+
'@weekly': '0 0 * * 0',
|
|
28
|
+
'@daily': '0 0 * * *',
|
|
29
|
+
'@midnight': '0 0 * * *',
|
|
30
|
+
'@hourly': '0 * * * *',
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const MONTH_NAMES: Readonly<Record<string, number>> = {
|
|
34
|
+
jan: 1,
|
|
35
|
+
feb: 2,
|
|
36
|
+
mar: 3,
|
|
37
|
+
apr: 4,
|
|
38
|
+
may: 5,
|
|
39
|
+
jun: 6,
|
|
40
|
+
jul: 7,
|
|
41
|
+
aug: 8,
|
|
42
|
+
sep: 9,
|
|
43
|
+
oct: 10,
|
|
44
|
+
nov: 11,
|
|
45
|
+
dec: 12,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const DOW_NAMES: Readonly<Record<string, number>> = {
|
|
49
|
+
sun: 0,
|
|
50
|
+
mon: 1,
|
|
51
|
+
tue: 2,
|
|
52
|
+
wed: 3,
|
|
53
|
+
thu: 4,
|
|
54
|
+
fri: 5,
|
|
55
|
+
sat: 6,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const WEEKDAY_SHORT_TO_DOW: Readonly<Record<string, number>> = {
|
|
59
|
+
Sun: 0,
|
|
60
|
+
Mon: 1,
|
|
61
|
+
Tue: 2,
|
|
62
|
+
Wed: 3,
|
|
63
|
+
Thu: 4,
|
|
64
|
+
Fri: 5,
|
|
65
|
+
Sat: 6,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const MAX_DAYS_IN_MONTH: Readonly<Record<number, number>> = {
|
|
69
|
+
1: 31,
|
|
70
|
+
2: 29,
|
|
71
|
+
3: 31,
|
|
72
|
+
4: 30,
|
|
73
|
+
5: 31,
|
|
74
|
+
6: 30,
|
|
75
|
+
7: 31,
|
|
76
|
+
8: 31,
|
|
77
|
+
9: 30,
|
|
78
|
+
10: 31,
|
|
79
|
+
11: 30,
|
|
80
|
+
12: 31,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const FORMATTERS = new Map<string, Intl.DateTimeFormat>()
|
|
84
|
+
|
|
85
|
+
export function assertValidTimeZone(timeZone: string): void {
|
|
86
|
+
if (typeof timeZone !== 'string' || timeZone.trim() === '')
|
|
87
|
+
throw new RangeError('@prunellejs/jobs: invalid timeZone: pass a non-empty IANA timezone name such as "UTC" or "Europe/Paris".')
|
|
88
|
+
if (FORMATTERS.has(timeZone))
|
|
89
|
+
return
|
|
90
|
+
try {
|
|
91
|
+
const fmt = new Intl.DateTimeFormat('en-US', {
|
|
92
|
+
timeZone,
|
|
93
|
+
year: 'numeric',
|
|
94
|
+
month: '2-digit',
|
|
95
|
+
day: '2-digit',
|
|
96
|
+
hour: '2-digit',
|
|
97
|
+
minute: '2-digit',
|
|
98
|
+
weekday: 'short',
|
|
99
|
+
hourCycle: 'h23',
|
|
100
|
+
})
|
|
101
|
+
FORMATTERS.set(timeZone, fmt)
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new RangeError(`@prunellejs/jobs: invalid IANA timeZone "${timeZone}": pass a valid IANA timezone such as "UTC" or "Europe/Paris".`)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function getFormatter(timeZone: string): Intl.DateTimeFormat {
|
|
109
|
+
let fmt = FORMATTERS.get(timeZone)
|
|
110
|
+
if (fmt === undefined) {
|
|
111
|
+
assertValidTimeZone(timeZone)
|
|
112
|
+
fmt = FORMATTERS.get(timeZone)!
|
|
113
|
+
}
|
|
114
|
+
return fmt
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function getZonedParts(tsMs: number, timeZone = 'UTC'): ZonedDateParts {
|
|
118
|
+
const parts = getFormatter(timeZone).formatToParts(new Date(tsMs))
|
|
119
|
+
let year = 0
|
|
120
|
+
let month = 1
|
|
121
|
+
let day = 1
|
|
122
|
+
let hour = 0
|
|
123
|
+
let minute = 0
|
|
124
|
+
let dow = 0
|
|
125
|
+
for (let i = 0; i < parts.length; i++) {
|
|
126
|
+
const p = parts[i]!
|
|
127
|
+
switch (p.type) {
|
|
128
|
+
case 'year':
|
|
129
|
+
year = Number(p.value)
|
|
130
|
+
break
|
|
131
|
+
case 'month':
|
|
132
|
+
month = Number(p.value)
|
|
133
|
+
break
|
|
134
|
+
case 'day':
|
|
135
|
+
day = Number(p.value)
|
|
136
|
+
break
|
|
137
|
+
case 'hour':
|
|
138
|
+
hour = Number(p.value) % 24
|
|
139
|
+
break
|
|
140
|
+
case 'minute':
|
|
141
|
+
minute = Number(p.value)
|
|
142
|
+
break
|
|
143
|
+
case 'weekday':
|
|
144
|
+
dow = WEEKDAY_SHORT_TO_DOW[p.value] ?? 0
|
|
145
|
+
break
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return { year, month, day, hour, minute, dow }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
interface FieldSpec {
|
|
152
|
+
readonly label: string
|
|
153
|
+
readonly min: number
|
|
154
|
+
readonly max: number
|
|
155
|
+
readonly names?: Readonly<Record<string, number>> | undefined
|
|
156
|
+
readonly wrapSevenToZero?: boolean | undefined
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function parseAtom(token: string, spec: FieldSpec, expr: string): number {
|
|
160
|
+
const lowered = token.toLowerCase()
|
|
161
|
+
if (spec.names !== undefined && Object.hasOwn(spec.names, lowered))
|
|
162
|
+
return spec.names[lowered]!
|
|
163
|
+
if (!/^\d+$/.test(token))
|
|
164
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": unexpected ${spec.label} token "${token}".`)
|
|
165
|
+
const n = Number(token)
|
|
166
|
+
if (!Number.isInteger(n) || n < spec.min || n > spec.max)
|
|
167
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": ${spec.label} value ${n} is out of range ${spec.min}-${spec.max}.`)
|
|
168
|
+
return n
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function addRange(out: Set<number>, start: number, end: number, step: number, wrapSeven: boolean): void {
|
|
172
|
+
for (let v = start; v <= end; v += step)
|
|
173
|
+
out.add(wrapSeven && v === 7 ? 0 : v)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function parseFieldSegment(segment: string, spec: FieldSpec, expr: string, out: Set<number>): void {
|
|
177
|
+
const slashParts = segment.split('/')
|
|
178
|
+
if (slashParts.length > 2)
|
|
179
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": malformed ${spec.label} step "${segment}".`)
|
|
180
|
+
|
|
181
|
+
const rangePart = slashParts[0]!
|
|
182
|
+
let step = 1
|
|
183
|
+
if (slashParts.length === 2) {
|
|
184
|
+
const rawStep = slashParts[1]!
|
|
185
|
+
if (!/^\d+$/.test(rawStep) || Number(rawStep) < 1)
|
|
186
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": ${spec.label} step "${rawStep}" must be a positive integer.`)
|
|
187
|
+
step = Number(rawStep)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const wrapSeven = spec.wrapSevenToZero === true
|
|
191
|
+
if (rangePart === '*') {
|
|
192
|
+
const end = wrapSeven ? 6 : spec.max
|
|
193
|
+
addRange(out, spec.min, end, step, wrapSeven)
|
|
194
|
+
return
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const dashParts = rangePart.split('-')
|
|
198
|
+
if (dashParts.length > 2)
|
|
199
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": malformed ${spec.label} range "${segment}".`)
|
|
200
|
+
|
|
201
|
+
if (dashParts.length === 1) {
|
|
202
|
+
const start = parseAtom(dashParts[0]!, spec, expr)
|
|
203
|
+
if (slashParts.length === 2) {
|
|
204
|
+
const end = wrapSeven ? 6 : spec.max
|
|
205
|
+
addRange(out, start, end, step, wrapSeven)
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
out.add(wrapSeven && start === 7 ? 0 : start)
|
|
209
|
+
}
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const start = parseAtom(dashParts[0]!, spec, expr)
|
|
214
|
+
const end = parseAtom(dashParts[1]!, spec, expr)
|
|
215
|
+
if (start > end)
|
|
216
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": ${spec.label} range "${rangePart}" has start > end.`)
|
|
217
|
+
addRange(out, start, end, step, wrapSeven)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function parseField(raw: string, spec: FieldSpec, expr: string): Set<number> {
|
|
221
|
+
if (raw.length === 0)
|
|
222
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": empty ${spec.label} field.`)
|
|
223
|
+
const out = new Set<number>()
|
|
224
|
+
const segments = raw.split(',')
|
|
225
|
+
for (let i = 0; i < segments.length; i++) {
|
|
226
|
+
const seg = segments[i]!
|
|
227
|
+
if (seg.length === 0)
|
|
228
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expr}": empty segment in ${spec.label} field "${raw}".`)
|
|
229
|
+
parseFieldSegment(seg, spec, expr, out)
|
|
230
|
+
}
|
|
231
|
+
return out
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function hasReachableMonthDay(months: ReadonlySet<number>, dom: ReadonlySet<number>): boolean {
|
|
235
|
+
for (const m of months) {
|
|
236
|
+
const maxDay = MAX_DAYS_IN_MONTH[m] ?? 31
|
|
237
|
+
for (const d of dom) {
|
|
238
|
+
if (d <= maxDay)
|
|
239
|
+
return true
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return false
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function parseCron(expression: string): ParsedCron {
|
|
246
|
+
const trimmed = expression.trim()
|
|
247
|
+
if (trimmed.length === 0)
|
|
248
|
+
throw new RangeError('@prunellejs/jobs: invalid cron expression "": pass a 5-field cron expression ("minute hour dom month dow").')
|
|
249
|
+
|
|
250
|
+
const expanded = MACROS[trimmed.toLowerCase()] ?? trimmed
|
|
251
|
+
const fields = expanded.split(/\s+/)
|
|
252
|
+
if (fields.length !== 5)
|
|
253
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expression}": expected 5 whitespace-separated fields (minute hour dom month dow), got ${fields.length}.`)
|
|
254
|
+
|
|
255
|
+
const [minRaw, hourRaw, domRaw, monthRaw, dowRaw] = fields as [string, string, string, string, string]
|
|
256
|
+
const minutes = parseField(minRaw, { label: 'minute', min: 0, max: 59 }, expression)
|
|
257
|
+
const hours = parseField(hourRaw, { label: 'hour', min: 0, max: 23 }, expression)
|
|
258
|
+
const dom = parseField(domRaw, { label: 'day-of-month', min: 1, max: 31 }, expression)
|
|
259
|
+
const months = parseField(monthRaw, { label: 'month', min: 1, max: 12, names: MONTH_NAMES }, expression)
|
|
260
|
+
const dow = parseField(dowRaw, { label: 'day-of-week', min: 0, max: 7, names: DOW_NAMES, wrapSevenToZero: true }, expression)
|
|
261
|
+
|
|
262
|
+
const domRestricted = domRaw !== '*' && domRaw !== '*/1'
|
|
263
|
+
const dowRestricted = dowRaw !== '*' && dowRaw !== '*/1'
|
|
264
|
+
|
|
265
|
+
if (!dowRestricted && !hasReachableMonthDay(months, dom))
|
|
266
|
+
throw new RangeError(`@prunellejs/jobs: invalid cron expression "${expression}": no calendar date matches day-of-month "${domRaw}" in month "${monthRaw}".`)
|
|
267
|
+
|
|
268
|
+
return { expression, minutes, hours, dom, months, dow, domRestricted, dowRestricted }
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function matchesDay(schedule: ParsedCron, day: number, dow: number): boolean {
|
|
272
|
+
const domOk = schedule.dom.has(day)
|
|
273
|
+
const dowOk = schedule.dow.has(dow)
|
|
274
|
+
if (schedule.domRestricted && schedule.dowRestricted)
|
|
275
|
+
return domOk || dowOk
|
|
276
|
+
return domOk && dowOk
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export function matchesCron(schedule: ParsedCron, tsMs: number, timeZone = 'UTC'): boolean {
|
|
280
|
+
const parts = getZonedParts(tsMs, timeZone)
|
|
281
|
+
return schedule.minutes.has(parts.minute)
|
|
282
|
+
&& schedule.hours.has(parts.hour)
|
|
283
|
+
&& schedule.months.has(parts.month)
|
|
284
|
+
&& matchesDay(schedule, parts.day, parts.dow)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const MINUTE_MS = 60_000
|
|
288
|
+
const MAX_SEARCH_SPAN_MS = 5 * 366 * 24 * 60 * MINUTE_MS
|
|
289
|
+
|
|
290
|
+
/** Computes the next exact minute boundary (UTC epoch ms) strictly after `afterMs` matching `schedule` in `timeZone`. */
|
|
291
|
+
export function nextCronTick(schedule: ParsedCron, afterMs: number, timeZone = 'UTC'): number {
|
|
292
|
+
assertValidTimeZone(timeZone)
|
|
293
|
+
let cursor = (Math.floor(afterMs / MINUTE_MS) + 1) * MINUTE_MS
|
|
294
|
+
const limit = cursor + MAX_SEARCH_SPAN_MS
|
|
295
|
+
|
|
296
|
+
while (cursor <= limit) {
|
|
297
|
+
const parts = getZonedParts(cursor, timeZone)
|
|
298
|
+
if (!schedule.months.has(parts.month) || !matchesDay(schedule, parts.day, parts.dow)) {
|
|
299
|
+
if (parts.hour < 22)
|
|
300
|
+
cursor += (22 - parts.hour) * 60 * MINUTE_MS
|
|
301
|
+
else
|
|
302
|
+
cursor += Math.min(30, 60 - parts.minute) * MINUTE_MS
|
|
303
|
+
continue
|
|
304
|
+
}
|
|
305
|
+
if (!schedule.hours.has(parts.hour)) {
|
|
306
|
+
cursor += Math.min(30, 60 - parts.minute) * MINUTE_MS
|
|
307
|
+
continue
|
|
308
|
+
}
|
|
309
|
+
if (!schedule.minutes.has(parts.minute)) {
|
|
310
|
+
cursor += MINUTE_MS
|
|
311
|
+
continue
|
|
312
|
+
}
|
|
313
|
+
return cursor
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
throw new RangeError(`@prunellejs/jobs: cron expression "${schedule.expression}" has no matching tick within 5 years in timeZone "${timeZone}".`)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function floorToMinute(tsMs: number): number {
|
|
320
|
+
return Math.floor(tsMs / MINUTE_MS) * MINUTE_MS
|
|
321
|
+
}
|