@harlan-zw/nuxt-cf-jobs 0.2.2 → 0.2.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/dist/checks.d.mts +25 -0
- package/dist/checks.mjs +80 -0
- package/dist/cli/index.mjs +1 -137
- package/dist/module.d.mts +4 -0
- package/dist/module.json +1 -1
- package/dist/module.mjs +7 -0
- package/dist/shared/nuxt-cf-jobs.DtbmBVBD.mjs +139 -0
- package/package.json +15 -3
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { CheckContext, Check } from '@harlan-zw/nuxt-checkin/server';
|
|
2
|
+
|
|
3
|
+
interface QueueCheckOptions {
|
|
4
|
+
id: string;
|
|
5
|
+
d1Binding: string;
|
|
6
|
+
queue: string;
|
|
7
|
+
warnAfterSeconds: number;
|
|
8
|
+
failAfterSeconds: number;
|
|
9
|
+
failMinimumReady?: number;
|
|
10
|
+
staleAfterSeconds?: number;
|
|
11
|
+
}
|
|
12
|
+
interface QueueEvidence {
|
|
13
|
+
queue: string;
|
|
14
|
+
ready: number;
|
|
15
|
+
reserved: number;
|
|
16
|
+
delayed: number;
|
|
17
|
+
oldestDueAgeSeconds: number | null;
|
|
18
|
+
oldestReservationAgeSeconds: number | null;
|
|
19
|
+
}
|
|
20
|
+
declare function evaluateQueueCheck(evidence: QueueEvidence, options: Pick<QueueCheckOptions, 'warnAfterSeconds' | 'failAfterSeconds' | 'staleAfterSeconds' | 'failMinimumReady'>): any;
|
|
21
|
+
declare function collectQueueEvidence(context: CheckContext, binding: string): Promise<readonly QueueEvidence[] | undefined>;
|
|
22
|
+
declare function defineQueueCheck(options: QueueCheckOptions): Check;
|
|
23
|
+
|
|
24
|
+
export { collectQueueEvidence, defineQueueCheck as default, defineQueueCheck, evaluateQueueCheck };
|
|
25
|
+
export type { QueueCheckOptions, QueueEvidence };
|
package/dist/checks.mjs
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { defineCheck, unavailable, fail, warn, pass } from '@harlan-zw/nuxt-checkin/server';
|
|
2
|
+
import { resolveCloudflareBindings } from '@harlan-zw/nuxt-cloudflare/bindings';
|
|
3
|
+
import { b as backpressureSql } from './shared/nuxt-cf-jobs.DtbmBVBD.mjs';
|
|
4
|
+
|
|
5
|
+
function evaluateQueueCheck(evidence, options) {
|
|
6
|
+
if (evidence.oldestReservationAgeSeconds !== null && options.staleAfterSeconds !== void 0 && evidence.oldestReservationAgeSeconds >= options.staleAfterSeconds)
|
|
7
|
+
return fail("Queue has a stale reservation.", { ...evidence });
|
|
8
|
+
if (evidence.oldestDueAgeSeconds !== null && evidence.oldestDueAgeSeconds >= options.failAfterSeconds && evidence.ready >= (options.failMinimumReady ?? 1))
|
|
9
|
+
return fail("Due queue work exceeded its failure threshold.", { ...evidence });
|
|
10
|
+
if (evidence.oldestDueAgeSeconds !== null && evidence.oldestDueAgeSeconds >= options.warnAfterSeconds)
|
|
11
|
+
return warn("Due queue work exceeded its warning threshold.", { ...evidence });
|
|
12
|
+
return pass({ ...evidence });
|
|
13
|
+
}
|
|
14
|
+
async function collectQueueEvidence(context, binding) {
|
|
15
|
+
const env = context.event ? resolveCloudflareBindings(context.event) : void 0;
|
|
16
|
+
const db = env?.[binding];
|
|
17
|
+
if (typeof db?.prepare !== "function")
|
|
18
|
+
return void 0;
|
|
19
|
+
const prepare = db.prepare.bind(db);
|
|
20
|
+
return context.collect(db, "cf-jobs.backpressure", async () => {
|
|
21
|
+
const response = await prepare(backpressureSql(void 0, context.now.getTime() / 1e3)).all();
|
|
22
|
+
if (!response || typeof response !== "object" || !("results" in response) || !Array.isArray(response.results) || "success" in response && response.success === false)
|
|
23
|
+
throw new Error("Queue query returned invalid data.");
|
|
24
|
+
const rows = response.results.map((raw) => parseQueueEvidence(raw, context.now.getTime() / 1e3));
|
|
25
|
+
if (new Set(rows.map((row) => row.queue)).size !== rows.length)
|
|
26
|
+
throw new Error("Queue query returned duplicate queues.");
|
|
27
|
+
const meta = "meta" in response ? response.meta : void 0;
|
|
28
|
+
return { value: rows, metrics: { requests: 1, ...meta?.rows_read === void 0 ? {} : { rowsRead: meta.rows_read } } };
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function parseQueueEvidence(raw, nowSeconds) {
|
|
32
|
+
if (!raw || typeof raw !== "object" || !("queue" in raw) || typeof raw.queue !== "string" || !raw.queue.trim())
|
|
33
|
+
throw new Error("Queue query returned an invalid queue.");
|
|
34
|
+
const row = raw;
|
|
35
|
+
const count = (key) => {
|
|
36
|
+
const value = row[key];
|
|
37
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
|
|
38
|
+
throw new Error("Queue count is invalid.");
|
|
39
|
+
return value;
|
|
40
|
+
};
|
|
41
|
+
const age = (key) => {
|
|
42
|
+
const value = row[key];
|
|
43
|
+
if (value === null)
|
|
44
|
+
return null;
|
|
45
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
46
|
+
throw new Error("Queue timestamp is invalid.");
|
|
47
|
+
return Math.max(0, nowSeconds - value);
|
|
48
|
+
};
|
|
49
|
+
const ready = count("ready");
|
|
50
|
+
const reserved = count("reserved");
|
|
51
|
+
const oldestDueAgeSeconds = age("oldest_available_at");
|
|
52
|
+
const oldestReservationAgeSeconds = age("oldest_reserved_at");
|
|
53
|
+
if (ready > 0 !== (oldestDueAgeSeconds !== null) || reserved > 0 !== (oldestReservationAgeSeconds !== null))
|
|
54
|
+
throw new Error("Queue counts and timestamps disagree.");
|
|
55
|
+
return { queue: raw.queue, ready, reserved, delayed: count("delayed"), oldestDueAgeSeconds, oldestReservationAgeSeconds };
|
|
56
|
+
}
|
|
57
|
+
function defineQueueCheck(options) {
|
|
58
|
+
for (const value of [options.warnAfterSeconds, options.failAfterSeconds, options.staleAfterSeconds ?? 1]) {
|
|
59
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
60
|
+
throw new TypeError("Queue thresholds must be positive seconds.");
|
|
61
|
+
}
|
|
62
|
+
if (options.failMinimumReady !== void 0 && (!Number.isSafeInteger(options.failMinimumReady) || options.failMinimumReady < 1))
|
|
63
|
+
throw new TypeError("Queue failure volume must be a positive integer.");
|
|
64
|
+
if (options.warnAfterSeconds > options.failAfterSeconds)
|
|
65
|
+
throw new TypeError("Queue warning threshold must not exceed its failure threshold.");
|
|
66
|
+
if (!options.queue?.trim() || !options.d1Binding?.trim())
|
|
67
|
+
throw new TypeError("Queue check requires a queue and D1 binding.");
|
|
68
|
+
return defineCheck({
|
|
69
|
+
id: options.id,
|
|
70
|
+
async run(context) {
|
|
71
|
+
const rows = await collectQueueEvidence(context, options.d1Binding);
|
|
72
|
+
if (!rows)
|
|
73
|
+
return unavailable("Queue D1 binding is unavailable.");
|
|
74
|
+
const evidence = rows.find((row) => row.queue === options.queue) ?? { queue: options.queue, ready: 0, reserved: 0, delayed: 0, oldestDueAgeSeconds: null, oldestReservationAgeSeconds: null };
|
|
75
|
+
return evaluateQueueCheck(evidence, options);
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export { collectQueueEvidence, defineQueueCheck as default, defineQueueCheck, evaluateQueueCheck };
|
package/dist/cli/index.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import { recentTerminalJobs, snapshotDurableQueues } from '../../dist/runtime/se
|
|
|
12
12
|
import { p as parseWranglerConfig, c as collectTasks } from '../shared/nuxt-cf-jobs.ywg3JBoP.mjs';
|
|
13
13
|
import { execFile } from 'node:child_process';
|
|
14
14
|
import { promisify } from 'node:util';
|
|
15
|
+
import { d as defaultTableNames, b as backpressureSql, f as failedCountSql, s as staleReservedSql, a as summarizeBackpressure, c as activeJobsSql, e as failedJobsSql, r as retrySql, g as forgetSql, h as flushSql, i as clearSql, p as pruneSql } from '../shared/nuxt-cf-jobs.DtbmBVBD.mjs';
|
|
15
16
|
import 'node:fs/promises';
|
|
16
17
|
import '@nuxt/kit';
|
|
17
18
|
import 'vite';
|
|
@@ -111,143 +112,6 @@ async function execD1Batch(target, sqls) {
|
|
|
111
112
|
return sqls.map((_, i) => entries[i]?.results ?? []);
|
|
112
113
|
}
|
|
113
114
|
|
|
114
|
-
const defaultTableNames = {
|
|
115
|
-
jobs: "jobs",
|
|
116
|
-
failed: "failed_jobs",
|
|
117
|
-
batches: "job_batches"
|
|
118
|
-
};
|
|
119
|
-
function sqlString(value) {
|
|
120
|
-
return `'${value.replace(/'/g, "''")}'`;
|
|
121
|
-
}
|
|
122
|
-
function sqlInt(value) {
|
|
123
|
-
if (!Number.isFinite(value))
|
|
124
|
-
throw new TypeError(`Expected a finite number, got ${value}`);
|
|
125
|
-
return Math.trunc(value);
|
|
126
|
-
}
|
|
127
|
-
const ACTIVE = "completed_at IS NULL AND failed_at IS NULL";
|
|
128
|
-
function stateClause(state) {
|
|
129
|
-
switch (state) {
|
|
130
|
-
case "ready":
|
|
131
|
-
return "reserved_at IS NULL AND available_at <= unixepoch()";
|
|
132
|
-
case "reserved":
|
|
133
|
-
return "reserved_at IS NOT NULL";
|
|
134
|
-
case "delayed":
|
|
135
|
-
return "reserved_at IS NULL AND available_at > unixepoch()";
|
|
136
|
-
case "completed":
|
|
137
|
-
return "completed_at IS NOT NULL";
|
|
138
|
-
default:
|
|
139
|
-
return "";
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
function andClauses(...clauses) {
|
|
143
|
-
const parts = clauses.filter((c) => !!c);
|
|
144
|
-
return parts.length ? `WHERE ${parts.join(" AND ")}` : "";
|
|
145
|
-
}
|
|
146
|
-
function backpressureSql(t = defaultTableNames) {
|
|
147
|
-
return `SELECT queue,
|
|
148
|
-
COUNT(*) AS total,
|
|
149
|
-
SUM(CASE WHEN reserved_at IS NULL AND available_at <= unixepoch() THEN 1 ELSE 0 END) AS ready,
|
|
150
|
-
SUM(CASE WHEN reserved_at IS NOT NULL THEN 1 ELSE 0 END) AS reserved,
|
|
151
|
-
SUM(CASE WHEN reserved_at IS NULL AND available_at > unixepoch() THEN 1 ELSE 0 END) AS delayed,
|
|
152
|
-
MIN(CASE WHEN reserved_at IS NULL AND available_at <= unixepoch() THEN available_at END) AS oldest_available_at,
|
|
153
|
-
MIN(reserved_at) AS oldest_reserved_at
|
|
154
|
-
FROM ${t.jobs}
|
|
155
|
-
WHERE ${ACTIVE}
|
|
156
|
-
GROUP BY queue
|
|
157
|
-
ORDER BY total DESC`;
|
|
158
|
-
}
|
|
159
|
-
function failedCountSql(t = defaultTableNames) {
|
|
160
|
-
return `SELECT queue, COUNT(*) AS total FROM ${t.failed} GROUP BY queue ORDER BY total DESC`;
|
|
161
|
-
}
|
|
162
|
-
function staleReservedSql(staleSeconds, t = defaultTableNames) {
|
|
163
|
-
return `SELECT COUNT(*) AS total
|
|
164
|
-
FROM ${t.jobs}
|
|
165
|
-
WHERE reserved_at IS NOT NULL AND reserved_at <= unixepoch() - ${sqlInt(staleSeconds)} AND ${ACTIVE}`;
|
|
166
|
-
}
|
|
167
|
-
function activeJobsSql(filters = {}, t = defaultTableNames) {
|
|
168
|
-
const limit = sqlInt(filters.limit ?? 50);
|
|
169
|
-
return `SELECT id, queue, job_type, attempts, max_attempts, available_at, reserved_at, created_at, site_id, last_error
|
|
170
|
-
FROM ${t.jobs}
|
|
171
|
-
${andClauses(
|
|
172
|
-
ACTIVE,
|
|
173
|
-
filters.queue && `queue = ${sqlString(filters.queue)}`,
|
|
174
|
-
filters.type && `job_type = ${sqlString(filters.type)}`,
|
|
175
|
-
stateClause(filters.state)
|
|
176
|
-
)}
|
|
177
|
-
ORDER BY available_at ASC
|
|
178
|
-
LIMIT ${limit}`;
|
|
179
|
-
}
|
|
180
|
-
function failedJobsSql(filters = {}, t = defaultTableNames) {
|
|
181
|
-
const limit = sqlInt(filters.limit ?? 50);
|
|
182
|
-
return `SELECT id, queue, job_type, attempts, max_attempts, failed_at, site_id, exception
|
|
183
|
-
FROM ${t.failed}
|
|
184
|
-
${andClauses(
|
|
185
|
-
filters.queue && `queue = ${sqlString(filters.queue)}`,
|
|
186
|
-
filters.type && `job_type = ${sqlString(filters.type)}`
|
|
187
|
-
)}
|
|
188
|
-
ORDER BY failed_at DESC
|
|
189
|
-
LIMIT ${limit}`;
|
|
190
|
-
}
|
|
191
|
-
const CARRIED_COLUMNS = "id, queue, job_type, batch_id, user_id, site_id, partner_id, trace_id, unique_key, payload";
|
|
192
|
-
function retrySql(opts, t = defaultTableNames) {
|
|
193
|
-
if (!opts.id && !opts.queue && !opts.all)
|
|
194
|
-
throw new Error("retrySql requires an id, a queue, or all=true");
|
|
195
|
-
const where = andClauses(
|
|
196
|
-
opts.id && `id = ${sqlString(opts.id)}`,
|
|
197
|
-
opts.queue && `queue = ${sqlString(opts.queue)}`
|
|
198
|
-
);
|
|
199
|
-
return `INSERT OR IGNORE INTO ${t.jobs} (${CARRIED_COLUMNS}, attempts, max_attempts, available_at, created_at)
|
|
200
|
-
SELECT ${CARRIED_COLUMNS}, 0, max_attempts, unixepoch(), unixepoch() FROM ${t.failed} ${where};
|
|
201
|
-
DELETE FROM ${t.failed} ${where};`;
|
|
202
|
-
}
|
|
203
|
-
function forgetSql(id, t = defaultTableNames) {
|
|
204
|
-
return `DELETE FROM ${t.failed} WHERE id = ${sqlString(id)}`;
|
|
205
|
-
}
|
|
206
|
-
function flushSql(queue, t = defaultTableNames) {
|
|
207
|
-
return `DELETE FROM ${t.failed} ${queue ? `WHERE queue = ${sqlString(queue)}` : ""}`.trimEnd();
|
|
208
|
-
}
|
|
209
|
-
function pruneCompletedJobsSql(hours, t = defaultTableNames) {
|
|
210
|
-
return `DELETE FROM ${t.jobs} WHERE completed_at IS NOT NULL AND completed_at <= unixepoch() - ${sqlInt(hours * 3600)}`;
|
|
211
|
-
}
|
|
212
|
-
function pruneFailedJobsSql(hours, t = defaultTableNames) {
|
|
213
|
-
return `DELETE FROM ${t.failed} WHERE failed_at <= unixepoch() - ${sqlInt(hours * 3600)}`;
|
|
214
|
-
}
|
|
215
|
-
function pruneFinishedBatchesSql(hours, t = defaultTableNames) {
|
|
216
|
-
return `DELETE FROM ${t.batches} WHERE finished_at IS NOT NULL AND finished_at <= unixepoch() - ${sqlInt(hours * 3600)}`;
|
|
217
|
-
}
|
|
218
|
-
function pruneSql(opts, t = defaultTableNames) {
|
|
219
|
-
return [
|
|
220
|
-
pruneCompletedJobsSql(opts.completedHours, t),
|
|
221
|
-
pruneFailedJobsSql(opts.failedHours, t),
|
|
222
|
-
pruneFinishedBatchesSql(opts.batchesHours, t)
|
|
223
|
-
].join(";\n");
|
|
224
|
-
}
|
|
225
|
-
function clearSql(filters = {}, t = defaultTableNames) {
|
|
226
|
-
return `DELETE FROM ${t.jobs}
|
|
227
|
-
${andClauses(
|
|
228
|
-
ACTIVE,
|
|
229
|
-
filters.queue && `queue = ${sqlString(filters.queue)}`,
|
|
230
|
-
stateClause(filters.state)
|
|
231
|
-
)}`;
|
|
232
|
-
}
|
|
233
|
-
function summarizeBackpressure(rows, nowSeconds) {
|
|
234
|
-
const queues = rows.map((r) => ({
|
|
235
|
-
...r,
|
|
236
|
-
lagSeconds: r.oldest_available_at != null && r.ready > 0 ? Math.max(0, nowSeconds - r.oldest_available_at) : 0
|
|
237
|
-
}));
|
|
238
|
-
const totals = queues.reduce(
|
|
239
|
-
(acc, q) => ({
|
|
240
|
-
total: acc.total + q.total,
|
|
241
|
-
ready: acc.ready + q.ready,
|
|
242
|
-
reserved: acc.reserved + q.reserved,
|
|
243
|
-
delayed: acc.delayed + q.delayed
|
|
244
|
-
}),
|
|
245
|
-
{ total: 0, ready: 0, reserved: 0, delayed: 0 }
|
|
246
|
-
);
|
|
247
|
-
const maxLagSeconds = queues.reduce((max, q) => Math.max(max, q.lagSeconds), 0);
|
|
248
|
-
return { queues, totals, maxLagSeconds };
|
|
249
|
-
}
|
|
250
|
-
|
|
251
115
|
const useColor = !process.env.NO_COLOR && process.stdout?.isTTY !== false;
|
|
252
116
|
function wrap(open, close) {
|
|
253
117
|
return (s) => useColor ? `\x1B[${open}m${s}\x1B[${close}m` : String(s);
|
package/dist/module.d.mts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { Nuxt } from '@nuxt/schema';
|
|
2
|
+
import { QueueCheckOptions } from './checks.mjs';
|
|
3
|
+
import '@harlan-zw/nuxt-checkin/server';
|
|
2
4
|
|
|
3
5
|
interface QueueBindingOptions {
|
|
4
6
|
binding: string;
|
|
@@ -75,6 +77,8 @@ interface ReconcileOptions {
|
|
|
75
77
|
terminalFailureContext?: string;
|
|
76
78
|
}
|
|
77
79
|
interface ModuleOptions {
|
|
80
|
+
/** Register checks through the public check-in API. */
|
|
81
|
+
checks?: QueueCheckOptions[];
|
|
78
82
|
/**
|
|
79
83
|
* Logical queue name -> Cloudflare env binding name.
|
|
80
84
|
*
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -376,6 +376,13 @@ const module$1 = defineNuxtModule().with({
|
|
|
376
376
|
const resolver = createResolver(import.meta.url);
|
|
377
377
|
const queues = options.queues;
|
|
378
378
|
const hasQueues = Object.keys(queues).length > 0;
|
|
379
|
+
nuxt.hook("checkin:register", (registry) => {
|
|
380
|
+
for (const check of options.checks ?? []) {
|
|
381
|
+
if (!(check.queue in queues))
|
|
382
|
+
throw new Error(`Check queue is not configured: ${check.queue}`);
|
|
383
|
+
registry.add({ id: check.id, handler: resolver.resolve("./checks"), options: { ...check } });
|
|
384
|
+
}
|
|
385
|
+
});
|
|
379
386
|
const broadcast = resolveBroadcastOptions(options.broadcast);
|
|
380
387
|
const reconcile = resolveReconcileOptions(options.reconcile);
|
|
381
388
|
nuxt.options.alias["#cf-jobs/server"] = resolver.resolve("./runtime/server");
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
const defaultTableNames = {
|
|
2
|
+
jobs: "jobs",
|
|
3
|
+
failed: "failed_jobs",
|
|
4
|
+
batches: "job_batches"
|
|
5
|
+
};
|
|
6
|
+
function sqlString(value) {
|
|
7
|
+
return `'${value.replace(/'/g, "''")}'`;
|
|
8
|
+
}
|
|
9
|
+
function sqlInt(value) {
|
|
10
|
+
if (!Number.isFinite(value))
|
|
11
|
+
throw new TypeError(`Expected a finite number, got ${value}`);
|
|
12
|
+
return Math.trunc(value);
|
|
13
|
+
}
|
|
14
|
+
const ACTIVE = "completed_at IS NULL AND failed_at IS NULL";
|
|
15
|
+
function stateClause(state) {
|
|
16
|
+
switch (state) {
|
|
17
|
+
case "ready":
|
|
18
|
+
return "reserved_at IS NULL AND available_at <= unixepoch()";
|
|
19
|
+
case "reserved":
|
|
20
|
+
return "reserved_at IS NOT NULL";
|
|
21
|
+
case "delayed":
|
|
22
|
+
return "reserved_at IS NULL AND available_at > unixepoch()";
|
|
23
|
+
case "completed":
|
|
24
|
+
return "completed_at IS NOT NULL";
|
|
25
|
+
default:
|
|
26
|
+
return "";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function andClauses(...clauses) {
|
|
30
|
+
const parts = clauses.filter((c) => !!c);
|
|
31
|
+
return parts.length ? `WHERE ${parts.join(" AND ")}` : "";
|
|
32
|
+
}
|
|
33
|
+
function backpressureSql(t = defaultTableNames, nowSeconds) {
|
|
34
|
+
const now = nowSeconds === void 0 ? "unixepoch()" : String(sqlInt(nowSeconds));
|
|
35
|
+
return `SELECT queue,
|
|
36
|
+
COUNT(*) AS total,
|
|
37
|
+
SUM(CASE WHEN reserved_at IS NULL AND available_at <= ${now} THEN 1 ELSE 0 END) AS ready,
|
|
38
|
+
SUM(CASE WHEN reserved_at IS NOT NULL THEN 1 ELSE 0 END) AS reserved,
|
|
39
|
+
SUM(CASE WHEN reserved_at IS NULL AND available_at > ${now} THEN 1 ELSE 0 END) AS delayed,
|
|
40
|
+
MIN(CASE WHEN reserved_at IS NULL AND available_at <= ${now} THEN available_at END) AS oldest_available_at,
|
|
41
|
+
MIN(reserved_at) AS oldest_reserved_at
|
|
42
|
+
FROM ${t.jobs}
|
|
43
|
+
WHERE ${ACTIVE}
|
|
44
|
+
GROUP BY queue
|
|
45
|
+
ORDER BY total DESC`;
|
|
46
|
+
}
|
|
47
|
+
function failedCountSql(t = defaultTableNames) {
|
|
48
|
+
return `SELECT queue, COUNT(*) AS total FROM ${t.failed} GROUP BY queue ORDER BY total DESC`;
|
|
49
|
+
}
|
|
50
|
+
function staleReservedSql(staleSeconds, t = defaultTableNames) {
|
|
51
|
+
return `SELECT COUNT(*) AS total
|
|
52
|
+
FROM ${t.jobs}
|
|
53
|
+
WHERE reserved_at IS NOT NULL AND reserved_at <= unixepoch() - ${sqlInt(staleSeconds)} AND ${ACTIVE}`;
|
|
54
|
+
}
|
|
55
|
+
function activeJobsSql(filters = {}, t = defaultTableNames) {
|
|
56
|
+
const limit = sqlInt(filters.limit ?? 50);
|
|
57
|
+
return `SELECT id, queue, job_type, attempts, max_attempts, available_at, reserved_at, created_at, site_id, last_error
|
|
58
|
+
FROM ${t.jobs}
|
|
59
|
+
${andClauses(
|
|
60
|
+
ACTIVE,
|
|
61
|
+
filters.queue && `queue = ${sqlString(filters.queue)}`,
|
|
62
|
+
filters.type && `job_type = ${sqlString(filters.type)}`,
|
|
63
|
+
stateClause(filters.state)
|
|
64
|
+
)}
|
|
65
|
+
ORDER BY available_at ASC
|
|
66
|
+
LIMIT ${limit}`;
|
|
67
|
+
}
|
|
68
|
+
function failedJobsSql(filters = {}, t = defaultTableNames) {
|
|
69
|
+
const limit = sqlInt(filters.limit ?? 50);
|
|
70
|
+
return `SELECT id, queue, job_type, attempts, max_attempts, failed_at, site_id, exception
|
|
71
|
+
FROM ${t.failed}
|
|
72
|
+
${andClauses(
|
|
73
|
+
filters.queue && `queue = ${sqlString(filters.queue)}`,
|
|
74
|
+
filters.type && `job_type = ${sqlString(filters.type)}`
|
|
75
|
+
)}
|
|
76
|
+
ORDER BY failed_at DESC
|
|
77
|
+
LIMIT ${limit}`;
|
|
78
|
+
}
|
|
79
|
+
const CARRIED_COLUMNS = "id, queue, job_type, batch_id, user_id, site_id, partner_id, trace_id, unique_key, payload";
|
|
80
|
+
function retrySql(opts, t = defaultTableNames) {
|
|
81
|
+
if (!opts.id && !opts.queue && !opts.all)
|
|
82
|
+
throw new Error("retrySql requires an id, a queue, or all=true");
|
|
83
|
+
const where = andClauses(
|
|
84
|
+
opts.id && `id = ${sqlString(opts.id)}`,
|
|
85
|
+
opts.queue && `queue = ${sqlString(opts.queue)}`
|
|
86
|
+
);
|
|
87
|
+
return `INSERT OR IGNORE INTO ${t.jobs} (${CARRIED_COLUMNS}, attempts, max_attempts, available_at, created_at)
|
|
88
|
+
SELECT ${CARRIED_COLUMNS}, 0, max_attempts, unixepoch(), unixepoch() FROM ${t.failed} ${where};
|
|
89
|
+
DELETE FROM ${t.failed} ${where};`;
|
|
90
|
+
}
|
|
91
|
+
function forgetSql(id, t = defaultTableNames) {
|
|
92
|
+
return `DELETE FROM ${t.failed} WHERE id = ${sqlString(id)}`;
|
|
93
|
+
}
|
|
94
|
+
function flushSql(queue, t = defaultTableNames) {
|
|
95
|
+
return `DELETE FROM ${t.failed} ${queue ? `WHERE queue = ${sqlString(queue)}` : ""}`.trimEnd();
|
|
96
|
+
}
|
|
97
|
+
function pruneCompletedJobsSql(hours, t = defaultTableNames) {
|
|
98
|
+
return `DELETE FROM ${t.jobs} WHERE completed_at IS NOT NULL AND completed_at <= unixepoch() - ${sqlInt(hours * 3600)}`;
|
|
99
|
+
}
|
|
100
|
+
function pruneFailedJobsSql(hours, t = defaultTableNames) {
|
|
101
|
+
return `DELETE FROM ${t.failed} WHERE failed_at <= unixepoch() - ${sqlInt(hours * 3600)}`;
|
|
102
|
+
}
|
|
103
|
+
function pruneFinishedBatchesSql(hours, t = defaultTableNames) {
|
|
104
|
+
return `DELETE FROM ${t.batches} WHERE finished_at IS NOT NULL AND finished_at <= unixepoch() - ${sqlInt(hours * 3600)}`;
|
|
105
|
+
}
|
|
106
|
+
function pruneSql(opts, t = defaultTableNames) {
|
|
107
|
+
return [
|
|
108
|
+
pruneCompletedJobsSql(opts.completedHours, t),
|
|
109
|
+
pruneFailedJobsSql(opts.failedHours, t),
|
|
110
|
+
pruneFinishedBatchesSql(opts.batchesHours, t)
|
|
111
|
+
].join(";\n");
|
|
112
|
+
}
|
|
113
|
+
function clearSql(filters = {}, t = defaultTableNames) {
|
|
114
|
+
return `DELETE FROM ${t.jobs}
|
|
115
|
+
${andClauses(
|
|
116
|
+
ACTIVE,
|
|
117
|
+
filters.queue && `queue = ${sqlString(filters.queue)}`,
|
|
118
|
+
stateClause(filters.state)
|
|
119
|
+
)}`;
|
|
120
|
+
}
|
|
121
|
+
function summarizeBackpressure(rows, nowSeconds) {
|
|
122
|
+
const queues = rows.map((r) => ({
|
|
123
|
+
...r,
|
|
124
|
+
lagSeconds: r.oldest_available_at != null && r.ready > 0 ? Math.max(0, nowSeconds - r.oldest_available_at) : 0
|
|
125
|
+
}));
|
|
126
|
+
const totals = queues.reduce(
|
|
127
|
+
(acc, q) => ({
|
|
128
|
+
total: acc.total + q.total,
|
|
129
|
+
ready: acc.ready + q.ready,
|
|
130
|
+
reserved: acc.reserved + q.reserved,
|
|
131
|
+
delayed: acc.delayed + q.delayed
|
|
132
|
+
}),
|
|
133
|
+
{ total: 0, ready: 0, reserved: 0, delayed: 0 }
|
|
134
|
+
);
|
|
135
|
+
const maxLagSeconds = queues.reduce((max, q) => Math.max(max, q.lagSeconds), 0);
|
|
136
|
+
return { queues, totals, maxLagSeconds };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export { summarizeBackpressure as a, backpressureSql as b, activeJobsSql as c, defaultTableNames as d, failedJobsSql as e, failedCountSql as f, forgetSql as g, flushSql as h, clearSql as i, pruneSql as p, retrySql as r, staleReservedSql as s };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@harlan-zw/nuxt-cf-jobs",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.3",
|
|
5
5
|
"description": "Experimental Nuxt module for typed Cloudflare queue jobs.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Harlan Wilton",
|
|
@@ -76,6 +76,10 @@
|
|
|
76
76
|
"types": "./dist/runtime/server/testing.d.ts",
|
|
77
77
|
"import": "./dist/runtime/server/testing.js",
|
|
78
78
|
"default": "./dist/runtime/server/testing.js"
|
|
79
|
+
},
|
|
80
|
+
"./checks": {
|
|
81
|
+
"types": "./dist/checks.d.mts",
|
|
82
|
+
"import": "./dist/checks.mjs"
|
|
79
83
|
}
|
|
80
84
|
},
|
|
81
85
|
"main": "./dist/module.mjs",
|
|
@@ -108,6 +112,9 @@
|
|
|
108
112
|
],
|
|
109
113
|
"testing": [
|
|
110
114
|
"dist/runtime/server/testing.d.ts"
|
|
115
|
+
],
|
|
116
|
+
"checks": [
|
|
117
|
+
"dist/checks.d.mts"
|
|
111
118
|
]
|
|
112
119
|
}
|
|
113
120
|
},
|
|
@@ -121,11 +128,15 @@
|
|
|
121
128
|
"node": ">=22.12.0"
|
|
122
129
|
},
|
|
123
130
|
"peerDependencies": {
|
|
131
|
+
"@harlan-zw/nuxt-checkin": "^0.1.0",
|
|
124
132
|
"@sentry/cloudflare": "^10.70.0",
|
|
125
133
|
"nuxt": ">=4.5.0 <6.0.0",
|
|
126
134
|
"vite": "^8.0.0"
|
|
127
135
|
},
|
|
128
136
|
"peerDependenciesMeta": {
|
|
137
|
+
"@harlan-zw/nuxt-checkin": {
|
|
138
|
+
"optional": true
|
|
139
|
+
},
|
|
129
140
|
"@sentry/cloudflare": {
|
|
130
141
|
"optional": true
|
|
131
142
|
}
|
|
@@ -135,7 +146,7 @@
|
|
|
135
146
|
"@nuxt/schema": "^4.5.2",
|
|
136
147
|
"citty": "^0.2.2",
|
|
137
148
|
"drizzle-orm": "1.0.0-rc.4",
|
|
138
|
-
"@harlan-zw/nuxt-cloudflare": "^0.
|
|
149
|
+
"@harlan-zw/nuxt-cloudflare": "^0.4.1"
|
|
139
150
|
},
|
|
140
151
|
"devDependencies": {
|
|
141
152
|
"@antfu/eslint-config": "^9.3.0",
|
|
@@ -159,7 +170,8 @@
|
|
|
159
170
|
"vitest": "^4.1.10",
|
|
160
171
|
"vue": "^3.5.40",
|
|
161
172
|
"vue-tsc": "^3.3.9",
|
|
162
|
-
"wrangler": "^4.120.1"
|
|
173
|
+
"wrangler": "^4.120.1",
|
|
174
|
+
"@harlan-zw/nuxt-checkin": "0.1.0"
|
|
163
175
|
},
|
|
164
176
|
"scripts": {
|
|
165
177
|
"build": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt-module-build build",
|