@vantedev/groundwork 0.0.0-stage → 0.2.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/CHANGELOG.md +87 -0
- package/LICENSE +21 -0
- package/README.md +350 -2
- package/dist/api-keys/api-keys.d.ts +56 -0
- package/dist/api-keys/api-keys.d.ts.map +1 -0
- package/dist/api-keys/api-keys.js +619 -0
- package/dist/api-keys/api-keys.js.map +1 -0
- package/dist/api-keys/audit.d.ts +17 -0
- package/dist/api-keys/audit.d.ts.map +1 -0
- package/dist/api-keys/audit.js +76 -0
- package/dist/api-keys/audit.js.map +1 -0
- package/dist/api-keys/format.d.ts +32 -0
- package/dist/api-keys/format.d.ts.map +1 -0
- package/dist/api-keys/format.js +92 -0
- package/dist/api-keys/format.js.map +1 -0
- package/dist/api-keys/index.d.ts +25 -0
- package/dist/api-keys/index.d.ts.map +1 -0
- package/dist/api-keys/index.js +23 -0
- package/dist/api-keys/index.js.map +1 -0
- package/dist/api-keys/policy.d.ts +16 -0
- package/dist/api-keys/policy.d.ts.map +1 -0
- package/dist/api-keys/policy.js +95 -0
- package/dist/api-keys/policy.js.map +1 -0
- package/dist/api-keys/responses.d.ts +6 -0
- package/dist/api-keys/responses.d.ts.map +1 -0
- package/dist/api-keys/responses.js +54 -0
- package/dist/api-keys/responses.js.map +1 -0
- package/dist/api-keys/scopes.d.ts +13 -0
- package/dist/api-keys/scopes.d.ts.map +1 -0
- package/dist/api-keys/scopes.js +49 -0
- package/dist/api-keys/scopes.js.map +1 -0
- package/dist/api-keys/types.d.ts +173 -0
- package/dist/api-keys/types.d.ts.map +1 -0
- package/dist/api-keys/types.js +2 -0
- package/dist/api-keys/types.js.map +1 -0
- package/dist/audit/audit-log.d.ts +35 -0
- package/dist/audit/audit-log.d.ts.map +1 -0
- package/dist/audit/audit-log.js +277 -0
- package/dist/audit/audit-log.js.map +1 -0
- package/dist/audit/cursor.d.ts +13 -0
- package/dist/audit/cursor.d.ts.map +1 -0
- package/dist/audit/cursor.js +26 -0
- package/dist/audit/cursor.js.map +1 -0
- package/dist/audit/diff.d.ts +19 -0
- package/dist/audit/diff.d.ts.map +1 -0
- package/dist/audit/diff.js +59 -0
- package/dist/audit/diff.js.map +1 -0
- package/dist/audit/index.d.ts +25 -0
- package/dist/audit/index.d.ts.map +1 -0
- package/dist/audit/index.js +24 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/json.d.ts +23 -0
- package/dist/audit/json.d.ts.map +1 -0
- package/dist/audit/json.js +120 -0
- package/dist/audit/json.js.map +1 -0
- package/dist/audit/types.d.ts +118 -0
- package/dist/audit/types.d.ts.map +1 -0
- package/dist/audit/types.js +2 -0
- package/dist/audit/types.js.map +1 -0
- package/dist/idempotency/http.d.ts +27 -0
- package/dist/idempotency/http.d.ts.map +1 -0
- package/dist/idempotency/http.js +130 -0
- package/dist/idempotency/http.js.map +1 -0
- package/dist/idempotency/idempotency.d.ts +45 -0
- package/dist/idempotency/idempotency.d.ts.map +1 -0
- package/dist/idempotency/idempotency.js +302 -0
- package/dist/idempotency/idempotency.js.map +1 -0
- package/dist/idempotency/index.d.ts +25 -0
- package/dist/idempotency/index.d.ts.map +1 -0
- package/dist/idempotency/index.js +24 -0
- package/dist/idempotency/index.js.map +1 -0
- package/dist/idempotency/keys.d.ts +13 -0
- package/dist/idempotency/keys.d.ts.map +1 -0
- package/dist/idempotency/keys.js +9 -0
- package/dist/idempotency/keys.js.map +1 -0
- package/dist/idempotency/types.d.ts +92 -0
- package/dist/idempotency/types.d.ts.map +1 -0
- package/dist/idempotency/types.js +2 -0
- package/dist/idempotency/types.js.map +1 -0
- package/dist/index.d.ts +122 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +201 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/cidr.d.ts +21 -0
- package/dist/internal/cidr.d.ts.map +1 -0
- package/dist/internal/cidr.js +159 -0
- package/dist/internal/cidr.js.map +1 -0
- package/dist/internal/clock.d.ts +6 -0
- package/dist/internal/clock.d.ts.map +1 -0
- package/dist/internal/clock.js +4 -0
- package/dist/internal/clock.js.map +1 -0
- package/dist/internal/crypto.d.ts +44 -0
- package/dist/internal/crypto.d.ts.map +1 -0
- package/dist/internal/crypto.js +97 -0
- package/dist/internal/crypto.js.map +1 -0
- package/dist/internal/db.d.ts +14 -0
- package/dist/internal/db.d.ts.map +1 -0
- package/dist/internal/db.js +20 -0
- package/dist/internal/db.js.map +1 -0
- package/dist/internal/duration.d.ts +25 -0
- package/dist/internal/duration.d.ts.map +1 -0
- package/dist/internal/duration.js +39 -0
- package/dist/internal/duration.js.map +1 -0
- package/dist/internal/errors.d.ts +33 -0
- package/dist/internal/errors.d.ts.map +1 -0
- package/dist/internal/errors.js +29 -0
- package/dist/internal/errors.js.map +1 -0
- package/dist/internal/logger.d.ts +37 -0
- package/dist/internal/logger.d.ts.map +1 -0
- package/dist/internal/logger.js +54 -0
- package/dist/internal/logger.js.map +1 -0
- package/dist/internal/standard-schema.d.ts +49 -0
- package/dist/internal/standard-schema.d.ts.map +1 -0
- package/dist/internal/standard-schema.js +16 -0
- package/dist/internal/standard-schema.js.map +1 -0
- package/dist/internal/table.d.ts +7 -0
- package/dist/internal/table.d.ts.map +1 -0
- package/dist/internal/table.js +20 -0
- package/dist/internal/table.js.map +1 -0
- package/dist/jobs/backoff.d.ts +7 -0
- package/dist/jobs/backoff.d.ts.map +1 -0
- package/dist/jobs/backoff.js +10 -0
- package/dist/jobs/backoff.js.map +1 -0
- package/dist/jobs/index.d.ts +31 -0
- package/dist/jobs/index.d.ts.map +1 -0
- package/dist/jobs/index.js +29 -0
- package/dist/jobs/index.js.map +1 -0
- package/dist/jobs/jobs.d.ts +42 -0
- package/dist/jobs/jobs.d.ts.map +1 -0
- package/dist/jobs/jobs.js +741 -0
- package/dist/jobs/jobs.js.map +1 -0
- package/dist/jobs/types.d.ts +199 -0
- package/dist/jobs/types.d.ts.map +1 -0
- package/dist/jobs/types.js +2 -0
- package/dist/jobs/types.js.map +1 -0
- package/dist/next/client-ip.d.ts +42 -0
- package/dist/next/client-ip.d.ts.map +1 -0
- package/dist/next/client-ip.js +59 -0
- package/dist/next/client-ip.js.map +1 -0
- package/dist/next/index.d.ts +29 -0
- package/dist/next/index.d.ts.map +1 -0
- package/dist/next/index.js +29 -0
- package/dist/next/index.js.map +1 -0
- package/dist/next/jobs-route.d.ts +31 -0
- package/dist/next/jobs-route.d.ts.map +1 -0
- package/dist/next/jobs-route.js +53 -0
- package/dist/next/jobs-route.js.map +1 -0
- package/dist/next/response.d.ts +6 -0
- package/dist/next/response.d.ts.map +1 -0
- package/dist/next/response.js +25 -0
- package/dist/next/response.js.map +1 -0
- package/dist/next/route-helpers.d.ts +67 -0
- package/dist/next/route-helpers.d.ts.map +1 -0
- package/dist/next/route-helpers.js +93 -0
- package/dist/next/route-helpers.js.map +1 -0
- package/dist/rate-limit/index.d.ts +19 -0
- package/dist/rate-limit/index.d.ts.map +1 -0
- package/dist/rate-limit/index.js +18 -0
- package/dist/rate-limit/index.js.map +1 -0
- package/dist/rate-limit/limiter.d.ts +60 -0
- package/dist/rate-limit/limiter.d.ts.map +1 -0
- package/dist/rate-limit/limiter.js +147 -0
- package/dist/rate-limit/limiter.js.map +1 -0
- package/dist/rate-limit/memory-store.d.ts +23 -0
- package/dist/rate-limit/memory-store.d.ts.map +1 -0
- package/dist/rate-limit/memory-store.js +77 -0
- package/dist/rate-limit/memory-store.js.map +1 -0
- package/dist/rate-limit/policy.d.ts +31 -0
- package/dist/rate-limit/policy.d.ts.map +1 -0
- package/dist/rate-limit/policy.js +174 -0
- package/dist/rate-limit/policy.js.map +1 -0
- package/dist/rate-limit/postgres-store.d.ts +13 -0
- package/dist/rate-limit/postgres-store.d.ts.map +1 -0
- package/dist/rate-limit/postgres-store.js +129 -0
- package/dist/rate-limit/postgres-store.js.map +1 -0
- package/dist/rate-limit/redis-store.d.ts +24 -0
- package/dist/rate-limit/redis-store.d.ts.map +1 -0
- package/dist/rate-limit/redis-store.js +97 -0
- package/dist/rate-limit/redis-store.js.map +1 -0
- package/dist/rate-limit/types.d.ts +140 -0
- package/dist/rate-limit/types.d.ts.map +1 -0
- package/dist/rate-limit/types.js +2 -0
- package/dist/rate-limit/types.js.map +1 -0
- package/dist/schema/api-keys.d.ts +545 -0
- package/dist/schema/api-keys.d.ts.map +1 -0
- package/dist/schema/api-keys.js +83 -0
- package/dist/schema/api-keys.js.map +1 -0
- package/dist/schema/audit-log.d.ts +248 -0
- package/dist/schema/audit-log.d.ts.map +1 -0
- package/dist/schema/audit-log.js +56 -0
- package/dist/schema/audit-log.js.map +1 -0
- package/dist/schema/factory.d.ts +19 -0
- package/dist/schema/factory.d.ts.map +1 -0
- package/dist/schema/factory.js +39 -0
- package/dist/schema/factory.js.map +1 -0
- package/dist/schema/idempotency-keys.d.ts +178 -0
- package/dist/schema/idempotency-keys.d.ts.map +1 -0
- package/dist/schema/idempotency-keys.js +41 -0
- package/dist/schema/idempotency-keys.js.map +1 -0
- package/dist/schema/index.d.ts +61 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +28 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/schema/jobs.d.ts +487 -0
- package/dist/schema/jobs.d.ts.map +1 -0
- package/dist/schema/jobs.js +103 -0
- package/dist/schema/jobs.js.map +1 -0
- package/dist/schema/rate-limits.d.ts +108 -0
- package/dist/schema/rate-limits.d.ts.map +1 -0
- package/dist/schema/rate-limits.js +27 -0
- package/dist/schema/rate-limits.js.map +1 -0
- package/dist/testing/index.d.ts +25 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +37 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +117 -4
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { hostname } from "node:os";
|
|
3
|
+
import { sql } from "drizzle-orm";
|
|
4
|
+
import { toJsonValue } from "../audit/json.js";
|
|
5
|
+
import { rowsOf, toNumber } from "../internal/db.js";
|
|
6
|
+
import { isDuration, parseDuration } from "../internal/duration.js";
|
|
7
|
+
import { errorText, GroundworkError } from "../internal/errors.js";
|
|
8
|
+
import { consoleLogger, createOnceLogger } from "../internal/logger.js";
|
|
9
|
+
import { validateWith } from "../internal/standard-schema.js";
|
|
10
|
+
import { assertTableColumns } from "../internal/table.js";
|
|
11
|
+
import { JOB_COLUMNS, JOB_SCHEDULE_COLUMNS, } from "../schema/jobs.js";
|
|
12
|
+
import { backoffDelayMs } from "./backoff.js";
|
|
13
|
+
const NAME_PATTERN = /^[A-Za-z0-9_.:-]{1,100}$/;
|
|
14
|
+
const SCHEDULE_PREFIX = "schedule:";
|
|
15
|
+
const MAX_LIST = 1_000;
|
|
16
|
+
const PRUNE_BATCH = 5_000;
|
|
17
|
+
const MAX_ERROR_LENGTH = 2_000;
|
|
18
|
+
const ms = (column) => `(extract(epoch from ${column}) * 1000)::float8`;
|
|
19
|
+
const RECORD = sql.raw(`jsonb_build_object(
|
|
20
|
+
'id', j.id::text, 'type', j.type, 'payload', j.payload, 'status', j.status, 'priority', j.priority,
|
|
21
|
+
'attempts', j.attempts, 'max_attempts', j.max_attempts, 'run_at', ${ms("j.run_at")},
|
|
22
|
+
'locked_until', ${ms("j.locked_until")}, 'locked_by', j.locked_by, 'dedupe_key', j.dedupe_key,
|
|
23
|
+
'last_error', j.last_error, 'result', j.result, 'created_at', ${ms("j.created_at")},
|
|
24
|
+
'started_at', ${ms("j.started_at")}, 'completed_at', ${ms("j.completed_at")}, 'updated_at', ${ms("j.updated_at")}
|
|
25
|
+
)::text`);
|
|
26
|
+
const toDate = (value) => (value === null ? null : new Date(value));
|
|
27
|
+
function toRecord(row) {
|
|
28
|
+
return {
|
|
29
|
+
id: row.id,
|
|
30
|
+
type: row.type,
|
|
31
|
+
schedule: row.type.startsWith(SCHEDULE_PREFIX) ? row.type.slice(SCHEDULE_PREFIX.length) : null,
|
|
32
|
+
status: row.status,
|
|
33
|
+
payload: row.payload,
|
|
34
|
+
priority: row.priority,
|
|
35
|
+
attempts: row.attempts,
|
|
36
|
+
maxAttempts: row.max_attempts,
|
|
37
|
+
runAt: new Date(row.run_at),
|
|
38
|
+
lockedUntil: toDate(row.locked_until),
|
|
39
|
+
lockedBy: row.locked_by,
|
|
40
|
+
dedupeKey: row.dedupe_key,
|
|
41
|
+
lastError: row.last_error,
|
|
42
|
+
result: row.result,
|
|
43
|
+
createdAt: new Date(row.created_at),
|
|
44
|
+
startedAt: toDate(row.started_at),
|
|
45
|
+
completedAt: toDate(row.completed_at),
|
|
46
|
+
updatedAt: new Date(row.updated_at),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function validateName(value, label) {
|
|
50
|
+
if (typeof value !== "string" || !NAME_PATTERN.test(value)) {
|
|
51
|
+
throw new GroundworkError("invalid_config", `Invalid ${label} ${JSON.stringify(value)}: use 1 to 100 letters, digits or _ . : - (for example "email.receipt").`);
|
|
52
|
+
}
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
function positiveInt(value, label, code) {
|
|
56
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
57
|
+
throw new GroundworkError(code, `${label} must be a positive integer.`);
|
|
58
|
+
}
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
function integer(value, label, code) {
|
|
62
|
+
if (!Number.isSafeInteger(value) || Math.abs(value) > 1_000_000) {
|
|
63
|
+
throw new GroundworkError(code, `${label} must be an integer between -1,000,000 and 1,000,000.`);
|
|
64
|
+
}
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Creates background jobs and schedules on your Postgres.
|
|
69
|
+
*
|
|
70
|
+
* ```ts
|
|
71
|
+
* const jobs = createJobs({ db, table: tables.jobs, schedulesTable: tables.jobSchedules });
|
|
72
|
+
* export const sendReceipt = jobs.define("email.receipt", {
|
|
73
|
+
* schema: z.object({ orderId: z.string() }),
|
|
74
|
+
* async run({ orderId }, { signal }) { await mailer.send(orderId, { signal }); },
|
|
75
|
+
* });
|
|
76
|
+
* await sendReceipt.enqueue({ orderId }, { tx, dedupeKey: `receipt:${orderId}` });
|
|
77
|
+
* await jobs.work({ signal });
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export function createJobs(options) {
|
|
81
|
+
if (typeof options !== "object" || options === null) {
|
|
82
|
+
throw new GroundworkError("invalid_config", "createJobs needs an options object.");
|
|
83
|
+
}
|
|
84
|
+
const { db, table, schedulesTable, clock } = options;
|
|
85
|
+
if (!db || typeof db.execute !== "function") {
|
|
86
|
+
throw new GroundworkError("invalid_config", "db must be a Drizzle Postgres database.");
|
|
87
|
+
}
|
|
88
|
+
assertTableColumns(table, JOB_COLUMNS, "jobs table from groundworkTables()");
|
|
89
|
+
assertTableColumns(schedulesTable, JOB_SCHEDULE_COLUMNS, "jobSchedules table from groundworkTables()");
|
|
90
|
+
const leaseMs = parseDuration(options.lease ?? "1m", { label: "lease", minMs: 1_000 });
|
|
91
|
+
const workerId = options.workerId ?? `${hostname()}:${process.pid}:${randomBytes(3).toString("hex")}`;
|
|
92
|
+
if (typeof workerId !== "string" || workerId === "") {
|
|
93
|
+
throw new GroundworkError("invalid_config", "workerId must be a non-empty string.");
|
|
94
|
+
}
|
|
95
|
+
const random = options.random ?? Math.random;
|
|
96
|
+
const logger = options.logger ?? consoleLogger;
|
|
97
|
+
const once = createOnceLogger(logger);
|
|
98
|
+
const handlers = new Map();
|
|
99
|
+
const schedules = new Map();
|
|
100
|
+
let schedulesSynced = false;
|
|
101
|
+
/** The time a statement works with: the injected clock, else Postgres's `now()`. */
|
|
102
|
+
const now = () => (clock ? sql `${clock.now().toISOString()}::timestamptz` : sql `now()`);
|
|
103
|
+
const lease = sql `${leaseMs}::float8 * interval '1 millisecond'`;
|
|
104
|
+
function addHandler(type, definition, defaults, schedule) {
|
|
105
|
+
if (handlers.has(type)) {
|
|
106
|
+
throw new GroundworkError("invalid_config", `Job type "${type}" is already defined; define each type once.`);
|
|
107
|
+
}
|
|
108
|
+
if (typeof definition.run !== "function") {
|
|
109
|
+
throw new GroundworkError("invalid_config", `Job type "${type}" needs a run function.`);
|
|
110
|
+
}
|
|
111
|
+
const schema = definition.schema;
|
|
112
|
+
if (schema !== undefined && typeof schema?.["~standard"]?.validate !== "function") {
|
|
113
|
+
throw new GroundworkError("invalid_config", `The schema of job type "${type}" isn't a Standard Schema (zod, valibot, arktype…).`);
|
|
114
|
+
}
|
|
115
|
+
if (definition.onExhausted !== undefined && typeof definition.onExhausted !== "function") {
|
|
116
|
+
throw new GroundworkError("invalid_config", `onExhausted of job type "${type}" must be a function.`);
|
|
117
|
+
}
|
|
118
|
+
const backoff = (definition.backoff ?? {});
|
|
119
|
+
const timeout = definition.timeout === undefined ? defaults.timeout : definition.timeout;
|
|
120
|
+
const handler = {
|
|
121
|
+
type,
|
|
122
|
+
schema,
|
|
123
|
+
run: definition.run,
|
|
124
|
+
onExhausted: definition.onExhausted,
|
|
125
|
+
maxAttempts: definition.maxAttempts === undefined
|
|
126
|
+
? defaults.maxAttempts
|
|
127
|
+
: positiveInt(definition.maxAttempts, `maxAttempts of "${type}"`, "invalid_config"),
|
|
128
|
+
backoffBaseMs: parseDuration((backoff.base ?? defaults.base), {
|
|
129
|
+
label: `backoff.base of "${type}"`,
|
|
130
|
+
}),
|
|
131
|
+
backoffMaxMs: parseDuration((backoff.max ?? defaults.max), {
|
|
132
|
+
label: `backoff.max of "${type}"`,
|
|
133
|
+
}),
|
|
134
|
+
timeoutMs: timeout === false
|
|
135
|
+
? null
|
|
136
|
+
: parseDuration(timeout, { label: `timeout of "${type}"`, minMs: 1 }),
|
|
137
|
+
priority: definition.priority === undefined
|
|
138
|
+
? 0
|
|
139
|
+
: integer(definition.priority, `priority of "${type}"`, "invalid_config"),
|
|
140
|
+
schedule,
|
|
141
|
+
};
|
|
142
|
+
handlers.set(type, handler);
|
|
143
|
+
return handler;
|
|
144
|
+
}
|
|
145
|
+
async function payloadFor(handler, payload) {
|
|
146
|
+
if (handler.schema) {
|
|
147
|
+
const checked = await validateWith(handler.schema, payload);
|
|
148
|
+
if (!checked.ok) {
|
|
149
|
+
throw new GroundworkError("invalid_argument", `Invalid payload for job type "${handler.type}": ${checked.message}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return toJsonValue(payload);
|
|
153
|
+
}
|
|
154
|
+
async function enqueue(handler, payload, enqueueOptions = {}) {
|
|
155
|
+
const json = await payloadFor(handler, payload);
|
|
156
|
+
const priority = enqueueOptions.priority === undefined
|
|
157
|
+
? handler.priority
|
|
158
|
+
: integer(enqueueOptions.priority, "priority", "invalid_argument");
|
|
159
|
+
const maxAttempts = enqueueOptions.maxAttempts === undefined
|
|
160
|
+
? handler.maxAttempts
|
|
161
|
+
: positiveInt(enqueueOptions.maxAttempts, "maxAttempts", "invalid_argument");
|
|
162
|
+
const dedupeKey = enqueueOptions.dedupeKey ?? null;
|
|
163
|
+
if (dedupeKey !== null &&
|
|
164
|
+
(typeof dedupeKey !== "string" || dedupeKey === "" || dedupeKey.length > 500)) {
|
|
165
|
+
throw new GroundworkError("invalid_argument", "dedupeKey must be a non-empty string of at most 500 characters.");
|
|
166
|
+
}
|
|
167
|
+
if (enqueueOptions.runAt !== undefined && enqueueOptions.delay !== undefined) {
|
|
168
|
+
throw new GroundworkError("invalid_argument", "Pass runAt or delay, not both.");
|
|
169
|
+
}
|
|
170
|
+
let runAt = sql `input.now`;
|
|
171
|
+
if (enqueueOptions.runAt !== undefined) {
|
|
172
|
+
if (!(enqueueOptions.runAt instanceof Date) || Number.isNaN(enqueueOptions.runAt.getTime())) {
|
|
173
|
+
throw new GroundworkError("invalid_argument", "runAt must be a valid Date.");
|
|
174
|
+
}
|
|
175
|
+
runAt = sql `${enqueueOptions.runAt.toISOString()}::timestamptz`;
|
|
176
|
+
}
|
|
177
|
+
else if (enqueueOptions.delay !== undefined) {
|
|
178
|
+
const delayMs = parseDuration(enqueueOptions.delay, { label: "delay" });
|
|
179
|
+
runAt = sql `input.now + ${delayMs}::float8 * interval '1 millisecond'`;
|
|
180
|
+
}
|
|
181
|
+
const target = enqueueOptions.tx ?? db;
|
|
182
|
+
const rows = rowsOf(await target.execute(sql `
|
|
183
|
+
with input as materialized (select ${now()} as now),
|
|
184
|
+
inserted as (
|
|
185
|
+
insert into ${table} as j (type, payload, priority, max_attempts, run_at, dedupe_key, created_at, updated_at)
|
|
186
|
+
select ${handler.type}::text, ${JSON.stringify(json)}::jsonb, ${priority}::int, ${maxAttempts}::int,
|
|
187
|
+
${runAt}, ${dedupeKey}::text, input.now, input.now
|
|
188
|
+
from input
|
|
189
|
+
on conflict (type, dedupe_key) where dedupe_key is not null and status in ('pending', 'running') do nothing
|
|
190
|
+
returning j.id::text as id
|
|
191
|
+
)
|
|
192
|
+
select id, true as created from inserted
|
|
193
|
+
union all
|
|
194
|
+
select j.id::text, false from ${table} j
|
|
195
|
+
where ${dedupeKey}::text is not null and j.type = ${handler.type}::text and j.dedupe_key = ${dedupeKey}::text
|
|
196
|
+
and j.status in ('pending', 'running') and not exists (select 1 from inserted)
|
|
197
|
+
limit 1`));
|
|
198
|
+
const row = rows[0];
|
|
199
|
+
if (row)
|
|
200
|
+
return { id: row.id, created: row.created === true };
|
|
201
|
+
// The duplicate committed after this statement's snapshot was taken: look it up again.
|
|
202
|
+
const [existing] = rowsOf(await target.execute(sql `select id::text as id from ${table} where type = ${handler.type}::text and dedupe_key = ${dedupeKey}::text and status in ('pending', 'running') limit 1`));
|
|
203
|
+
if (!existing)
|
|
204
|
+
throw new Error("enqueue found neither a new job nor the duplicate it collided with");
|
|
205
|
+
return { id: existing.id, created: false };
|
|
206
|
+
}
|
|
207
|
+
// ── Schedules ──────────────────────────────────────────────────────────────
|
|
208
|
+
const scheduleValues = () => sql.join([...schedules.values()].map((s) => sql `(${s.name}::text, ${s.every}::text, ${s.everyMs}::float8, ${s.maxAttempts}::int)`), sql `, `);
|
|
209
|
+
async function syncSchedules() {
|
|
210
|
+
if (schedulesSynced || schedules.size === 0)
|
|
211
|
+
return;
|
|
212
|
+
// New schedules are due at once; existing ones keep their next run.
|
|
213
|
+
await db.execute(sql `
|
|
214
|
+
insert into ${schedulesTable} (name, every, next_run_at, created_at, updated_at)
|
|
215
|
+
select v.name, v.every, ${now()}, ${now()}, ${now()}
|
|
216
|
+
from (values ${scheduleValues()}) as v(name, every, every_ms, max_attempts)
|
|
217
|
+
on conflict (name) do update set every = excluded.every, updated_at = excluded.updated_at
|
|
218
|
+
where ${schedulesTable}.every is distinct from excluded.every`);
|
|
219
|
+
schedulesSynced = true;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* One statement per tick: move each due schedule's next run forward (a conditional update, so
|
|
223
|
+
* of several instances only one wins) and enqueue its job. The job's dedupe key skips a tick
|
|
224
|
+
* while the previous one is still pending or running.
|
|
225
|
+
*/
|
|
226
|
+
async function tickSchedules() {
|
|
227
|
+
if (schedules.size === 0)
|
|
228
|
+
return 0;
|
|
229
|
+
await syncSchedules();
|
|
230
|
+
const [row] = rowsOf(await db.execute(sql `
|
|
231
|
+
with input as materialized (select ${now()} as now),
|
|
232
|
+
v (name, every, every_ms, max_attempts) as (values ${scheduleValues()}),
|
|
233
|
+
due as (
|
|
234
|
+
update ${schedulesTable} as s
|
|
235
|
+
set next_run_at = input.now + v.every_ms * interval '1 millisecond', last_run_at = input.now, updated_at = input.now
|
|
236
|
+
from input, v
|
|
237
|
+
where s.name = v.name and s.next_run_at <= input.now
|
|
238
|
+
returning s.name, v.max_attempts
|
|
239
|
+
),
|
|
240
|
+
enqueued as (
|
|
241
|
+
insert into ${table} (type, payload, max_attempts, run_at, dedupe_key, created_at, updated_at)
|
|
242
|
+
select ${SCHEDULE_PREFIX} || due.name,
|
|
243
|
+
jsonb_build_object('scheduledAt', to_char(input.now at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')),
|
|
244
|
+
due.max_attempts, input.now, 'tick', input.now, input.now
|
|
245
|
+
from due, input
|
|
246
|
+
on conflict (type, dedupe_key) where dedupe_key is not null and status in ('pending', 'running') do nothing
|
|
247
|
+
returning 1
|
|
248
|
+
)
|
|
249
|
+
select (select count(*) from enqueued)::int as enqueued`));
|
|
250
|
+
return row ? toNumber(row.enqueued) : 0;
|
|
251
|
+
}
|
|
252
|
+
// ── Running jobs ───────────────────────────────────────────────────────────
|
|
253
|
+
async function claim(limit) {
|
|
254
|
+
const types = [...handlers.keys()];
|
|
255
|
+
if (types.length === 0 || limit < 1)
|
|
256
|
+
return [];
|
|
257
|
+
const rows = rowsOf(await db.execute(sql `
|
|
258
|
+
with input as materialized (select ${now()} as now),
|
|
259
|
+
candidates as (
|
|
260
|
+
select c.id from ${table} c, input
|
|
261
|
+
where c.status in ('pending', 'running') and c.run_at <= input.now
|
|
262
|
+
and c.type in (${sql.join(types.map((type) => sql `${type}::text`), sql `, `)})
|
|
263
|
+
order by c.priority desc nulls last, c.run_at, c.id
|
|
264
|
+
limit ${limit}
|
|
265
|
+
for update of c skip locked
|
|
266
|
+
)
|
|
267
|
+
update ${table} as j
|
|
268
|
+
set status = 'running', attempts = j.attempts + 1, locked_by = ${workerId}::text,
|
|
269
|
+
locked_until = input.now + ${lease}, run_at = input.now + ${lease},
|
|
270
|
+
started_at = coalesce(j.started_at, input.now), updated_at = input.now
|
|
271
|
+
from candidates, input
|
|
272
|
+
where j.id = candidates.id
|
|
273
|
+
returning ${RECORD} as record`));
|
|
274
|
+
return rows.map((row) => JSON.parse(row.record));
|
|
275
|
+
}
|
|
276
|
+
/** Only the worker holding the latest attempt may change a running job. */
|
|
277
|
+
const owned = (job) => sql `j.id = ${job.id}::uuid and j.status = 'running' and j.locked_by = ${workerId}::text and j.attempts = ${job.attempts}::int`;
|
|
278
|
+
async function extendLease(job) {
|
|
279
|
+
const rows = rowsOf(await db.execute(sql `
|
|
280
|
+
update ${table} as j set locked_until = ${now()} + ${lease}, run_at = ${now()} + ${lease}, updated_at = ${now()}
|
|
281
|
+
where ${owned(job)} returning 1`));
|
|
282
|
+
return rows.length > 0;
|
|
283
|
+
}
|
|
284
|
+
async function complete(job, handler, result) {
|
|
285
|
+
const scheduleUpdate = handler.schedule
|
|
286
|
+
? sql `, touched as (
|
|
287
|
+
update ${schedulesTable} set last_success_at = ${now()}, last_error = null, updated_at = ${now()}
|
|
288
|
+
where name = ${handler.schedule}::text and exists (select 1 from done))`
|
|
289
|
+
: sql ``;
|
|
290
|
+
const [row] = rowsOf(await db.execute(sql `
|
|
291
|
+
with done as (
|
|
292
|
+
update ${table} as j set status = 'completed', completed_at = ${now()}, result = ${JSON.stringify(toJsonValue(result))}::jsonb,
|
|
293
|
+
last_error = null, locked_by = null, locked_until = null, updated_at = ${now()}
|
|
294
|
+
where ${owned(job)} returning 1
|
|
295
|
+
)${scheduleUpdate}
|
|
296
|
+
select count(*)::int as done from done`));
|
|
297
|
+
return row !== undefined && toNumber(row.done) === 1;
|
|
298
|
+
}
|
|
299
|
+
async function fail(job, handler, error, permanent) {
|
|
300
|
+
const { name, message } = errorText(error);
|
|
301
|
+
const lastError = `${name}: ${message}`.slice(0, MAX_ERROR_LENGTH);
|
|
302
|
+
const exhausted = permanent || job.attempts >= job.max_attempts;
|
|
303
|
+
const delayMs = exhausted
|
|
304
|
+
? 0
|
|
305
|
+
: backoffDelayMs(job.attempts, handler.backoffBaseMs, handler.backoffMaxMs, random);
|
|
306
|
+
const scheduleUpdate = handler.schedule
|
|
307
|
+
? sql `, touched as (
|
|
308
|
+
update ${schedulesTable} set last_failure_at = ${now()}, last_error = ${lastError}::text, updated_at = ${now()}
|
|
309
|
+
where name = ${handler.schedule}::text and exists (select 1 from done))`
|
|
310
|
+
: sql ``;
|
|
311
|
+
const [row] = rowsOf(await db.execute(sql `
|
|
312
|
+
with done as (
|
|
313
|
+
update ${table} as j set
|
|
314
|
+
status = ${exhausted ? "failed" : "pending"}::text,
|
|
315
|
+
run_at = ${exhausted ? sql `j.run_at` : sql `${now()} + ${delayMs}::float8 * interval '1 millisecond'`},
|
|
316
|
+
completed_at = ${exhausted ? now() : sql `null`},
|
|
317
|
+
last_error = ${lastError}::text, locked_by = null, locked_until = null, updated_at = ${now()}
|
|
318
|
+
where ${owned(job)} returning 1
|
|
319
|
+
)${scheduleUpdate}
|
|
320
|
+
select count(*)::int as done from done`));
|
|
321
|
+
if (!row || toNumber(row.done) !== 1)
|
|
322
|
+
return "lost";
|
|
323
|
+
const context = { type: job.type, id: job.id, attempt: job.attempts, error: { name, message } };
|
|
324
|
+
if (exhausted) {
|
|
325
|
+
logger.error(`Job "${job.type}" failed for good after ${job.attempts} attempt(s).`, context);
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
logger.warn(`Job "${job.type}" failed; retrying in ${Math.ceil(delayMs / 1000)}s.`, context);
|
|
329
|
+
}
|
|
330
|
+
return exhausted ? "failed" : "retried";
|
|
331
|
+
}
|
|
332
|
+
async function execute(job, counters) {
|
|
333
|
+
const handler = handlers.get(job.type);
|
|
334
|
+
if (!handler)
|
|
335
|
+
return; // claim only selects known types
|
|
336
|
+
const controller = new AbortController();
|
|
337
|
+
const context = {
|
|
338
|
+
id: job.id,
|
|
339
|
+
type: job.type,
|
|
340
|
+
attempt: job.attempts,
|
|
341
|
+
maxAttempts: job.max_attempts,
|
|
342
|
+
signal: controller.signal,
|
|
343
|
+
createdAt: new Date(job.created_at),
|
|
344
|
+
...(handler.schedule
|
|
345
|
+
? {
|
|
346
|
+
scheduledAt: new Date(String(job.payload?.scheduledAt ?? job.created_at)),
|
|
347
|
+
}
|
|
348
|
+
: {}),
|
|
349
|
+
};
|
|
350
|
+
const record = (outcome) => {
|
|
351
|
+
if (outcome === "lost") {
|
|
352
|
+
logger.warn(`Job "${job.type}" finished after this worker lost its lease; another worker owns it now.`, {
|
|
353
|
+
type: job.type,
|
|
354
|
+
id: job.id,
|
|
355
|
+
attempt: job.attempts,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
else
|
|
359
|
+
counters[outcome]++;
|
|
360
|
+
};
|
|
361
|
+
const runExhausted = async (payload, error) => {
|
|
362
|
+
if (!handler.onExhausted)
|
|
363
|
+
return;
|
|
364
|
+
try {
|
|
365
|
+
await handler.onExhausted(payload, { ...errorText(error), attempt: job.attempts }, context);
|
|
366
|
+
}
|
|
367
|
+
catch (hookError) {
|
|
368
|
+
logger.error(`onExhausted of job "${job.type}" threw.`, {
|
|
369
|
+
id: job.id,
|
|
370
|
+
error: errorText(hookError),
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
// Its worker stopped during the last attempt (the lease ran out): that attempt counts.
|
|
375
|
+
if (job.attempts > job.max_attempts) {
|
|
376
|
+
const error = new Error("The worker running the last attempt stopped before finishing.");
|
|
377
|
+
record(await fail(job, handler, error, true));
|
|
378
|
+
await runExhausted(job.payload, error);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
let payload = job.payload;
|
|
382
|
+
if (handler.schema) {
|
|
383
|
+
const checked = await validateWith(handler.schema, job.payload);
|
|
384
|
+
if (!checked.ok) {
|
|
385
|
+
// A payload that doesn't validate never will: fail now instead of retrying.
|
|
386
|
+
const error = new GroundworkError("invalid_argument", `Invalid payload: ${checked.message}`);
|
|
387
|
+
record(await fail(job, handler, error, true));
|
|
388
|
+
await runExhausted(job.payload, error);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
payload = checked.value;
|
|
392
|
+
}
|
|
393
|
+
const timer = handler.timeoutMs === null
|
|
394
|
+
? undefined
|
|
395
|
+
: setTimeout(() => {
|
|
396
|
+
const error = new Error(`Timed out after ${handler.timeoutMs}ms.`);
|
|
397
|
+
error.name = "TimeoutError";
|
|
398
|
+
controller.abort(error);
|
|
399
|
+
}, handler.timeoutMs);
|
|
400
|
+
const heartbeat = setInterval(() => {
|
|
401
|
+
extendLease(job)
|
|
402
|
+
.then((kept) => {
|
|
403
|
+
if (!kept && !controller.signal.aborted) {
|
|
404
|
+
const error = new Error("This worker lost the job's lease.");
|
|
405
|
+
error.name = "LeaseLostError";
|
|
406
|
+
controller.abort(error);
|
|
407
|
+
}
|
|
408
|
+
})
|
|
409
|
+
.catch((error) => {
|
|
410
|
+
once.once("warn", "heartbeat", "Could not renew a job lease; retrying.", {
|
|
411
|
+
error: errorText(error),
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
}, Math.max(1_000, Math.floor(leaseMs / 3)));
|
|
415
|
+
try {
|
|
416
|
+
const running = Promise.resolve().then(() => handler.run(payload, context));
|
|
417
|
+
// A handler that ignores the signal keeps running, but its outcome no longer counts.
|
|
418
|
+
running.catch(() => { });
|
|
419
|
+
const aborted = new Promise((_, reject) => {
|
|
420
|
+
if (controller.signal.aborted)
|
|
421
|
+
reject(controller.signal.reason);
|
|
422
|
+
controller.signal.addEventListener("abort", () => reject(controller.signal.reason), {
|
|
423
|
+
once: true,
|
|
424
|
+
});
|
|
425
|
+
});
|
|
426
|
+
aborted.catch(() => { });
|
|
427
|
+
const result = await Promise.race([running, aborted]);
|
|
428
|
+
if (await complete(job, handler, result))
|
|
429
|
+
counters.completed++;
|
|
430
|
+
else
|
|
431
|
+
record("lost");
|
|
432
|
+
}
|
|
433
|
+
catch (error) {
|
|
434
|
+
const outcome = await fail(job, handler, error, false);
|
|
435
|
+
record(outcome);
|
|
436
|
+
if (outcome === "failed")
|
|
437
|
+
await runExhausted(payload, error);
|
|
438
|
+
}
|
|
439
|
+
finally {
|
|
440
|
+
clearTimeout(timer);
|
|
441
|
+
clearInterval(heartbeat);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
async function loop(settings) {
|
|
445
|
+
const started = performance.now();
|
|
446
|
+
const counters = { claimed: 0, completed: 0, retried: 0, failed: 0, scheduled: 0 };
|
|
447
|
+
const inFlight = new Set();
|
|
448
|
+
const stopping = () => settings.signal?.aborted === true ||
|
|
449
|
+
(settings.deadline !== null && performance.now() >= settings.deadline);
|
|
450
|
+
let lastTick = Number.NEGATIVE_INFINITY;
|
|
451
|
+
const wait = (msToWait) => new Promise((resolve) => {
|
|
452
|
+
const timer = setTimeout(done, msToWait);
|
|
453
|
+
settings.signal?.addEventListener("abort", done, { once: true });
|
|
454
|
+
for (const promise of inFlight)
|
|
455
|
+
promise.then(done, done);
|
|
456
|
+
function done() {
|
|
457
|
+
clearTimeout(timer);
|
|
458
|
+
resolve();
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
try {
|
|
462
|
+
while (!stopping()) {
|
|
463
|
+
try {
|
|
464
|
+
if (performance.now() - lastTick >= settings.pollMs) {
|
|
465
|
+
lastTick = performance.now();
|
|
466
|
+
counters.scheduled += await tickSchedules();
|
|
467
|
+
}
|
|
468
|
+
const free = settings.concurrency - inFlight.size;
|
|
469
|
+
const claimed = free > 0 ? await claim(free) : [];
|
|
470
|
+
if (claimed.length > 0)
|
|
471
|
+
once.reset("claim");
|
|
472
|
+
counters.claimed += claimed.length;
|
|
473
|
+
for (const job of claimed) {
|
|
474
|
+
const promise = execute(job, counters).finally(() => inFlight.delete(promise));
|
|
475
|
+
inFlight.add(promise);
|
|
476
|
+
}
|
|
477
|
+
if (inFlight.size >= settings.concurrency) {
|
|
478
|
+
await Promise.race(inFlight);
|
|
479
|
+
}
|
|
480
|
+
else if (claimed.length < free) {
|
|
481
|
+
// Nothing more is due right now.
|
|
482
|
+
if (settings.mode === "once") {
|
|
483
|
+
if (inFlight.size === 0)
|
|
484
|
+
break;
|
|
485
|
+
await Promise.race(inFlight); // a finishing job may have enqueued another
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
await wait(settings.pollMs);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
catch (error) {
|
|
493
|
+
if (settings.mode === "once")
|
|
494
|
+
throw error;
|
|
495
|
+
once.once("error", "claim", "The job worker could not reach the database; it keeps retrying.", {
|
|
496
|
+
error: errorText(error),
|
|
497
|
+
});
|
|
498
|
+
await wait(settings.pollMs);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
finally {
|
|
503
|
+
await Promise.allSettled([...inFlight]);
|
|
504
|
+
}
|
|
505
|
+
return { ...counters, durationMs: Math.round(performance.now() - started) };
|
|
506
|
+
}
|
|
507
|
+
const validConcurrency = (value) => value === undefined ? 4 : positiveInt(value, "concurrency", "invalid_argument");
|
|
508
|
+
const validId = (id) => typeof id === "string" &&
|
|
509
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
|
|
510
|
+
const jobs = {
|
|
511
|
+
define(type, definition) {
|
|
512
|
+
validateName(type, "job type");
|
|
513
|
+
if (type.startsWith(SCHEDULE_PREFIX)) {
|
|
514
|
+
throw new GroundworkError("invalid_config", `Job types can't start with "${SCHEDULE_PREFIX}"; that prefix is for schedules.`);
|
|
515
|
+
}
|
|
516
|
+
if (typeof definition !== "object" || definition === null) {
|
|
517
|
+
throw new GroundworkError("invalid_config", `Job type "${type}" needs a definition object.`);
|
|
518
|
+
}
|
|
519
|
+
const handler = addHandler(type, definition, {
|
|
520
|
+
maxAttempts: 5,
|
|
521
|
+
base: "30s",
|
|
522
|
+
max: "1h",
|
|
523
|
+
timeout: "5m",
|
|
524
|
+
});
|
|
525
|
+
return {
|
|
526
|
+
type,
|
|
527
|
+
enqueue: (payload, enqueueOptions) => enqueue(handler, payload, enqueueOptions),
|
|
528
|
+
};
|
|
529
|
+
},
|
|
530
|
+
schedule(name, scheduleOptions, run) {
|
|
531
|
+
validateName(name, "schedule name");
|
|
532
|
+
if (schedules.has(name)) {
|
|
533
|
+
throw new GroundworkError("invalid_config", `Schedule "${name}" is already defined.`);
|
|
534
|
+
}
|
|
535
|
+
if (typeof scheduleOptions !== "object" ||
|
|
536
|
+
scheduleOptions === null ||
|
|
537
|
+
!isDuration(scheduleOptions.every)) {
|
|
538
|
+
throw new GroundworkError("invalid_config", `Schedule "${name}" needs { every }, such as "1h".`);
|
|
539
|
+
}
|
|
540
|
+
const everyMs = parseDuration(scheduleOptions.every, {
|
|
541
|
+
label: `every of schedule "${name}"`,
|
|
542
|
+
minMs: 1_000,
|
|
543
|
+
});
|
|
544
|
+
const handler = addHandler(`${SCHEDULE_PREFIX}${name}`, {
|
|
545
|
+
...scheduleOptions,
|
|
546
|
+
run: (_payload, context) => run(context),
|
|
547
|
+
}, { maxAttempts: 3, base: "5s", max: "1m", timeout: "5m" }, name);
|
|
548
|
+
schedules.set(name, {
|
|
549
|
+
name,
|
|
550
|
+
every: scheduleOptions.every,
|
|
551
|
+
everyMs,
|
|
552
|
+
maxAttempts: handler.maxAttempts,
|
|
553
|
+
});
|
|
554
|
+
schedulesSynced = false;
|
|
555
|
+
},
|
|
556
|
+
async trigger(name) {
|
|
557
|
+
if (!schedules.has(name))
|
|
558
|
+
return false;
|
|
559
|
+
await syncSchedules();
|
|
560
|
+
const rows = rowsOf(await db.execute(sql `update ${schedulesTable} set next_run_at = ${now()}, updated_at = ${now()} where name = ${name}::text returning 1`));
|
|
561
|
+
return rows.length > 0;
|
|
562
|
+
},
|
|
563
|
+
runOnce(runOptions = {}) {
|
|
564
|
+
const budgetMs = runOptions.budgetMs ?? 10_000;
|
|
565
|
+
if (typeof budgetMs !== "number" || !Number.isFinite(budgetMs) || budgetMs <= 0) {
|
|
566
|
+
throw new GroundworkError("invalid_argument", "budgetMs must be a positive number of milliseconds.");
|
|
567
|
+
}
|
|
568
|
+
return loop({
|
|
569
|
+
concurrency: validConcurrency(runOptions.concurrency),
|
|
570
|
+
deadline: performance.now() + budgetMs,
|
|
571
|
+
signal: undefined,
|
|
572
|
+
pollMs: 0,
|
|
573
|
+
mode: "once",
|
|
574
|
+
});
|
|
575
|
+
},
|
|
576
|
+
work(workOptions = {}) {
|
|
577
|
+
return loop({
|
|
578
|
+
concurrency: validConcurrency(workOptions.concurrency),
|
|
579
|
+
deadline: null,
|
|
580
|
+
signal: workOptions.signal,
|
|
581
|
+
pollMs: parseDuration(workOptions.pollInterval ?? "1s", {
|
|
582
|
+
label: "pollInterval",
|
|
583
|
+
minMs: 10,
|
|
584
|
+
}),
|
|
585
|
+
mode: "work",
|
|
586
|
+
});
|
|
587
|
+
},
|
|
588
|
+
async get(id) {
|
|
589
|
+
if (!validId(id))
|
|
590
|
+
return null;
|
|
591
|
+
const [row] = rowsOf(await db.execute(sql `select ${RECORD} as record from ${table} j where j.id = ${id}::uuid`));
|
|
592
|
+
return row ? toRecord(JSON.parse(row.record)) : null;
|
|
593
|
+
},
|
|
594
|
+
async list(filter = {}) {
|
|
595
|
+
const limit = filter.limit ?? 100;
|
|
596
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIST) {
|
|
597
|
+
throw new GroundworkError("invalid_argument", `limit must be an integer from 1 to ${MAX_LIST}.`);
|
|
598
|
+
}
|
|
599
|
+
const conditions = [];
|
|
600
|
+
const listOf = (value) => (Array.isArray(value) ? value : [value]);
|
|
601
|
+
const inList = (column, values) => values.length === 0
|
|
602
|
+
? sql `false`
|
|
603
|
+
: sql `${sql.raw(column)} in (${sql.join(values.map((v) => sql `${v}::text`), sql `, `)})`;
|
|
604
|
+
if (filter.type !== undefined)
|
|
605
|
+
conditions.push(inList("j.type", listOf(filter.type)));
|
|
606
|
+
if (filter.schedule !== undefined) {
|
|
607
|
+
const names = listOf(filter.schedule).map((name) => `${SCHEDULE_PREFIX}${name}`);
|
|
608
|
+
conditions.push(inList("j.type", names));
|
|
609
|
+
}
|
|
610
|
+
if (filter.status !== undefined)
|
|
611
|
+
conditions.push(inList("j.status", listOf(filter.status)));
|
|
612
|
+
if (filter.since !== undefined) {
|
|
613
|
+
if (!(filter.since instanceof Date) || Number.isNaN(filter.since.getTime())) {
|
|
614
|
+
throw new GroundworkError("invalid_argument", "since must be a valid Date.");
|
|
615
|
+
}
|
|
616
|
+
conditions.push(sql `j.created_at >= ${filter.since.toISOString()}::timestamptz`);
|
|
617
|
+
}
|
|
618
|
+
const where = conditions.length === 0 ? sql `` : sql `where ${sql.join(conditions, sql ` and `)}`;
|
|
619
|
+
const rows = rowsOf(await db.execute(sql `select ${RECORD} as record from ${table} j ${where} order by j.created_at desc, j.id desc limit ${limit}`));
|
|
620
|
+
return rows.map((row) => toRecord(JSON.parse(row.record)));
|
|
621
|
+
},
|
|
622
|
+
async retry(id) {
|
|
623
|
+
if (!validId(id))
|
|
624
|
+
return false;
|
|
625
|
+
try {
|
|
626
|
+
const rows = rowsOf(await db.execute(sql `
|
|
627
|
+
update ${table} set status = 'pending', attempts = 0, run_at = ${now()}, completed_at = null,
|
|
628
|
+
locked_by = null, locked_until = null, updated_at = ${now()}
|
|
629
|
+
where id = ${id}::uuid and status in ('failed', 'cancelled') returning 1`));
|
|
630
|
+
return rows.length > 0;
|
|
631
|
+
}
|
|
632
|
+
catch (error) {
|
|
633
|
+
// Another job with the same dedupe key is already pending or running.
|
|
634
|
+
const code = error?.code ??
|
|
635
|
+
error?.cause?.code;
|
|
636
|
+
if (code === "23505")
|
|
637
|
+
return false;
|
|
638
|
+
throw error;
|
|
639
|
+
}
|
|
640
|
+
},
|
|
641
|
+
async cancel(id) {
|
|
642
|
+
if (!validId(id))
|
|
643
|
+
return false;
|
|
644
|
+
const rows = rowsOf(await db.execute(sql `
|
|
645
|
+
update ${table} set status = 'cancelled', completed_at = ${now()}, updated_at = ${now()}
|
|
646
|
+
where id = ${id}::uuid and status = 'pending' returning 1`));
|
|
647
|
+
return rows.length > 0;
|
|
648
|
+
},
|
|
649
|
+
async prune(pruneOptions) {
|
|
650
|
+
if (typeof pruneOptions !== "object" || pruneOptions === null) {
|
|
651
|
+
throw new GroundworkError("invalid_argument", 'prune needs { completedOlderThan }, such as "7d".');
|
|
652
|
+
}
|
|
653
|
+
const completedMs = parseDuration(pruneOptions.completedOlderThan, {
|
|
654
|
+
label: "completedOlderThan",
|
|
655
|
+
minMs: 1,
|
|
656
|
+
});
|
|
657
|
+
const failedMs = pruneOptions.failedOlderThan === undefined
|
|
658
|
+
? completedMs
|
|
659
|
+
: parseDuration(pruneOptions.failedOlderThan, { label: "failedOlderThan", minMs: 1 });
|
|
660
|
+
let total = 0;
|
|
661
|
+
for (;;) {
|
|
662
|
+
const [row] = rowsOf(await db.execute(sql `
|
|
663
|
+
with input as materialized (select ${now()} as now),
|
|
664
|
+
doomed as (
|
|
665
|
+
select j.id from ${table} j, input
|
|
666
|
+
where (j.status in ('completed', 'cancelled') and j.completed_at < input.now - ${completedMs}::float8 * interval '1 millisecond')
|
|
667
|
+
or (j.status = 'failed' and j.completed_at < input.now - ${failedMs}::float8 * interval '1 millisecond')
|
|
668
|
+
limit ${PRUNE_BATCH}
|
|
669
|
+
),
|
|
670
|
+
deleted as (delete from ${table} where id in (select id from doomed) returning 1)
|
|
671
|
+
select count(*)::int as deleted from deleted`));
|
|
672
|
+
const deleted = row ? toNumber(row.deleted) : 0;
|
|
673
|
+
total += deleted;
|
|
674
|
+
if (deleted < PRUNE_BATCH)
|
|
675
|
+
return total;
|
|
676
|
+
}
|
|
677
|
+
},
|
|
678
|
+
async health() {
|
|
679
|
+
await syncSchedules();
|
|
680
|
+
const typeRows = rowsOf(await db.execute(sql `
|
|
681
|
+
with input as materialized (select ${now()} as now)
|
|
682
|
+
select j.type,
|
|
683
|
+
count(*) filter (where j.status = 'pending')::int as pending,
|
|
684
|
+
count(*) filter (where j.status = 'running')::int as running,
|
|
685
|
+
count(*) filter (where j.status = 'failed' and j.completed_at > input.now - interval '24 hours')::int as failed_24h,
|
|
686
|
+
${sql.raw(ms("input.now"))} - ${sql.raw(ms("min(j.run_at) filter (where j.status = 'pending' and j.run_at <= input.now)"))} as oldest_pending_age_ms,
|
|
687
|
+
${sql.raw(ms("max(j.completed_at) filter (where j.status = 'completed')"))} as last_success
|
|
688
|
+
from ${table} j, input
|
|
689
|
+
group by j.type, input.now`));
|
|
690
|
+
const byType = new Map(typeRows.map((row) => [row.type, row]));
|
|
691
|
+
const known = [...new Set([...handlers.keys(), ...byType.keys()])].sort();
|
|
692
|
+
const types = known.map((type) => {
|
|
693
|
+
const row = byType.get(type);
|
|
694
|
+
const number = (value) => value === null || value === undefined ? 0 : toNumber(value);
|
|
695
|
+
return {
|
|
696
|
+
type,
|
|
697
|
+
pending: number(row?.pending),
|
|
698
|
+
running: number(row?.running),
|
|
699
|
+
failedLast24h: number(row?.failed_24h),
|
|
700
|
+
oldestPendingAgeMs: row?.oldest_pending_age_ms === null || row?.oldest_pending_age_ms === undefined
|
|
701
|
+
? null
|
|
702
|
+
: Math.max(0, Math.round(toNumber(row.oldest_pending_age_ms))),
|
|
703
|
+
lastSuccessAt: row?.last_success === null || row?.last_success === undefined
|
|
704
|
+
? null
|
|
705
|
+
: new Date(toNumber(row.last_success)),
|
|
706
|
+
};
|
|
707
|
+
});
|
|
708
|
+
const names = [...schedules.keys()];
|
|
709
|
+
const scheduleRows = names.length === 0
|
|
710
|
+
? []
|
|
711
|
+
: rowsOf(await db.execute(sql `
|
|
712
|
+
with input as materialized (select ${now()} as now)
|
|
713
|
+
select s.name, s.every, ${sql.raw(ms("s.next_run_at"))} as next_run_at, ${sql.raw(ms("s.last_run_at"))} as last_run_at,
|
|
714
|
+
${sql.raw(ms("s.last_success_at"))} as last_success_at, ${sql.raw(ms("s.last_failure_at"))} as last_failure_at,
|
|
715
|
+
s.last_error, ${sql.raw(ms("input.now"))} as now
|
|
716
|
+
from ${schedulesTable} s, input
|
|
717
|
+
where s.name in (${sql.join(names.map((name) => sql `${name}::text`), sql `, `)})
|
|
718
|
+
order by s.name`));
|
|
719
|
+
const optionalDate = (value) => value === null || value === undefined ? null : new Date(toNumber(value));
|
|
720
|
+
const schedulesHealth = scheduleRows.map((row) => {
|
|
721
|
+
const entry = schedules.get(row.name);
|
|
722
|
+
const lastSuccess = optionalDate(row.last_success_at);
|
|
723
|
+
return {
|
|
724
|
+
name: row.name,
|
|
725
|
+
every: (entry?.every ?? row.every),
|
|
726
|
+
nextRunAt: new Date(toNumber(row.next_run_at)),
|
|
727
|
+
lastRunAt: optionalDate(row.last_run_at),
|
|
728
|
+
lastSuccessAt: lastSuccess,
|
|
729
|
+
lastFailureAt: optionalDate(row.last_failure_at),
|
|
730
|
+
lastError: row.last_error,
|
|
731
|
+
healthy: lastSuccess !== null &&
|
|
732
|
+
entry !== undefined &&
|
|
733
|
+
toNumber(row.now) - lastSuccess.getTime() < entry.everyMs * 3,
|
|
734
|
+
};
|
|
735
|
+
});
|
|
736
|
+
return { types, schedules: schedulesHealth };
|
|
737
|
+
},
|
|
738
|
+
};
|
|
739
|
+
return jobs;
|
|
740
|
+
}
|
|
741
|
+
//# sourceMappingURL=jobs.js.map
|