@plitzi/sdk-actions 0.0.0-stage → 0.39.2
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 +11 -0
- package/README.md +54 -2
- package/dist/chunks/credentials-DwxZeAvH.mjs +27 -0
- package/dist/chunks/errors-bCBfIe7c.mjs +54 -0
- package/dist/chunks/grants-BsD-WlLE.mjs +168 -0
- package/dist/chunks/load-DBWRZn7G.mjs +48 -0
- package/dist/chunks/module-WdDzbjHy.mjs +7032 -0
- package/dist/chunks/queueDocument-xYz-KZ5V.mjs +21 -0
- package/dist/chunks/queueRules-BCCVgeUE.mjs +487 -0
- package/dist/chunks/remote-DopPgCMK.mjs +404 -0
- package/dist/chunks/storeClock-Btm7EaVm.mjs +31 -0
- package/dist/chunks/taskCatalog-S1IozUTD.mjs +201 -0
- package/dist/connectors/connectors.d.ts +7 -0
- package/dist/connectors/engine.d.ts +47 -0
- package/dist/connectors/getByPath.d.ts +8 -0
- package/dist/connectors/projection.d.ts +18 -0
- package/dist/connectors/resolver.d.ts +27 -0
- package/dist/connectors/types.d.ts +19 -0
- package/dist/engine/configSeam.d.ts +10 -0
- package/dist/engine/connectorWrite.d.ts +12 -0
- package/dist/engine/fileStore.d.ts +60 -0
- package/dist/engine/fleet.d.ts +20 -0
- package/dist/engine/jobs/calls.d.ts +49 -0
- package/dist/engine/jobs/claimSpaces.d.ts +10 -0
- package/dist/engine/jobs/codeMarks.d.ts +10 -0
- package/dist/engine/jobs/endings.d.ts +42 -0
- package/dist/engine/jobs/failureStreak.d.ts +15 -0
- package/dist/engine/jobs/fileQueue.d.ts +34 -0
- package/dist/engine/jobs/flow.d.ts +11 -0
- package/dist/engine/jobs/jobs.d.ts +36 -0
- package/dist/engine/jobs/later.d.ts +27 -0
- package/dist/engine/jobs/memoryNeeds.d.ts +24 -0
- package/dist/engine/jobs/memoryQueue.d.ts +33 -0
- package/dist/engine/jobs/memoryWatch.d.ts +21 -0
- package/dist/engine/jobs/notNow.d.ts +39 -0
- package/dist/engine/jobs/queueDocument.d.ts +15 -0
- package/dist/engine/jobs/queueRules.d.ts +64 -0
- package/dist/engine/jobs/scheduler.d.ts +70 -0
- package/dist/engine/jobs/schedules.d.ts +24 -0
- package/dist/engine/jobs/storeClock.d.ts +16 -0
- package/dist/engine/jobs/wake.d.ts +6 -0
- package/dist/engine/jobs/worker.d.ts +99 -0
- package/dist/engine/module.d.ts +96 -0
- package/dist/engine/moduleFor.d.ts +3 -0
- package/dist/engine/runtime/check.d.ts +24 -0
- package/dist/engine/runtime/credentials.d.ts +8 -0
- package/dist/engine/runtime/deadline.d.ts +19 -0
- package/dist/engine/runtime/email.d.ts +38 -0
- package/dist/engine/runtime/errors.d.ts +28 -0
- package/dist/engine/runtime/fileKv.d.ts +35 -0
- package/dist/engine/runtime/flags.d.ts +16 -0
- package/dist/engine/runtime/guards.d.ts +190 -0
- package/dist/engine/runtime/kvList.d.ts +28 -0
- package/dist/engine/runtime/kvStore.d.ts +36 -0
- package/dist/engine/runtime/limits.d.ts +12 -0
- package/dist/engine/runtime/memoryKv.d.ts +28 -0
- package/dist/engine/runtime/namespaceKv.d.ts +9 -0
- package/dist/engine/runtime/precheck.d.ts +28 -0
- package/dist/engine/runtime/rateLimit.d.ts +9 -0
- package/dist/engine/runtime/redisKv.d.ts +27 -0
- package/dist/engine/runtime/renderFailure.d.ts +24 -0
- package/dist/engine/runtime/renderResolver.d.ts +16 -0
- package/dist/engine/runtime/renderShare.d.ts +12 -0
- package/dist/engine/runtime/report.d.ts +15 -0
- package/dist/engine/runtime/runAction.d.ts +26 -0
- package/dist/engine/runtime/runLogger.d.ts +37 -0
- package/dist/engine/runtime/runStats.d.ts +8 -0
- package/dist/engine/runtime/scope.d.ts +40 -0
- package/dist/engine/runtime/signing.d.ts +27 -0
- package/dist/engine/runtime/taskContext.d.ts +54 -0
- package/dist/engine/runtime/triggers.d.ts +12 -0
- package/dist/engine/taskCatalog.d.ts +28 -0
- package/dist/engine/tasks/auth.d.ts +2 -0
- package/dist/engine/tasks/builtins.d.ts +10 -0
- package/dist/engine/tasks/connector.d.ts +2 -0
- package/dist/engine/tasks/db.d.ts +2 -0
- package/dist/engine/tasks/email.d.ts +2 -0
- package/dist/engine/tasks/flow.d.ts +3 -0
- package/dist/engine/tasks/helpers.d.ts +16 -0
- package/dist/engine/tasks/http.d.ts +2 -0
- package/dist/engine/tasks/kv.d.ts +2 -0
- package/dist/engine/tasks/list.d.ts +2 -0
- package/dist/engine/tasks/names.d.ts +8 -0
- package/dist/engine/tasks/realtime.d.ts +3 -0
- package/dist/engine/tasks/registry.d.ts +19 -0
- package/dist/engine/tasks/transform.d.ts +2 -0
- package/dist/engine/transport/callHandler.d.ts +34 -0
- package/dist/engine/transport/cancelHandler.d.ts +23 -0
- package/dist/engine/transport/catalogHandler.d.ts +22 -0
- package/dist/engine/transport/stream.d.ts +22 -0
- package/dist/engine/transport/verifySignature.d.ts +16 -0
- package/dist/engine/transport/webhookHandler.d.ts +26 -0
- package/dist/engine/types.d.ts +442 -0
- package/dist/functions/build.d.ts +27 -0
- package/dist/functions/capabilities.d.ts +11 -0
- package/dist/functions/config.d.ts +111 -0
- package/dist/functions/context.d.ts +15 -0
- package/dist/functions/index.d.ts +17 -0
- package/dist/functions/index.mjs +461 -0
- package/dist/functions/jobControl.d.ts +22 -0
- package/dist/functions/jobs.d.ts +104 -0
- package/dist/functions/load.d.ts +22 -0
- package/dist/functions/local.d.ts +36 -0
- package/dist/functions/manifest.d.ts +32 -0
- package/dist/functions/native.d.ts +13 -0
- package/dist/functions/oauth.d.ts +33 -0
- package/dist/functions/routes.d.ts +50 -0
- package/dist/functions/runner/remote.d.ts +26 -0
- package/dist/functions/scope.d.ts +28 -0
- package/dist/functions/space.d.ts +41 -0
- package/dist/functions/tryEntry.d.ts +9 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.mjs +545 -0
- package/dist/mongo/claimable.d.ts +5 -0
- package/dist/mongo/index.d.ts +4 -0
- package/dist/mongo/index.mjs +779 -0
- package/dist/mongo/jobQueue.d.ts +38 -0
- package/dist/mongo/kv.d.ts +15 -0
- package/dist/mysql/index.d.ts +5 -0
- package/dist/mysql/index.mjs +808 -0
- package/dist/mysql/jobQueue.d.ts +40 -0
- package/dist/mysql/kv.d.ts +18 -0
- package/dist/mysql/rows.d.ts +64 -0
- package/dist/mysql/schema.d.ts +28 -0
- package/dist/mysql/summary.d.ts +7 -0
- package/dist/realtime/declarations.d.ts +11 -0
- package/dist/realtime/failure.d.ts +6 -0
- package/dist/realtime/grants.d.ts +22 -0
- package/dist/realtime/handlers.d.ts +86 -0
- package/dist/realtime/hub.d.ts +71 -0
- package/dist/realtime/index.d.ts +105 -0
- package/dist/realtime/index.mjs +824 -0
- package/dist/realtime/jobs.d.ts +18 -0
- package/dist/realtime/message.d.ts +3 -0
- package/dist/realtime/presence.d.ts +33 -0
- package/dist/realtime/retained.d.ts +21 -0
- package/dist/realtime/socket.d.ts +30 -0
- package/dist/render/index.d.ts +10 -0
- package/dist/render/index.mjs +1 -0
- package/dist/render/protocol.d.ts +47 -0
- package/dist/render/remote.d.ts +16 -0
- package/dist/runtimes/bundle.d.ts +29 -0
- package/dist/runtimes/index.d.ts +3 -0
- package/dist/runtimes/index.mjs +229 -0
- package/dist/runtimes/stages.d.ts +52 -0
- package/dist/sqlite/index.d.ts +4 -0
- package/dist/sqlite/index.mjs +160 -0
- package/dist/sqlite/jobQueue.d.ts +35 -0
- package/dist/sqlite/kv.d.ts +34 -0
- package/dist/sqlite/open.d.ts +3 -0
- package/dist/types/config.d.ts +293 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types/jobs.d.ts +317 -0
- package/dist/worker/elsewhere.d.ts +16 -0
- package/dist/worker/index.d.ts +5 -0
- package/dist/worker/index.mjs +1703 -0
- package/dist/worker/origin.d.ts +12 -0
- package/dist/worker/pageEngine.d.ts +11 -0
- package/dist/worker/stages/action.d.ts +24 -0
- package/dist/worker/stages/cors.d.ts +9 -0
- package/dist/worker/stages/forward.d.ts +12 -0
- package/dist/worker/stages/functionRoutes.d.ts +10 -0
- package/dist/worker/stages/queuedCalls.d.ts +15 -0
- package/dist/worker/stages/realtime.d.ts +9 -0
- package/dist/worker/stages/render.d.ts +9 -0
- package/dist/worker/worker.d.ts +39 -0
- package/package.json +76 -3
|
@@ -0,0 +1,808 @@
|
|
|
1
|
+
import { _ as flowOf, d as LOST_ERROR, g as outgrewWorker, h as needsAfterLoss, m as lostError, o as noJobsByStatus, p as SET_ASIDE_WORDS, u as waitingKindOf } from "../chunks/queueRules-BCCVgeUE.mjs";
|
|
2
|
+
import { t as createStoreClock } from "../chunks/storeClock-Btm7EaVm.mjs";
|
|
3
|
+
import { TERMINAL_JOB_STATUSES } from "@plitzi/sdk-shared/actions";
|
|
4
|
+
import { execute, selectOne, selectRows } from "@plitzi/sdk-kernel/mysql";
|
|
5
|
+
// src/mysql/rows.ts
|
|
6
|
+
/**
|
|
7
|
+
* A row as the contract shapes it.
|
|
8
|
+
*
|
|
9
|
+
* `BIGINT` arrives as a number or as a string depending on how the deployment configured its pool
|
|
10
|
+
* (`bigNumberStrings`), so every numeric column goes through `Number`. The text columns hold only what this queue
|
|
11
|
+
* wrote into them — a status, an environment, a trigger — which is why they can be read back as those types.
|
|
12
|
+
*/
|
|
13
|
+
var toJob = (row) => ({
|
|
14
|
+
id: row.id,
|
|
15
|
+
spaceId: Number(row.space_id),
|
|
16
|
+
target: JSON.parse(row.target),
|
|
17
|
+
environment: row.environment,
|
|
18
|
+
input: JSON.parse(row.input),
|
|
19
|
+
dueAt: Number(row.due_at),
|
|
20
|
+
maxAttempts: Number(row.max_attempts),
|
|
21
|
+
...row.missed === null ? {} : { missed: Number(row.missed) },
|
|
22
|
+
...row.job_key === null ? {} : { key: row.job_key },
|
|
23
|
+
status: row.status,
|
|
24
|
+
runAt: Number(row.run_at),
|
|
25
|
+
attempts: Number(row.attempts),
|
|
26
|
+
...row.lease_until === null ? {} : { leaseUntil: Number(row.lease_until) },
|
|
27
|
+
...row.worker_id === null ? {} : { workerId: row.worker_id },
|
|
28
|
+
...row.run_id === null ? {} : { runId: row.run_id },
|
|
29
|
+
...Number(row.cancel_requested) === 1 ? { cancelRequested: true } : {},
|
|
30
|
+
createdAt: Number(row.created_at),
|
|
31
|
+
updatedAt: Number(row.updated_at),
|
|
32
|
+
...row.error === null ? {} : { error: row.error },
|
|
33
|
+
history: JSON.parse(row.history),
|
|
34
|
+
...row.state === null ? {} : { state: JSON.parse(row.state) },
|
|
35
|
+
...row.progress === null ? {} : { progress: JSON.parse(row.progress) },
|
|
36
|
+
...row.result === null ? {} : { result: JSON.parse(row.result) },
|
|
37
|
+
...Number(row.pause_requested) === 1 ? { pauseRequested: true } : {},
|
|
38
|
+
...Number(row.active_ms) > 0 ? { activeMs: Number(row.active_ms) } : {},
|
|
39
|
+
...row.holder_memory_mb === null ? {} : { holderMemoryMb: Number(row.holder_memory_mb) },
|
|
40
|
+
...row.needs_memory_mb === null ? {} : { needsMemoryMb: Number(row.needs_memory_mb) },
|
|
41
|
+
...Number(row.near_memory_limit) === 1 ? { nearMemoryLimit: true } : {}
|
|
42
|
+
});
|
|
43
|
+
/** A value of a JSON column, or SQL's NULL for none. */
|
|
44
|
+
var jsonOrNull = (value) => value === void 0 ? null : JSON.stringify(value);
|
|
45
|
+
var toSchedule = (row) => ({
|
|
46
|
+
spaceId: Number(row.space_id),
|
|
47
|
+
actionId: row.action_id,
|
|
48
|
+
cron: row.cron,
|
|
49
|
+
...row.timezone === null ? {} : { timezone: row.timezone },
|
|
50
|
+
environment: row.environment,
|
|
51
|
+
enabled: Number(row.enabled) === 1,
|
|
52
|
+
nextRunAt: Number(row.next_run_at),
|
|
53
|
+
...row.last_fire_at === null ? {} : { lastFireAt: Number(row.last_fire_at) },
|
|
54
|
+
missed: Number(row.missed),
|
|
55
|
+
maxAttempts: Number(row.max_attempts),
|
|
56
|
+
updatedAt: Number(row.updated_at)
|
|
57
|
+
});
|
|
58
|
+
/**
|
|
59
|
+
* What a claim with these `spaces` and `memoryMb` takes at `at`, as SQL: due and waiting, of its spaces — as many
|
|
60
|
+
* placeholders as ids; an empty "only" takes none, an empty "except" every space — or a job a worker died running that
|
|
61
|
+
* this one may hold, whatever its spaces.
|
|
62
|
+
*/
|
|
63
|
+
/** What each kind of work is, as a condition (`JobTake`, `queueRules`' `takeOf`): `code` is written only as true. */
|
|
64
|
+
var TAKES = {
|
|
65
|
+
light: "target_kind = 'action' AND JSON_EXTRACT(target, '$.code') IS NULL",
|
|
66
|
+
codeActions: "target_kind = 'action' AND JSON_EXTRACT(target, '$.code') IS NOT NULL",
|
|
67
|
+
functionJobs: "target_kind = 'function'"
|
|
68
|
+
};
|
|
69
|
+
var claimable = (at, spaces, memoryMb, takes) => {
|
|
70
|
+
const ids = spaces ? "only" in spaces ? spaces.only : spaces.except : [];
|
|
71
|
+
const bySpace = !spaces || ids.length === 0 ? spaces && "only" in spaces ? " AND FALSE" : "" : ` AND space_id ${"only" in spaces ? "IN" : "NOT IN"} (${ids.map(() => "?").join(", ")})`;
|
|
72
|
+
return {
|
|
73
|
+
sql: `status = 'pending' AND run_at <= ?${takes ? ` AND ${TAKES[takes]}` : ""}
|
|
74
|
+
AND ((needs_memory_mb IS NULL${bySpace})${memoryMb === void 0 ? "" : " OR needs_memory_mb <= ?"})`,
|
|
75
|
+
params: [
|
|
76
|
+
at,
|
|
77
|
+
...bySpace.includes("?") ? ids : [],
|
|
78
|
+
...memoryMb === void 0 ? [] : [memoryMb]
|
|
79
|
+
]
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
// src/mysql/schema.ts
|
|
83
|
+
var PREFIX = /^[A-Za-z0-9_]*$/;
|
|
84
|
+
/**
|
|
85
|
+
* Table names under a prefix. A prefix is part of an identifier, which no driver can bind as a parameter — so it is
|
|
86
|
+
* held to the characters an unquoted identifier may use, and refused otherwise, rather than escaped and hoped for.
|
|
87
|
+
*/
|
|
88
|
+
var jobTables = (prefix = "") => {
|
|
89
|
+
if (!PREFIX.test(prefix)) throw new Error(`@plitzi/sdk-actions/mysql: tablePrefix "${prefix}" may only use letters, digits and underscores`);
|
|
90
|
+
return {
|
|
91
|
+
jobs: `\`${prefix}action_jobs\``,
|
|
92
|
+
schedules: `\`${prefix}action_schedules\``,
|
|
93
|
+
kv: `\`${prefix}action_kv\``
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
var CHARSET = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
|
|
97
|
+
/**
|
|
98
|
+
* The tables, as SQL — for a deployment that runs its own migrations rather than letting the helpers create them.
|
|
99
|
+
*
|
|
100
|
+
* Instants are epoch milliseconds in `BIGINT`, read from the SERVER's clock; `history` and `input` are JSON kept as
|
|
101
|
+
* text, because they are only ever read whole. Separate from the account store's schema and its version: a deployment
|
|
102
|
+
* can use either without the other.
|
|
103
|
+
*
|
|
104
|
+
* A `kv` key is BYTES, as it is in Redis and in memory: under a collation `Board` and `board` — and `a` and `a ` — were
|
|
105
|
+
* one key here and two everywhere else. A value is a `MEDIUMTEXT`: a `TEXT` stops at 64 KB, and past it MySQL
|
|
106
|
+
* refuses the write, or cuts it short where it is not strict.
|
|
107
|
+
*/
|
|
108
|
+
var mysqlJobSchemaStatements = (prefix = "") => {
|
|
109
|
+
const t = jobTables(prefix);
|
|
110
|
+
return [
|
|
111
|
+
`CREATE TABLE IF NOT EXISTS ${t.jobs} (
|
|
112
|
+
id VARCHAR(191) NOT NULL,
|
|
113
|
+
space_id BIGINT NOT NULL,
|
|
114
|
+
target_kind VARCHAR(16) NOT NULL,
|
|
115
|
+
target_name VARCHAR(191) NOT NULL,
|
|
116
|
+
target MEDIUMTEXT NOT NULL,
|
|
117
|
+
environment VARCHAR(64) NOT NULL,
|
|
118
|
+
input MEDIUMTEXT NOT NULL,
|
|
119
|
+
due_at BIGINT NOT NULL,
|
|
120
|
+
max_attempts INT NOT NULL,
|
|
121
|
+
missed INT NULL,
|
|
122
|
+
job_key VARCHAR(191) NULL,
|
|
123
|
+
status VARCHAR(16) NOT NULL,
|
|
124
|
+
run_at BIGINT NOT NULL,
|
|
125
|
+
attempts INT NOT NULL DEFAULT 0,
|
|
126
|
+
lease_until BIGINT NULL,
|
|
127
|
+
worker_id VARCHAR(191) NULL,
|
|
128
|
+
run_id VARCHAR(191) NULL,
|
|
129
|
+
cancel_requested TINYINT(1) NOT NULL DEFAULT 0,
|
|
130
|
+
created_at BIGINT NOT NULL,
|
|
131
|
+
updated_at BIGINT NOT NULL,
|
|
132
|
+
error TEXT NULL,
|
|
133
|
+
history MEDIUMTEXT NOT NULL,
|
|
134
|
+
expires_at BIGINT NULL,
|
|
135
|
+
state MEDIUMTEXT NULL,
|
|
136
|
+
progress TEXT NULL,
|
|
137
|
+
result MEDIUMTEXT NULL,
|
|
138
|
+
pause_requested TINYINT(1) NOT NULL DEFAULT 0,
|
|
139
|
+
active_ms BIGINT NOT NULL DEFAULT 0,
|
|
140
|
+
holder_memory_mb INT NULL,
|
|
141
|
+
needs_memory_mb INT NULL,
|
|
142
|
+
near_memory_limit TINYINT(1) NOT NULL DEFAULT 0,
|
|
143
|
+
PRIMARY KEY (id),
|
|
144
|
+
KEY action_jobs_pending (status, run_at),
|
|
145
|
+
KEY action_jobs_lease (status, lease_until),
|
|
146
|
+
KEY action_jobs_space (space_id, updated_at),
|
|
147
|
+
KEY action_jobs_target (space_id, target_name, updated_at),
|
|
148
|
+
KEY action_jobs_key (space_id, job_key, status),
|
|
149
|
+
KEY action_jobs_expires (expires_at),
|
|
150
|
+
KEY action_jobs_due (due_at),
|
|
151
|
+
KEY action_jobs_updated (updated_at)
|
|
152
|
+
) ${CHARSET}`,
|
|
153
|
+
`CREATE TABLE IF NOT EXISTS ${t.schedules} (
|
|
154
|
+
space_id BIGINT NOT NULL,
|
|
155
|
+
action_id VARCHAR(191) NOT NULL,
|
|
156
|
+
cron VARCHAR(191) NOT NULL,
|
|
157
|
+
timezone VARCHAR(64) NULL,
|
|
158
|
+
environment VARCHAR(64) NOT NULL,
|
|
159
|
+
enabled TINYINT(1) NOT NULL,
|
|
160
|
+
next_run_at BIGINT NOT NULL,
|
|
161
|
+
last_fire_at BIGINT NULL,
|
|
162
|
+
missed INT NOT NULL DEFAULT 0,
|
|
163
|
+
max_attempts INT NOT NULL,
|
|
164
|
+
updated_at BIGINT NOT NULL,
|
|
165
|
+
PRIMARY KEY (space_id, action_id),
|
|
166
|
+
KEY action_schedules_due (enabled, next_run_at)
|
|
167
|
+
) ${CHARSET}`,
|
|
168
|
+
`CREATE TABLE IF NOT EXISTS ${t.kv} (
|
|
169
|
+
k VARBINARY(764) NOT NULL,
|
|
170
|
+
v MEDIUMTEXT NOT NULL,
|
|
171
|
+
expires_at BIGINT NULL,
|
|
172
|
+
PRIMARY KEY (k),
|
|
173
|
+
KEY action_kv_expires (expires_at)
|
|
174
|
+
) ${CHARSET}`
|
|
175
|
+
];
|
|
176
|
+
};
|
|
177
|
+
/** The server's now, in epoch ms, as an SQL expression — what every comparison reads instead of a caller's clock. */
|
|
178
|
+
var NOW_MS = "CAST(ROUND(UNIX_TIMESTAMP(NOW(3)) * 1000) AS SIGNED)";
|
|
179
|
+
/** Creates the tables once per process, on first use; a failure is retried by the next call rather than remembered. */
|
|
180
|
+
var ensureJobTables = (db, prefix, create) => {
|
|
181
|
+
let ready;
|
|
182
|
+
return async () => {
|
|
183
|
+
if (!create) return;
|
|
184
|
+
ready ??= (async () => {
|
|
185
|
+
for (const statement of mysqlJobSchemaStatements(prefix)) await execute(db, statement);
|
|
186
|
+
})().catch((error) => {
|
|
187
|
+
ready = void 0;
|
|
188
|
+
throw error;
|
|
189
|
+
});
|
|
190
|
+
await ready;
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
// src/mysql/summary.ts
|
|
194
|
+
var TRIGGER = "JSON_UNQUOTE(JSON_EXTRACT(target, '$.trigger'))";
|
|
195
|
+
var WAITING = "status = 'pending'";
|
|
196
|
+
var NEEDING = "status IN ('pending', 'paused')";
|
|
197
|
+
/**
|
|
198
|
+
* The jobs table at a glance (`JobQueue.summarize`), counted by MySQL: every status, what waits by what it is, and the
|
|
199
|
+
* spaces with the most waiting — with what the job of each touched last said.
|
|
200
|
+
*/
|
|
201
|
+
var summarizeJobsTable = async (conn, table, spaces) => {
|
|
202
|
+
const [statuses, kinds, bySpace, needing] = await Promise.all([
|
|
203
|
+
selectRows(conn, `SELECT status, COUNT(*) AS n FROM ${table} GROUP BY status`, []),
|
|
204
|
+
selectRows(conn, `SELECT target_kind AS kind, ${TRIGGER} AS trig, COUNT(*) AS n, MIN(due_at) AS oldest
|
|
205
|
+
FROM ${table} WHERE ${WAITING} GROUP BY target_kind, trig`, []),
|
|
206
|
+
selectRows(conn, `SELECT j.space_id, COUNT(*) AS waiting, SUM(JSON_UNQUOTE(JSON_EXTRACT(j.target, '$.trigger')) = 'call') AS calls,
|
|
207
|
+
MIN(j.due_at) AS oldest,
|
|
208
|
+
(SELECT l.error FROM ${table} l WHERE l.space_id = j.space_id AND l.${WAITING}
|
|
209
|
+
ORDER BY l.updated_at DESC LIMIT 1) AS last_error
|
|
210
|
+
FROM ${table} j WHERE j.${WAITING}
|
|
211
|
+
GROUP BY j.space_id ORDER BY waiting DESC, oldest ASC LIMIT ?`, [spaces]),
|
|
212
|
+
selectRows(conn, `SELECT status, COUNT(*) AS n, MAX(needs_memory_mb) AS most
|
|
213
|
+
FROM ${table} WHERE ${NEEDING} AND needs_memory_mb IS NOT NULL GROUP BY status`, [])
|
|
214
|
+
]);
|
|
215
|
+
const waitingForMemory = needing.find((row) => row.status === "pending");
|
|
216
|
+
const pausedForMemory = needing.find((row) => row.status === "paused");
|
|
217
|
+
const byStatus = noJobsByStatus();
|
|
218
|
+
statuses.forEach((row) => {
|
|
219
|
+
byStatus[row.status] = Number(row.n);
|
|
220
|
+
});
|
|
221
|
+
const waiting = {
|
|
222
|
+
calls: 0,
|
|
223
|
+
schedules: 0,
|
|
224
|
+
later: 0,
|
|
225
|
+
functionJobs: 0,
|
|
226
|
+
other: 0
|
|
227
|
+
};
|
|
228
|
+
let oldestDueAt;
|
|
229
|
+
kinds.forEach((row) => {
|
|
230
|
+
waiting[waitingKindOf(row.kind, row.trig)] += Number(row.n);
|
|
231
|
+
oldestDueAt = oldestDueAt === void 0 ? Number(row.oldest) : Math.min(oldestDueAt, Number(row.oldest));
|
|
232
|
+
});
|
|
233
|
+
return {
|
|
234
|
+
byStatus,
|
|
235
|
+
waiting,
|
|
236
|
+
...oldestDueAt === void 0 ? {} : { oldestDueAt },
|
|
237
|
+
needingMemory: {
|
|
238
|
+
waiting: Number(waitingForMemory?.n ?? 0),
|
|
239
|
+
paused: Number(pausedForMemory?.n ?? 0),
|
|
240
|
+
...waitingForMemory ? { mostMb: Number(waitingForMemory.most) } : {}
|
|
241
|
+
},
|
|
242
|
+
spaces: bySpace.map((row) => ({
|
|
243
|
+
spaceId: Number(row.space_id),
|
|
244
|
+
waiting: Number(row.waiting),
|
|
245
|
+
calls: Number(row.calls ?? 0),
|
|
246
|
+
oldestDueAt: Number(row.oldest),
|
|
247
|
+
...row.last_error ? { lastError: row.last_error } : {}
|
|
248
|
+
}))
|
|
249
|
+
};
|
|
250
|
+
};
|
|
251
|
+
// src/mysql/jobQueue.ts
|
|
252
|
+
/** Spread into a plain array: the queries take a mutable list. */
|
|
253
|
+
var TERMINAL = [...TERMINAL_JOB_STATUSES];
|
|
254
|
+
var DAY_MS = 864e5;
|
|
255
|
+
/** How often finished jobs past their retention are removed — at most once a minute per process, on a write. */
|
|
256
|
+
var PURGE_EVERY_MS = 6e4;
|
|
257
|
+
/** MySQL's answer when two transactions wait on each other: one is rolled back, and is meant to be run again. */
|
|
258
|
+
var DEADLOCK = "ER_LOCK_DEADLOCK";
|
|
259
|
+
var TRANSACTION_ATTEMPTS = 3;
|
|
260
|
+
/** Claim rounds per call: a worker that lost every row it read to other workers looks once more, then waits a poll. */
|
|
261
|
+
var CLAIM_ROUNDS = 3;
|
|
262
|
+
/** Lapsed jobs reaped per claim: the rest are reaped by the next one, a poll later. */
|
|
263
|
+
var REAP_ROWS = 50;
|
|
264
|
+
/**
|
|
265
|
+
* One connection, one transaction: what a settlement or a schedule write needs so the rows it read stay locked until
|
|
266
|
+
* it writes. A deadlock is retried — MySQL picks a victim and expects it to try again, which is what two replicas
|
|
267
|
+
* reconciling the same space at boot will occasionally make it do.
|
|
268
|
+
*/
|
|
269
|
+
var transaction = async (pool, work) => {
|
|
270
|
+
for (let attempt = 1;; attempt += 1) {
|
|
271
|
+
const connection = await pool.getConnection();
|
|
272
|
+
try {
|
|
273
|
+
await connection.beginTransaction();
|
|
274
|
+
const result = await work(connection);
|
|
275
|
+
await connection.commit();
|
|
276
|
+
return result;
|
|
277
|
+
} catch (error) {
|
|
278
|
+
await connection.rollback();
|
|
279
|
+
if (error.code !== DEADLOCK || attempt >= TRANSACTION_ATTEMPTS) throw error;
|
|
280
|
+
} finally {
|
|
281
|
+
connection.release();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
/** MySQL's code for a primary key that refused a second row with the same value. */
|
|
286
|
+
var DUPLICATE_ENTRY = "ER_DUP_ENTRY";
|
|
287
|
+
/**
|
|
288
|
+
* An {@link JobQueue} over tables in a MySQL database the deployment owns. Tested on MySQL 8; nothing in it
|
|
289
|
+
* needs more than 5.7.
|
|
290
|
+
*
|
|
291
|
+
* The helper for a deployment that already runs MySQL: it borrows connections from the pool it is handed, and creates
|
|
292
|
+
* its three tables on first use unless told not to. Every replica pointed at the same database shares the jobs and the
|
|
293
|
+
* schedules.
|
|
294
|
+
*
|
|
295
|
+
* ```ts
|
|
296
|
+
* import mysql from 'mysql2/promise';
|
|
297
|
+
* import { createMysqlJobQueue, createMysqlKv } from '@plitzi/sdk-actions/mysql';
|
|
298
|
+
*
|
|
299
|
+
* const pool = mysql.createPool(process.env.DATABASE_URL);
|
|
300
|
+
* createServer({ action: { lookups, kv: createMysqlKv({ pool }), jobs: { queue: createMysqlJobQueue({ pool }) } } });
|
|
301
|
+
* ```
|
|
302
|
+
*
|
|
303
|
+
* The contract's rules, as MySQL keeps them: every instant is the SERVER's (`NOW(3)`), `enqueue` is idempotent by the
|
|
304
|
+
* primary key, `claim` takes each job with a single-row compare-and-set — so two workers never take the same one —
|
|
305
|
+
* and reaps a lapsed lease in the same write, and a schedule advances by compare-and-set too.
|
|
306
|
+
*/
|
|
307
|
+
var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retentionDays = 90 }) => {
|
|
308
|
+
const t = jobTables(tablePrefix);
|
|
309
|
+
const ready = ensureJobTables(pool, tablePrefix, createTables);
|
|
310
|
+
const clock = createStoreClock(async () => {
|
|
311
|
+
const row = await selectOne(pool, `SELECT ${NOW_MS} AS now`);
|
|
312
|
+
return row ? Number(row.now) : Date.now();
|
|
313
|
+
});
|
|
314
|
+
const db = async () => {
|
|
315
|
+
await ready();
|
|
316
|
+
return pool;
|
|
317
|
+
};
|
|
318
|
+
const expiryOf = (at) => at + retentionDays * DAY_MS;
|
|
319
|
+
let purgedAt = 0;
|
|
320
|
+
const purge = async (at) => {
|
|
321
|
+
if (at - purgedAt < PURGE_EVERY_MS) return;
|
|
322
|
+
purgedAt = at;
|
|
323
|
+
await execute(pool, `DELETE FROM ${t.jobs} WHERE expires_at IS NOT NULL AND expires_at < ? LIMIT 1000`, [at]);
|
|
324
|
+
};
|
|
325
|
+
const inSpaces = (spaceIds) => spaceIds.length > 0;
|
|
326
|
+
return {
|
|
327
|
+
resyncClock: clock.resync,
|
|
328
|
+
now: async () => new Date(await clock.now()),
|
|
329
|
+
enqueue: async (job) => {
|
|
330
|
+
const conn = await db();
|
|
331
|
+
const at = await clock.now();
|
|
332
|
+
try {
|
|
333
|
+
await execute(conn, `INSERT INTO ${t.jobs} (id, space_id, target_kind, target_name, target, environment, input, due_at,
|
|
334
|
+
max_attempts, missed, job_key, needs_memory_mb, status, run_at, attempts, created_at, updated_at, history)
|
|
335
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, 0, ?, ?, '[]')`, [
|
|
336
|
+
job.id,
|
|
337
|
+
job.spaceId,
|
|
338
|
+
job.target.kind,
|
|
339
|
+
job.target.name,
|
|
340
|
+
JSON.stringify(job.target),
|
|
341
|
+
job.environment,
|
|
342
|
+
JSON.stringify(job.input),
|
|
343
|
+
job.dueAt,
|
|
344
|
+
job.maxAttempts,
|
|
345
|
+
job.missed ?? null,
|
|
346
|
+
job.key ?? null,
|
|
347
|
+
job.needsMemoryMb ?? null,
|
|
348
|
+
job.dueAt,
|
|
349
|
+
at,
|
|
350
|
+
at
|
|
351
|
+
]);
|
|
352
|
+
return true;
|
|
353
|
+
} catch (error) {
|
|
354
|
+
if (error.code === DUPLICATE_ENTRY) return false;
|
|
355
|
+
throw error;
|
|
356
|
+
}
|
|
357
|
+
},
|
|
358
|
+
claim: async ({ workerId, leaseMs, limit, spaces, memory, takes }) => {
|
|
359
|
+
const conn = await db();
|
|
360
|
+
const at = await clock.now();
|
|
361
|
+
const taken = [];
|
|
362
|
+
const lapsed = await selectRows(conn, `SELECT * FROM ${t.jobs} WHERE status = 'running' AND lease_until < ? ORDER BY run_at LIMIT ?`, [at, REAP_ROWS]);
|
|
363
|
+
for (const row of lapsed) {
|
|
364
|
+
const job = toJob(row);
|
|
365
|
+
const holderMb = job.holderMemoryMb;
|
|
366
|
+
const outgrew = outgrewWorker(job);
|
|
367
|
+
const history = [...job.history, {
|
|
368
|
+
attempt: job.history.length + 1,
|
|
369
|
+
status: "lost",
|
|
370
|
+
startedAt: job.updatedAt,
|
|
371
|
+
endedAt: at,
|
|
372
|
+
workerId: job.workerId ?? "unknown",
|
|
373
|
+
error: LOST_ERROR,
|
|
374
|
+
...holderMb === void 0 ? {} : { memoryMb: holderMb },
|
|
375
|
+
...job.nearMemoryLimit ? { nearMemoryLimit: job.nearMemoryLimit } : {}
|
|
376
|
+
}];
|
|
377
|
+
await execute(conn, `UPDATE ${t.jobs} SET status = 'pending', worker_id = NULL, lease_until = NULL, holder_memory_mb = NULL,
|
|
378
|
+
near_memory_limit = 0, needs_memory_mb = ?, error = ?, history = ?, updated_at = ?
|
|
379
|
+
WHERE id = ? AND status = 'running' AND updated_at = ? AND lease_until < ?`, [
|
|
380
|
+
needsAfterLoss(job.needsMemoryMb, holderMb, outgrew) ?? null,
|
|
381
|
+
lostError(holderMb, outgrew),
|
|
382
|
+
JSON.stringify(history),
|
|
383
|
+
at,
|
|
384
|
+
job.id,
|
|
385
|
+
job.updatedAt,
|
|
386
|
+
at
|
|
387
|
+
]);
|
|
388
|
+
}
|
|
389
|
+
if (memory) await execute(conn, `UPDATE ${t.jobs} SET status = 'paused', error = CONCAT(?, needs_memory_mb - 1, ?, ?, ?), updated_at = ?
|
|
390
|
+
WHERE status = 'pending' AND needs_memory_mb > ?`, [
|
|
391
|
+
...SET_ASIDE_WORDS.slice(0, 2),
|
|
392
|
+
String(memory.ceilingMb),
|
|
393
|
+
SET_ASIDE_WORDS[2],
|
|
394
|
+
at,
|
|
395
|
+
memory.ceilingMb
|
|
396
|
+
]);
|
|
397
|
+
/**
|
|
398
|
+
* Read, then take each job with ONE single-row update that only lands if the row is still the version that was
|
|
399
|
+
* read — due, waiting, and not written since. Two workers reading the same candidates each get the rows they
|
|
400
|
+
* win and skip the rest.
|
|
401
|
+
*
|
|
402
|
+
* Not `SELECT … FOR UPDATE SKIP LOCKED` in a transaction: the locks that takes on the status index cross with
|
|
403
|
+
* the ones the updates need, and two replicas claiming at once deadlock. A single-row update by primary key
|
|
404
|
+
* holds one lock and cannot.
|
|
405
|
+
*/
|
|
406
|
+
for (let round = 0; round < CLAIM_ROUNDS && taken.length < limit; round += 1) {
|
|
407
|
+
const where = claimable(at, spaces, memory?.takesNeeding === false ? void 0 : memory?.mb, takes);
|
|
408
|
+
const rows = await selectRows(conn, `SELECT * FROM ${t.jobs} WHERE ${where.sql} ORDER BY run_at LIMIT ?`, [...where.params, limit - taken.length]);
|
|
409
|
+
if (rows.length === 0) break;
|
|
410
|
+
for (const row of rows) {
|
|
411
|
+
const job = toJob(row);
|
|
412
|
+
if ((await execute(conn, `UPDATE ${t.jobs} SET status = 'running', worker_id = ?, lease_until = ?, updated_at = ?,
|
|
413
|
+
attempts = attempts + 1, holder_memory_mb = ?, near_memory_limit = 0
|
|
414
|
+
WHERE id = ? AND status = 'pending' AND updated_at = ? AND attempts = ? AND run_at <= ?`, [
|
|
415
|
+
workerId,
|
|
416
|
+
at + leaseMs,
|
|
417
|
+
at,
|
|
418
|
+
memory?.mb ?? null,
|
|
419
|
+
job.id,
|
|
420
|
+
job.updatedAt,
|
|
421
|
+
job.attempts,
|
|
422
|
+
at
|
|
423
|
+
])).affectedRows !== 1) continue;
|
|
424
|
+
taken.push({
|
|
425
|
+
...job,
|
|
426
|
+
status: "running",
|
|
427
|
+
workerId,
|
|
428
|
+
leaseUntil: at + leaseMs,
|
|
429
|
+
updatedAt: at,
|
|
430
|
+
attempts: job.attempts + 1,
|
|
431
|
+
...memory ? { holderMemoryMb: memory.mb } : {}
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return taken;
|
|
436
|
+
},
|
|
437
|
+
heartbeat: async ({ jobIds, workerId, leaseMs, nearMemoryLimit }) => {
|
|
438
|
+
if (jobIds.length === 0) return [];
|
|
439
|
+
const conn = await db();
|
|
440
|
+
const at = await clock.now();
|
|
441
|
+
await execute(conn, `UPDATE ${t.jobs} SET lease_until = ?${nearMemoryLimit ? ", near_memory_limit = 1" : ""}
|
|
442
|
+
WHERE id IN (?) AND worker_id = ? AND status = 'running'`, [
|
|
443
|
+
at + leaseMs,
|
|
444
|
+
jobIds,
|
|
445
|
+
workerId
|
|
446
|
+
]);
|
|
447
|
+
return (await selectRows(conn, `SELECT id, cancel_requested FROM ${t.jobs} WHERE id IN (?) AND worker_id = ? AND status = 'running'
|
|
448
|
+
AND (cancel_requested = 1 OR pause_requested = 1)`, [jobIds, workerId])).map((row) => ({
|
|
449
|
+
jobId: row.id,
|
|
450
|
+
stop: Number(row.cancel_requested) === 1 ? "cancel" : "pause"
|
|
451
|
+
}));
|
|
452
|
+
},
|
|
453
|
+
write: async ({ jobId, workerId, state, progress }) => {
|
|
454
|
+
const conn = await db();
|
|
455
|
+
const at = await clock.now();
|
|
456
|
+
const sets = [
|
|
457
|
+
"updated_at = ?",
|
|
458
|
+
...state === void 0 ? [] : ["state = ?"],
|
|
459
|
+
...progress ? ["progress = ?"] : []
|
|
460
|
+
];
|
|
461
|
+
return (await execute(conn, `UPDATE ${t.jobs} SET ${sets.join(", ")} WHERE id = ? AND worker_id = ? AND status = 'running'`, [
|
|
462
|
+
at,
|
|
463
|
+
...state === void 0 ? [] : [JSON.stringify(state)],
|
|
464
|
+
...progress ? [JSON.stringify({
|
|
465
|
+
...progress,
|
|
466
|
+
at
|
|
467
|
+
})] : [],
|
|
468
|
+
jobId,
|
|
469
|
+
workerId
|
|
470
|
+
])).affectedRows === 1;
|
|
471
|
+
},
|
|
472
|
+
settle: async ({ jobId, workerId, status, delayMs, runId, error, attempt, result, spentMs, refund = status === "pending" && !attempt }) => {
|
|
473
|
+
await db();
|
|
474
|
+
const at = await clock.now();
|
|
475
|
+
await transaction(pool, async (connection) => {
|
|
476
|
+
const row = await selectOne(connection, `SELECT * FROM ${t.jobs} WHERE id = ? AND worker_id = ? FOR UPDATE`, [jobId, workerId]);
|
|
477
|
+
if (!row) return;
|
|
478
|
+
const job = toJob(row);
|
|
479
|
+
const history = attempt ? [...job.history, {
|
|
480
|
+
...attempt,
|
|
481
|
+
attempt: job.history.length + 1,
|
|
482
|
+
startedAt: job.updatedAt,
|
|
483
|
+
endedAt: at
|
|
484
|
+
}] : job.history;
|
|
485
|
+
const settled = status === "pending" && job.cancelRequested ? "cancelled" : status === "pending" && job.pauseRequested ? "paused" : status;
|
|
486
|
+
const attempts = refund ? Math.max(0, job.attempts - 1) : job.attempts;
|
|
487
|
+
const waiting = settled === "pending" || settled === "paused";
|
|
488
|
+
await execute(connection, `UPDATE ${t.jobs} SET status = ?, updated_at = ?, lease_until = NULL, error = ?, run_id = COALESCE(?, run_id),
|
|
489
|
+
run_at = ?, worker_id = ?, attempts = ?, history = ?, expires_at = ?, cancel_requested = 0,
|
|
490
|
+
pause_requested = 0, result = COALESCE(?, result), active_ms = active_ms + ? WHERE id = ?`, [
|
|
491
|
+
settled,
|
|
492
|
+
at,
|
|
493
|
+
error ?? null,
|
|
494
|
+
runId ?? null,
|
|
495
|
+
settled === "pending" ? at + (delayMs ?? 0) : job.runAt,
|
|
496
|
+
waiting ? null : workerId,
|
|
497
|
+
attempts,
|
|
498
|
+
JSON.stringify(history),
|
|
499
|
+
TERMINAL.includes(settled) ? expiryOf(at) : null,
|
|
500
|
+
jsonOrNull(result),
|
|
501
|
+
spentMs ?? 0,
|
|
502
|
+
jobId
|
|
503
|
+
]);
|
|
504
|
+
});
|
|
505
|
+
await purge(at);
|
|
506
|
+
},
|
|
507
|
+
dueSchedules: async (limit) => {
|
|
508
|
+
const conn = await db();
|
|
509
|
+
const at = await clock.now();
|
|
510
|
+
return (await selectRows(conn, `SELECT * FROM ${t.schedules} WHERE enabled = 1 AND next_run_at <= ? ORDER BY next_run_at LIMIT ?`, [at, limit])).map(toSchedule);
|
|
511
|
+
},
|
|
512
|
+
advanceSchedule: async ({ spaceId, actionId, from, to, missed }) => {
|
|
513
|
+
const conn = await db();
|
|
514
|
+
const at = await clock.now();
|
|
515
|
+
return (await execute(conn, `UPDATE ${t.schedules} SET next_run_at = ?, last_fire_at = ?, updated_at = ?, missed = missed + ?
|
|
516
|
+
WHERE space_id = ? AND action_id = ? AND next_run_at = ?`, [
|
|
517
|
+
to,
|
|
518
|
+
from,
|
|
519
|
+
at,
|
|
520
|
+
missed,
|
|
521
|
+
spaceId,
|
|
522
|
+
actionId,
|
|
523
|
+
from
|
|
524
|
+
])).affectedRows === 1;
|
|
525
|
+
},
|
|
526
|
+
putSchedules: async ({ spaceId, schedules: incoming }) => {
|
|
527
|
+
await db();
|
|
528
|
+
const at = await clock.now();
|
|
529
|
+
await transaction(pool, async (connection) => {
|
|
530
|
+
for (const schedule of incoming)
|
|
531
|
+
/**
|
|
532
|
+
* `next_run_at` FIRST: MySQL applies these assignments left to right, each seeing the ones before it, so
|
|
533
|
+
* the comparison has to read the old expression before `cron` is overwritten. A fire already promised for
|
|
534
|
+
* an unchanged expression is kept — recomputing it on every save would push a busy space's schedule forward
|
|
535
|
+
* forever. `VALUES()` rather than a row alias, which MariaDB does not have.
|
|
536
|
+
*/
|
|
537
|
+
await execute(connection, `INSERT INTO ${t.schedules} (space_id, action_id, cron, timezone, environment, enabled, next_run_at,
|
|
538
|
+
missed, max_attempts, updated_at)
|
|
539
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
|
|
540
|
+
ON DUPLICATE KEY UPDATE
|
|
541
|
+
next_run_at = IF(cron = VALUES(cron) AND timezone <=> VALUES(timezone)
|
|
542
|
+
AND environment = VALUES(environment), next_run_at, VALUES(next_run_at)),
|
|
543
|
+
cron = VALUES(cron), timezone = VALUES(timezone), environment = VALUES(environment),
|
|
544
|
+
enabled = VALUES(enabled), max_attempts = VALUES(max_attempts), updated_at = VALUES(updated_at)`, [
|
|
545
|
+
spaceId,
|
|
546
|
+
schedule.actionId,
|
|
547
|
+
schedule.cron,
|
|
548
|
+
schedule.timezone ?? null,
|
|
549
|
+
schedule.environment,
|
|
550
|
+
schedule.enabled ? 1 : 0,
|
|
551
|
+
schedule.nextRunAt,
|
|
552
|
+
schedule.maxAttempts,
|
|
553
|
+
at
|
|
554
|
+
]);
|
|
555
|
+
const kept = incoming.map((schedule) => schedule.actionId);
|
|
556
|
+
await execute(connection, kept.length > 0 ? `DELETE FROM ${t.schedules} WHERE space_id = ? AND action_id NOT IN (?)` : `DELETE FROM ${t.schedules} WHERE space_id = ?`, kept.length > 0 ? [spaceId, kept] : [spaceId]);
|
|
557
|
+
});
|
|
558
|
+
},
|
|
559
|
+
listJobs: async ({ spaceIds, name, status, kind, limit, offset }) => {
|
|
560
|
+
if (!inSpaces(spaceIds)) return {
|
|
561
|
+
jobs: [],
|
|
562
|
+
total: 0
|
|
563
|
+
};
|
|
564
|
+
const conn = await db();
|
|
565
|
+
const where = [
|
|
566
|
+
"space_id IN (?)",
|
|
567
|
+
...name ? ["target_name = ?"] : [],
|
|
568
|
+
...status ? ["status = ?"] : [],
|
|
569
|
+
...kind ? ["target_kind = ?"] : []
|
|
570
|
+
].join(" AND ");
|
|
571
|
+
const params = [
|
|
572
|
+
spaceIds,
|
|
573
|
+
...name ? [name] : [],
|
|
574
|
+
...status ? [status] : [],
|
|
575
|
+
...kind ? [kind] : []
|
|
576
|
+
];
|
|
577
|
+
const [rows, count] = await Promise.all([selectRows(conn, `SELECT * FROM ${t.jobs} WHERE ${where} ORDER BY updated_at DESC, id DESC LIMIT ? OFFSET ?`, [
|
|
578
|
+
...params,
|
|
579
|
+
limit,
|
|
580
|
+
offset
|
|
581
|
+
]), selectOne(conn, `SELECT COUNT(*) AS total FROM ${t.jobs} WHERE ${where}`, params)]);
|
|
582
|
+
return {
|
|
583
|
+
jobs: rows.map(toJob),
|
|
584
|
+
total: Number(count?.total ?? 0)
|
|
585
|
+
};
|
|
586
|
+
},
|
|
587
|
+
countDue: async ({ spaces, memoryMb } = {}) => {
|
|
588
|
+
const conn = await db();
|
|
589
|
+
const where = claimable(await clock.now(), spaces, memoryMb);
|
|
590
|
+
const row = await selectOne(conn, `SELECT COUNT(*) AS n FROM ${t.jobs} WHERE ${where.sql}`, where.params);
|
|
591
|
+
return Number(row?.n ?? 0);
|
|
592
|
+
},
|
|
593
|
+
listAcross: async ({ statuses, limit, order }) => {
|
|
594
|
+
if (statuses.length === 0) return [];
|
|
595
|
+
return (await selectRows(await db(), `SELECT * FROM ${t.jobs} WHERE status IN (?) ORDER BY ${order === "due" ? "run_at ASC" : "updated_at DESC"}, id LIMIT ?`, [statuses, limit])).map(toJob);
|
|
596
|
+
},
|
|
597
|
+
summarize: async ({ spaces = 10 } = {}) => summarizeJobsTable(await db(), t.jobs, spaces),
|
|
598
|
+
flow: async ({ from, to }) => {
|
|
599
|
+
const rows = await selectRows(await db(), `SELECT due_at, history, status, updated_at, attempts FROM ${t.jobs}
|
|
600
|
+
WHERE (due_at >= ? AND due_at < ?) OR updated_at >= ?`, [
|
|
601
|
+
from,
|
|
602
|
+
to,
|
|
603
|
+
from
|
|
604
|
+
]);
|
|
605
|
+
return flowOf(rows.map((row) => ({
|
|
606
|
+
dueAt: Number(row.due_at),
|
|
607
|
+
history: JSON.parse(row.history),
|
|
608
|
+
status: row.status,
|
|
609
|
+
updatedAt: Number(row.updated_at),
|
|
610
|
+
attempts: Number(row.attempts)
|
|
611
|
+
})), from, to);
|
|
612
|
+
},
|
|
613
|
+
getJob: async (spaceIds, jobId) => {
|
|
614
|
+
if (!inSpaces(spaceIds)) return;
|
|
615
|
+
const row = await selectOne(await db(), `SELECT * FROM ${t.jobs} WHERE id = ? AND space_id IN (?)`, [jobId, spaceIds]);
|
|
616
|
+
return row ? toJob(row) : void 0;
|
|
617
|
+
},
|
|
618
|
+
listSchedules: async (spaceIds) => {
|
|
619
|
+
if (!inSpaces(spaceIds)) return [];
|
|
620
|
+
return (await selectRows(await db(), `SELECT * FROM ${t.schedules} WHERE space_id IN (?) ORDER BY next_run_at`, [spaceIds])).map(toSchedule);
|
|
621
|
+
},
|
|
622
|
+
requeue: async (spaceIds, jobId, { input, fresh = false } = {}) => {
|
|
623
|
+
if (!inSpaces(spaceIds)) return false;
|
|
624
|
+
const conn = await db();
|
|
625
|
+
const at = await clock.now();
|
|
626
|
+
return (await execute(conn, `UPDATE ${t.jobs} SET status = 'pending', run_at = ?, attempts = 0, updated_at = ?, cancel_requested = 0,
|
|
627
|
+
pause_requested = 0, worker_id = NULL, lease_until = NULL, error = NULL, expires_at = NULL, result = NULL
|
|
628
|
+
${input ? ", input = ?" : ""}${fresh ? ", state = NULL, progress = NULL, active_ms = 0" : ""}
|
|
629
|
+
WHERE id = ? AND space_id IN (?) AND status IN (?)`, [
|
|
630
|
+
at,
|
|
631
|
+
at,
|
|
632
|
+
...input ? [JSON.stringify(input)] : [],
|
|
633
|
+
jobId,
|
|
634
|
+
spaceIds,
|
|
635
|
+
TERMINAL
|
|
636
|
+
])).affectedRows === 1;
|
|
637
|
+
},
|
|
638
|
+
cancel: async (spaceIds, jobId) => {
|
|
639
|
+
if (!inSpaces(spaceIds)) return false;
|
|
640
|
+
const conn = await db();
|
|
641
|
+
const at = await clock.now();
|
|
642
|
+
if ((await execute(conn, `UPDATE ${t.jobs} SET status = 'cancelled', updated_at = ?, expires_at = ?, worker_id = NULL, pause_requested = 0
|
|
643
|
+
WHERE id = ? AND space_id IN (?) AND status IN ('pending', 'paused')`, [
|
|
644
|
+
at,
|
|
645
|
+
expiryOf(at),
|
|
646
|
+
jobId,
|
|
647
|
+
spaceIds
|
|
648
|
+
])).affectedRows === 1) return true;
|
|
649
|
+
return (await execute(conn, `UPDATE ${t.jobs} SET cancel_requested = 1, updated_at = ? WHERE id = ? AND space_id IN (?) AND status = 'running'`, [
|
|
650
|
+
at,
|
|
651
|
+
jobId,
|
|
652
|
+
spaceIds
|
|
653
|
+
])).affectedRows === 1;
|
|
654
|
+
},
|
|
655
|
+
pause: async (spaceIds, jobId) => {
|
|
656
|
+
if (!inSpaces(spaceIds)) return false;
|
|
657
|
+
const conn = await db();
|
|
658
|
+
const at = await clock.now();
|
|
659
|
+
if ((await execute(conn, `UPDATE ${t.jobs} SET status = 'paused', updated_at = ?
|
|
660
|
+
WHERE id = ? AND space_id IN (?) AND target_kind = 'function' AND status = 'pending'`, [
|
|
661
|
+
at,
|
|
662
|
+
jobId,
|
|
663
|
+
spaceIds
|
|
664
|
+
])).affectedRows === 1) return true;
|
|
665
|
+
return (await execute(conn, `UPDATE ${t.jobs} SET pause_requested = 1, updated_at = ?
|
|
666
|
+
WHERE id = ? AND space_id IN (?) AND target_kind = 'function' AND status = 'running' AND pause_requested = 0`, [
|
|
667
|
+
at,
|
|
668
|
+
jobId,
|
|
669
|
+
spaceIds
|
|
670
|
+
])).affectedRows === 1;
|
|
671
|
+
},
|
|
672
|
+
resume: async (spaceIds, jobId) => {
|
|
673
|
+
if (!inSpaces(spaceIds)) return false;
|
|
674
|
+
const conn = await db();
|
|
675
|
+
const at = await clock.now();
|
|
676
|
+
return (await execute(conn, `UPDATE ${t.jobs} SET status = 'pending', run_at = ?, updated_at = ?,
|
|
677
|
+
attempts = IF(attempts >= max_attempts, 0, attempts)
|
|
678
|
+
WHERE id = ? AND space_id IN (?) AND status = 'paused'`, [
|
|
679
|
+
at,
|
|
680
|
+
at,
|
|
681
|
+
jobId,
|
|
682
|
+
spaceIds
|
|
683
|
+
])).affectedRows === 1;
|
|
684
|
+
},
|
|
685
|
+
cancelPending: async ({ spaceId, key, olderThan }) => {
|
|
686
|
+
const conn = await db();
|
|
687
|
+
const newest = olderThan === void 0 ? void 0 : await selectOne(conn, `SELECT id, created_at FROM ${t.jobs} WHERE id = ?`, [olderThan]);
|
|
688
|
+
const at = await clock.now();
|
|
689
|
+
return (await execute(conn, `UPDATE ${t.jobs} SET status = 'cancelled', updated_at = ?, expires_at = ?, worker_id = NULL
|
|
690
|
+
WHERE space_id = ? AND job_key = ? AND status = 'pending'${newest ? " AND (created_at < ? OR (created_at = ? AND id < ?))" : ""}`, [
|
|
691
|
+
at,
|
|
692
|
+
expiryOf(at),
|
|
693
|
+
spaceId,
|
|
694
|
+
key,
|
|
695
|
+
...newest ? [
|
|
696
|
+
newest.created_at,
|
|
697
|
+
newest.created_at,
|
|
698
|
+
newest.id
|
|
699
|
+
] : []
|
|
700
|
+
])).affectedRows;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
};
|
|
704
|
+
// src/mysql/kv.ts
|
|
705
|
+
/** Alive by the SERVER's clock: a key past its lifetime answers nothing, whether or not it has been removed yet. */
|
|
706
|
+
var LIVE = `(expires_at IS NULL OR expires_at > ${NOW_MS})`;
|
|
707
|
+
/**
|
|
708
|
+
* An {@link ActionKvAdapter} over a table in a MySQL database the deployment owns.
|
|
709
|
+
*
|
|
710
|
+
* What the run guards' single-flight keys and the `kv` tasks' counters need from a store the replicas share: a TTL the
|
|
711
|
+
* store enforces and an increment nobody can race. The increment is one `INSERT … ON DUPLICATE KEY UPDATE`, which
|
|
712
|
+
* MySQL applies to the row under its lock — so two replicas counting at once both count.
|
|
713
|
+
*/
|
|
714
|
+
var createMysqlKv = ({ pool, tablePrefix = "", createTables = true }) => {
|
|
715
|
+
const { kv } = jobTables(tablePrefix);
|
|
716
|
+
const ready = ensureJobTables(pool, tablePrefix, createTables);
|
|
717
|
+
const db = async () => {
|
|
718
|
+
await ready();
|
|
719
|
+
return pool;
|
|
720
|
+
};
|
|
721
|
+
/** Expired rows are removed as they are overwritten or read past; a table of used-once keys is swept here too. */
|
|
722
|
+
let sweptAt = 0;
|
|
723
|
+
const sweep = async () => {
|
|
724
|
+
if (Date.now() - sweptAt < 6e4) return;
|
|
725
|
+
sweptAt = Date.now();
|
|
726
|
+
await execute(pool, `DELETE FROM ${kv} WHERE expires_at IS NOT NULL AND expires_at <= ${NOW_MS} LIMIT 1000`);
|
|
727
|
+
};
|
|
728
|
+
return {
|
|
729
|
+
get: async (key) => {
|
|
730
|
+
return (await selectOne(await db(), `SELECT v FROM ${kv} WHERE k = ? AND ${LIVE}`, [key]))?.v;
|
|
731
|
+
},
|
|
732
|
+
set: async (key, value, ttlSeconds) => {
|
|
733
|
+
const expiry = ttlSeconds === void 0 ? "NULL" : `${NOW_MS} + ?`;
|
|
734
|
+
await execute(await db(), `INSERT INTO ${kv} (k, v, expires_at) VALUES (?, ?, ${expiry})
|
|
735
|
+
ON DUPLICATE KEY UPDATE v = VALUES(v), expires_at = VALUES(expires_at)`, ttlSeconds === void 0 ? [key, value] : [
|
|
736
|
+
key,
|
|
737
|
+
value,
|
|
738
|
+
ttlSeconds * 1e3
|
|
739
|
+
]);
|
|
740
|
+
await sweep();
|
|
741
|
+
},
|
|
742
|
+
delete: async (key) => {
|
|
743
|
+
await execute(await db(), `DELETE FROM ${kv} WHERE k = ?`, [key]);
|
|
744
|
+
},
|
|
745
|
+
increment: async (key, amount) => {
|
|
746
|
+
const connection = await (await db()).getConnection();
|
|
747
|
+
try {
|
|
748
|
+
await connection.beginTransaction();
|
|
749
|
+
/**
|
|
750
|
+
* `v` FIRST: the assignments run left to right and each sees the ones before it, so the value has to be
|
|
751
|
+
* computed while `expires_at` still says whether the old one is alive. A lapsed counter starts again from
|
|
752
|
+
* zero, and without the lifetime it had. `+ 0` reads the text as a number, as Redis reads its strings.
|
|
753
|
+
*/
|
|
754
|
+
await execute(connection, `INSERT INTO ${kv} (k, v, expires_at) VALUES (?, CAST(? AS CHAR), NULL)
|
|
755
|
+
ON DUPLICATE KEY UPDATE
|
|
756
|
+
v = CAST(IF(${LIVE}, (v + 0) + ?, ?) AS CHAR),
|
|
757
|
+
expires_at = IF(${LIVE}, expires_at, NULL)`, [
|
|
758
|
+
key,
|
|
759
|
+
amount,
|
|
760
|
+
amount,
|
|
761
|
+
amount
|
|
762
|
+
]);
|
|
763
|
+
const row = await selectOne(connection, `SELECT v FROM ${kv} WHERE k = ?`, [key]);
|
|
764
|
+
await connection.commit();
|
|
765
|
+
return Number(row?.v ?? amount);
|
|
766
|
+
} catch (error) {
|
|
767
|
+
await connection.rollback();
|
|
768
|
+
throw error;
|
|
769
|
+
} finally {
|
|
770
|
+
connection.release();
|
|
771
|
+
}
|
|
772
|
+
},
|
|
773
|
+
expire: async (key, ttlSeconds) => {
|
|
774
|
+
await execute(await db(), `UPDATE ${kv} SET expires_at = ${NOW_MS} + ? WHERE k = ? AND ${LIVE}`, [ttlSeconds * 1e3, key]);
|
|
775
|
+
},
|
|
776
|
+
/**
|
|
777
|
+
* Each branch is ONE statement MySQL applies under the row's lock, so two writers racing for the same key cannot
|
|
778
|
+
* both win. `affectedRows` counts the rows MATCHED because mysql2 connects with `FOUND_ROWS`: without it, writing
|
|
779
|
+
* back the value a key already holds would read as a refusal. The comparison is on bytes — the table's collation
|
|
780
|
+
* ignores case and trailing spaces, and "unchanged" has to mean the same bytes.
|
|
781
|
+
*/
|
|
782
|
+
swap: async (key, expected, next, ttlSeconds) => {
|
|
783
|
+
const expiry = ttlSeconds === void 0 ? "NULL" : `${NOW_MS} + ?`;
|
|
784
|
+
const lifetime = ttlSeconds === void 0 ? [] : [ttlSeconds * 1e3];
|
|
785
|
+
const pool = await db();
|
|
786
|
+
if (expected !== void 0) return (await execute(pool, `UPDATE ${kv} SET v = ?, expires_at = ${expiry}
|
|
787
|
+
WHERE k = ? AND ${LIVE} AND CAST(v AS BINARY) = CAST(? AS BINARY)`, [
|
|
788
|
+
next,
|
|
789
|
+
...lifetime,
|
|
790
|
+
key,
|
|
791
|
+
expected
|
|
792
|
+
])).affectedRows === 1;
|
|
793
|
+
if ((await execute(pool, `UPDATE ${kv} SET v = ?, expires_at = ${expiry} WHERE k = ? AND NOT ${LIVE}`, [
|
|
794
|
+
next,
|
|
795
|
+
...lifetime,
|
|
796
|
+
key
|
|
797
|
+
])).affectedRows === 1) return true;
|
|
798
|
+
const inserted = await execute(pool, `INSERT IGNORE INTO ${kv} (k, v, expires_at) VALUES (?, ?, ${expiry})`, [
|
|
799
|
+
key,
|
|
800
|
+
next,
|
|
801
|
+
...lifetime
|
|
802
|
+
]);
|
|
803
|
+
await sweep();
|
|
804
|
+
return inserted.affectedRows === 1;
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
};
|
|
808
|
+
export { createMysqlJobQueue, createMysqlKv, mysqlJobSchemaStatements };
|