@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,779 @@
|
|
|
1
|
+
import { _ as flowOf, d as LOST_ERROR, f as LOST_MEMORY_WORDS, n as WAITING_STATUSES, o as noJobsByStatus, p as SET_ASIDE_WORDS, t as NEEDING_STATUSES, 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
|
+
// src/mongo/claimable.ts
|
|
5
|
+
/** What each kind of work is, as a filter (`JobTake`, `queueRules`' `takeOf`). */
|
|
6
|
+
var TAKES = {
|
|
7
|
+
light: {
|
|
8
|
+
"target.kind": "action",
|
|
9
|
+
"target.code": { $ne: true }
|
|
10
|
+
},
|
|
11
|
+
codeActions: {
|
|
12
|
+
"target.kind": "action",
|
|
13
|
+
"target.code": true
|
|
14
|
+
},
|
|
15
|
+
functionJobs: { "target.kind": "function" }
|
|
16
|
+
};
|
|
17
|
+
/** What a claim with these `spaces` and `memoryMb` takes at `at`: due and waiting, of its spaces — or a job a worker died
|
|
18
|
+
* running that this one may hold, whatever its spaces. */
|
|
19
|
+
var claimable = (at, spaces, memoryMb, takes) => ({
|
|
20
|
+
status: "pending",
|
|
21
|
+
runAt: { $lte: at },
|
|
22
|
+
...takes ? TAKES[takes] : {},
|
|
23
|
+
$or: [{
|
|
24
|
+
needsMemoryMb: { $exists: false },
|
|
25
|
+
...spaces ? { spaceId: "only" in spaces ? { $in: spaces.only } : { $nin: spaces.except } } : {}
|
|
26
|
+
}, ...memoryMb === void 0 ? [] : [{ needsMemoryMb: { $lte: memoryMb } }]]
|
|
27
|
+
});
|
|
28
|
+
// src/mongo/jobQueue.ts
|
|
29
|
+
/** Mongo's code for a unique index that refused a second document with the same key. */
|
|
30
|
+
var DUPLICATE_KEY$1 = 11e3;
|
|
31
|
+
/** Spread into a plain array: the queries take a mutable list. */
|
|
32
|
+
var TERMINAL = [...TERMINAL_JOB_STATUSES];
|
|
33
|
+
var DAY_MS = 864e5;
|
|
34
|
+
var resolveDb = (source) => typeof source === "function" ? source() : source;
|
|
35
|
+
var scheduleId = (spaceId, actionId) => `${spaceId}:${actionId}`;
|
|
36
|
+
/**
|
|
37
|
+
* A stored document as the contract shapes it: an optional field is absent, never `null`.
|
|
38
|
+
*
|
|
39
|
+
* Mongo keeps what a `$set` wrote, and clearing a field in an update pipeline writes `null` — so a released job would
|
|
40
|
+
* otherwise come back with `workerId: null`, which every reader typed as `string | undefined` gets wrong.
|
|
41
|
+
*/
|
|
42
|
+
var withoutNulls = (document) => Object.fromEntries(Object.entries(document).filter(([, value]) => value !== null));
|
|
43
|
+
var toJob = ({ _id, expiresAt: _expiresAt, ...rest }) => withoutNulls({
|
|
44
|
+
...rest,
|
|
45
|
+
id: _id
|
|
46
|
+
});
|
|
47
|
+
var toSchedule = ({ _id: _unused, ...rest }) => withoutNulls(rest);
|
|
48
|
+
/** The history entry a reclaim writes on behalf of a worker that never came back. */
|
|
49
|
+
var lostAttempt = (at) => ({ $concatArrays: ["$history", [{
|
|
50
|
+
attempt: { $add: [{ $size: "$history" }, 1] },
|
|
51
|
+
status: "lost",
|
|
52
|
+
startedAt: "$updatedAt",
|
|
53
|
+
endedAt: at,
|
|
54
|
+
workerId: { $ifNull: ["$workerId", "unknown"] },
|
|
55
|
+
error: LOST_ERROR,
|
|
56
|
+
memoryMb: "$holderMemoryMb",
|
|
57
|
+
nearMemoryLimit: "$nearMemoryLimit"
|
|
58
|
+
}]] });
|
|
59
|
+
/**
|
|
60
|
+
* Whether the job took the worker that held it down, and that worker said what it could hold: `outgrewWorker` — it
|
|
61
|
+
* neared its memory, or the attempt before was lost too — read over the document before its lost attempt is written.
|
|
62
|
+
*/
|
|
63
|
+
var outgrewSaid = { $and: [{ $ne: [{ $type: "$holderMemoryMb" }, "missing"] }, { $or: [{ $eq: ["$nearMemoryLimit", true] }, { $eq: [{ $arrayElemAt: [{ $ifNull: ["$history.status", []] }, -1] }, "lost"] }] }] };
|
|
64
|
+
/** `needsAfterLoss`, as Mongo computes it over the document. */
|
|
65
|
+
var needsAfterLossOf = { $cond: [
|
|
66
|
+
outgrewSaid,
|
|
67
|
+
{ $max: [{ $ifNull: ["$needsMemoryMb", 0] }, { $add: ["$holderMemoryMb", 1] }] },
|
|
68
|
+
"$needsMemoryMb"
|
|
69
|
+
] };
|
|
70
|
+
/** `lostError`, as Mongo composes it over the document. */
|
|
71
|
+
var lostErrorOf = { $cond: [
|
|
72
|
+
outgrewSaid,
|
|
73
|
+
{ $concat: [
|
|
74
|
+
LOST_MEMORY_WORDS[0],
|
|
75
|
+
{ $toString: "$holderMemoryMb" },
|
|
76
|
+
LOST_MEMORY_WORDS[1]
|
|
77
|
+
] },
|
|
78
|
+
LOST_ERROR
|
|
79
|
+
] };
|
|
80
|
+
/** `setAsideError`, as Mongo composes it over the document. */
|
|
81
|
+
var setAsideErrorOf = (ceilingMb) => ({ $concat: [
|
|
82
|
+
SET_ASIDE_WORDS[0],
|
|
83
|
+
{ $toString: { $subtract: ["$needsMemoryMb", 1] } },
|
|
84
|
+
SET_ASIDE_WORDS[1],
|
|
85
|
+
String(ceilingMb),
|
|
86
|
+
SET_ASIDE_WORDS[2]
|
|
87
|
+
] });
|
|
88
|
+
/**
|
|
89
|
+
* An {@link JobQueue} over two collections of a Mongo database the deployment owns.
|
|
90
|
+
*
|
|
91
|
+
* The helper for a deployment that already runs Mongo: it holds no connection of its own and creates nothing but the
|
|
92
|
+
* indexes its queries need, on first use. Every replica pointed at the same database shares the jobs and the
|
|
93
|
+
* schedules, which is what running more than one needs.
|
|
94
|
+
*
|
|
95
|
+
* ```ts
|
|
96
|
+
* import { createMongoJobQueue } from '@plitzi/sdk-actions/mongo';
|
|
97
|
+
*
|
|
98
|
+
* const queue = createMongoJobQueue({ db: client.db('app') });
|
|
99
|
+
* createServer({ action: { lookups, kv, jobs: { queue } } });
|
|
100
|
+
* ```
|
|
101
|
+
*
|
|
102
|
+
* The contract's rules, as Mongo keeps them: every instant is the SERVER's (`hello.localTime`), `enqueue` is idempotent
|
|
103
|
+
* by the job's `_id`, `claim` takes one document per `findOneAndUpdate` — the atomic unit — and reaps a lapsed lease in
|
|
104
|
+
* the same operation, and a schedule advances by compare-and-set on the instant that was read.
|
|
105
|
+
*/
|
|
106
|
+
var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 }) => {
|
|
107
|
+
const jobsName = names.jobs ?? "action_jobs";
|
|
108
|
+
const schedulesName = names.schedules ?? "action_schedules";
|
|
109
|
+
const jobsOf = () => resolveDb(db).collection(jobsName);
|
|
110
|
+
const schedulesOf = () => resolveDb(db).collection(schedulesName);
|
|
111
|
+
const clock = createStoreClock(async () => {
|
|
112
|
+
const { localTime } = await resolveDb(db).command({ hello: 1 });
|
|
113
|
+
return localTime ? localTime.getTime() : Date.now();
|
|
114
|
+
});
|
|
115
|
+
let ready;
|
|
116
|
+
/**
|
|
117
|
+
* The indexes the queue cannot work without, built once on first use.
|
|
118
|
+
*
|
|
119
|
+
* `claim` is the one that matters: it runs on every poll of every replica, and without an index over status and the
|
|
120
|
+
* two time fields it is a collection scan several times a second. The two branches of its `$or` are answered by one
|
|
121
|
+
* index each and merged already sorted.
|
|
122
|
+
*/
|
|
123
|
+
const build = async () => {
|
|
124
|
+
await Promise.all([
|
|
125
|
+
jobsOf().createIndex({
|
|
126
|
+
status: 1,
|
|
127
|
+
runAt: 1
|
|
128
|
+
}),
|
|
129
|
+
jobsOf().createIndex({
|
|
130
|
+
status: 1,
|
|
131
|
+
leaseUntil: 1
|
|
132
|
+
}),
|
|
133
|
+
jobsOf().createIndex({
|
|
134
|
+
spaceId: 1,
|
|
135
|
+
updatedAt: -1
|
|
136
|
+
}),
|
|
137
|
+
jobsOf().createIndex({
|
|
138
|
+
spaceId: 1,
|
|
139
|
+
"target.name": 1,
|
|
140
|
+
updatedAt: -1
|
|
141
|
+
}),
|
|
142
|
+
jobsOf().createIndex({
|
|
143
|
+
spaceId: 1,
|
|
144
|
+
key: 1,
|
|
145
|
+
status: 1
|
|
146
|
+
}, { partialFilterExpression: { key: { $exists: true } } }),
|
|
147
|
+
jobsOf().createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }),
|
|
148
|
+
jobsOf().createIndex({ dueAt: 1 }),
|
|
149
|
+
jobsOf().createIndex({ updatedAt: 1 }),
|
|
150
|
+
schedulesOf().createIndex({
|
|
151
|
+
enabled: 1,
|
|
152
|
+
nextRunAt: 1
|
|
153
|
+
}),
|
|
154
|
+
schedulesOf().createIndex({ spaceId: 1 })
|
|
155
|
+
]);
|
|
156
|
+
};
|
|
157
|
+
const collections = async () => {
|
|
158
|
+
ready ??= build().catch((error) => {
|
|
159
|
+
ready = void 0;
|
|
160
|
+
throw error;
|
|
161
|
+
});
|
|
162
|
+
await ready;
|
|
163
|
+
return {
|
|
164
|
+
jobs: jobsOf(),
|
|
165
|
+
schedules: schedulesOf()
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
/**
|
|
169
|
+
* A lapsed lease reaped — its worker died, its attempt written for it — and a job that needs more memory than the
|
|
170
|
+
* largest worker holds set aside, each document once however many claim at once: the filter is read again as each is
|
|
171
|
+
* written. Each asked first by a read of one id, and written only when there is one: a worker claims as each job
|
|
172
|
+
* ends, and a multi-document write on every claim — thirty a second a replica under load — fought the heartbeats for
|
|
173
|
+
* the same documents until leases lapsed, and live workers' jobs were reaped as lost and run again.
|
|
174
|
+
*/
|
|
175
|
+
const maintain = async (jobs, at, ceilingMb) => {
|
|
176
|
+
const lapsed = {
|
|
177
|
+
status: "running",
|
|
178
|
+
leaseUntil: { $lt: at }
|
|
179
|
+
};
|
|
180
|
+
if (await jobs.findOne(lapsed, { projection: { _id: 1 } })) await jobs.updateMany(lapsed, [{ $set: {
|
|
181
|
+
history: lostAttempt(at),
|
|
182
|
+
needsMemoryMb: needsAfterLossOf,
|
|
183
|
+
error: lostErrorOf,
|
|
184
|
+
status: "pending",
|
|
185
|
+
updatedAt: at
|
|
186
|
+
} }, { $unset: [
|
|
187
|
+
"workerId",
|
|
188
|
+
"leaseUntil",
|
|
189
|
+
"holderMemoryMb",
|
|
190
|
+
"nearMemoryLimit"
|
|
191
|
+
] }]);
|
|
192
|
+
const outgrown = {
|
|
193
|
+
status: "pending",
|
|
194
|
+
needsMemoryMb: { $gt: ceilingMb ?? Number.POSITIVE_INFINITY }
|
|
195
|
+
};
|
|
196
|
+
if (ceilingMb !== void 0 && await jobs.findOne(outgrown, { projection: { _id: 1 } })) await jobs.updateMany(outgrown, [{ $set: {
|
|
197
|
+
status: "paused",
|
|
198
|
+
error: setAsideErrorOf(ceilingMb),
|
|
199
|
+
updatedAt: at
|
|
200
|
+
} }]);
|
|
201
|
+
};
|
|
202
|
+
const expiryOf = (at) => new Date(at + retentionDays * DAY_MS);
|
|
203
|
+
return {
|
|
204
|
+
resyncClock: clock.resync,
|
|
205
|
+
now: async () => new Date(await clock.now()),
|
|
206
|
+
enqueue: async (job) => {
|
|
207
|
+
const { jobs } = await collections();
|
|
208
|
+
const at = await clock.now();
|
|
209
|
+
const { id, ...fields } = job;
|
|
210
|
+
const document = {
|
|
211
|
+
...fields,
|
|
212
|
+
_id: id,
|
|
213
|
+
status: "pending",
|
|
214
|
+
runAt: job.dueAt,
|
|
215
|
+
attempts: 0,
|
|
216
|
+
createdAt: at,
|
|
217
|
+
updatedAt: at,
|
|
218
|
+
history: []
|
|
219
|
+
};
|
|
220
|
+
try {
|
|
221
|
+
await jobs.insertOne(document);
|
|
222
|
+
return true;
|
|
223
|
+
} catch (error) {
|
|
224
|
+
if (error.code === DUPLICATE_KEY$1) return false;
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
claim: async ({ workerId, leaseMs, limit, spaces, memory, takes }) => {
|
|
229
|
+
const { jobs } = await collections();
|
|
230
|
+
const at = await clock.now();
|
|
231
|
+
const taken = [];
|
|
232
|
+
await maintain(jobs, at, memory?.ceilingMb);
|
|
233
|
+
for (let slot = 0; slot < limit; slot += 1) {
|
|
234
|
+
const claimed = await jobs.findOneAndUpdate(claimable(at, spaces, memory?.takesNeeding === false ? void 0 : memory?.mb, takes), [{ $set: {
|
|
235
|
+
status: "running",
|
|
236
|
+
workerId,
|
|
237
|
+
leaseUntil: at + leaseMs,
|
|
238
|
+
updatedAt: at,
|
|
239
|
+
attempts: { $add: ["$attempts", 1] },
|
|
240
|
+
...memory ? { holderMemoryMb: memory.mb } : {}
|
|
241
|
+
} }, { $unset: "nearMemoryLimit" }], {
|
|
242
|
+
sort: { runAt: 1 },
|
|
243
|
+
returnDocument: "after"
|
|
244
|
+
});
|
|
245
|
+
if (!claimed) break;
|
|
246
|
+
taken.push(toJob(claimed));
|
|
247
|
+
}
|
|
248
|
+
return taken;
|
|
249
|
+
},
|
|
250
|
+
heartbeat: async ({ jobIds, workerId, leaseMs, nearMemoryLimit }) => {
|
|
251
|
+
const { jobs } = await collections();
|
|
252
|
+
const at = await clock.now();
|
|
253
|
+
await jobs.updateMany({
|
|
254
|
+
_id: { $in: jobIds },
|
|
255
|
+
workerId,
|
|
256
|
+
status: "running"
|
|
257
|
+
}, { $set: {
|
|
258
|
+
leaseUntil: at + leaseMs,
|
|
259
|
+
...nearMemoryLimit ? { nearMemoryLimit: true } : {}
|
|
260
|
+
} });
|
|
261
|
+
return (await jobs.find({
|
|
262
|
+
_id: { $in: jobIds },
|
|
263
|
+
workerId,
|
|
264
|
+
status: "running",
|
|
265
|
+
$or: [{ cancelRequested: true }, { pauseRequested: true }]
|
|
266
|
+
}).project({
|
|
267
|
+
_id: 1,
|
|
268
|
+
cancelRequested: 1
|
|
269
|
+
}).toArray()).map((job) => ({
|
|
270
|
+
jobId: job._id,
|
|
271
|
+
stop: job.cancelRequested === true ? "cancel" : "pause"
|
|
272
|
+
}));
|
|
273
|
+
},
|
|
274
|
+
write: async ({ jobId, workerId, state, progress }) => {
|
|
275
|
+
const { jobs } = await collections();
|
|
276
|
+
const at = await clock.now();
|
|
277
|
+
return (await jobs.updateOne({
|
|
278
|
+
_id: jobId,
|
|
279
|
+
workerId,
|
|
280
|
+
status: "running"
|
|
281
|
+
}, { $set: {
|
|
282
|
+
updatedAt: at,
|
|
283
|
+
...state === void 0 ? {} : { state },
|
|
284
|
+
...progress ? { progress: {
|
|
285
|
+
...progress,
|
|
286
|
+
at
|
|
287
|
+
} } : {}
|
|
288
|
+
} })).matchedCount === 1;
|
|
289
|
+
},
|
|
290
|
+
settle: async ({ jobId, workerId, status, delayMs, runId, error, attempt, result, spentMs, refund = status === "pending" && !attempt }) => {
|
|
291
|
+
const { jobs } = await collections();
|
|
292
|
+
const at = await clock.now();
|
|
293
|
+
const entry = {
|
|
294
|
+
attempt: { $add: [{ $size: "$history" }, 1] },
|
|
295
|
+
startedAt: "$updatedAt",
|
|
296
|
+
endedAt: at,
|
|
297
|
+
...attempt
|
|
298
|
+
};
|
|
299
|
+
const settled = status === "pending" ? { $cond: [
|
|
300
|
+
{ $eq: ["$cancelRequested", true] },
|
|
301
|
+
"cancelled",
|
|
302
|
+
{ $cond: [
|
|
303
|
+
{ $eq: ["$pauseRequested", true] },
|
|
304
|
+
"paused",
|
|
305
|
+
"pending"
|
|
306
|
+
] }
|
|
307
|
+
] } : status;
|
|
308
|
+
await jobs.updateOne({
|
|
309
|
+
_id: jobId,
|
|
310
|
+
workerId
|
|
311
|
+
}, [{ $set: {
|
|
312
|
+
...attempt ? { history: { $concatArrays: ["$history", [entry]] } } : {},
|
|
313
|
+
status: settled,
|
|
314
|
+
updatedAt: at,
|
|
315
|
+
leaseUntil: null,
|
|
316
|
+
error: error ?? null,
|
|
317
|
+
cancelRequested: null,
|
|
318
|
+
pauseRequested: null,
|
|
319
|
+
...runId ? { runId } : {},
|
|
320
|
+
...result === void 0 ? {} : { result: { $literal: result } },
|
|
321
|
+
...spentMs ? { activeMs: { $add: [{ $ifNull: ["$activeMs", 0] }, spentMs] } } : {},
|
|
322
|
+
...refund ? { attempts: { $max: [0, { $subtract: ["$attempts", 1] }] } } : {}
|
|
323
|
+
} }, { $set: {
|
|
324
|
+
runAt: { $cond: [
|
|
325
|
+
{ $eq: ["$status", "pending"] },
|
|
326
|
+
at + (delayMs ?? 0),
|
|
327
|
+
"$runAt"
|
|
328
|
+
] },
|
|
329
|
+
workerId: { $cond: [
|
|
330
|
+
{ $in: ["$status", ["pending", "paused"]] },
|
|
331
|
+
null,
|
|
332
|
+
"$workerId"
|
|
333
|
+
] },
|
|
334
|
+
expiresAt: { $cond: [
|
|
335
|
+
{ $in: ["$status", TERMINAL] },
|
|
336
|
+
expiryOf(at),
|
|
337
|
+
null
|
|
338
|
+
] }
|
|
339
|
+
} }]);
|
|
340
|
+
},
|
|
341
|
+
dueSchedules: async (limit) => {
|
|
342
|
+
const { schedules } = await collections();
|
|
343
|
+
const at = await clock.now();
|
|
344
|
+
return (await schedules.find({
|
|
345
|
+
enabled: true,
|
|
346
|
+
nextRunAt: { $lte: at }
|
|
347
|
+
}).sort({ nextRunAt: 1 }).limit(limit).toArray()).map(toSchedule);
|
|
348
|
+
},
|
|
349
|
+
advanceSchedule: async ({ spaceId, actionId, from, to, missed }) => {
|
|
350
|
+
const { schedules } = await collections();
|
|
351
|
+
const at = await clock.now();
|
|
352
|
+
return (await schedules.updateOne({
|
|
353
|
+
_id: scheduleId(spaceId, actionId),
|
|
354
|
+
nextRunAt: from
|
|
355
|
+
}, {
|
|
356
|
+
$set: {
|
|
357
|
+
nextRunAt: to,
|
|
358
|
+
lastFireAt: from,
|
|
359
|
+
updatedAt: at
|
|
360
|
+
},
|
|
361
|
+
$inc: { missed }
|
|
362
|
+
})).matchedCount === 1;
|
|
363
|
+
},
|
|
364
|
+
putSchedules: async ({ spaceId, schedules: incoming }) => {
|
|
365
|
+
const { schedules } = await collections();
|
|
366
|
+
const at = await clock.now();
|
|
367
|
+
if (incoming.length > 0) await schedules.bulkWrite(incoming.map((schedule) => ({ updateOne: {
|
|
368
|
+
filter: { _id: scheduleId(spaceId, schedule.actionId) },
|
|
369
|
+
update: [{ $set: {
|
|
370
|
+
...schedule,
|
|
371
|
+
timezone: schedule.timezone ?? null,
|
|
372
|
+
updatedAt: at,
|
|
373
|
+
missed: { $ifNull: ["$missed", 0] },
|
|
374
|
+
nextRunAt: { $cond: [
|
|
375
|
+
{ $and: [
|
|
376
|
+
{ $eq: ["$cron", schedule.cron] },
|
|
377
|
+
{ $eq: [{ $ifNull: ["$timezone", null] }, schedule.timezone ?? null] },
|
|
378
|
+
{ $eq: ["$environment", schedule.environment] },
|
|
379
|
+
{ $ne: [{ $ifNull: ["$nextRunAt", null] }, null] }
|
|
380
|
+
] },
|
|
381
|
+
"$nextRunAt",
|
|
382
|
+
schedule.nextRunAt
|
|
383
|
+
] }
|
|
384
|
+
} }],
|
|
385
|
+
upsert: true
|
|
386
|
+
} })));
|
|
387
|
+
await schedules.deleteMany({
|
|
388
|
+
spaceId,
|
|
389
|
+
actionId: { $nin: incoming.map((schedule) => schedule.actionId) }
|
|
390
|
+
});
|
|
391
|
+
},
|
|
392
|
+
listJobs: async ({ spaceIds, name, status, kind, limit, offset }) => {
|
|
393
|
+
const { jobs } = await collections();
|
|
394
|
+
const filter = {
|
|
395
|
+
spaceId: { $in: spaceIds },
|
|
396
|
+
...name ? { "target.name": name } : {},
|
|
397
|
+
...status ? { status } : {},
|
|
398
|
+
...kind ? { "target.kind": kind } : {}
|
|
399
|
+
};
|
|
400
|
+
const [found, total] = await Promise.all([jobs.find(filter).sort({
|
|
401
|
+
updatedAt: -1,
|
|
402
|
+
_id: -1
|
|
403
|
+
}).skip(offset).limit(limit).toArray(), jobs.countDocuments(filter)]);
|
|
404
|
+
return {
|
|
405
|
+
jobs: found.map(toJob),
|
|
406
|
+
total
|
|
407
|
+
};
|
|
408
|
+
},
|
|
409
|
+
listAcross: async ({ statuses, limit, order }) => {
|
|
410
|
+
const { jobs } = await collections();
|
|
411
|
+
return (await jobs.find({ status: { $in: statuses } }).sort(order === "due" ? {
|
|
412
|
+
runAt: 1,
|
|
413
|
+
_id: 1
|
|
414
|
+
} : {
|
|
415
|
+
updatedAt: -1,
|
|
416
|
+
_id: -1
|
|
417
|
+
}).limit(limit).toArray()).map(toJob);
|
|
418
|
+
},
|
|
419
|
+
summarize: async ({ spaces = 10 } = {}) => {
|
|
420
|
+
const { jobs } = await collections();
|
|
421
|
+
const waitingNow = { status: { $in: [...WAITING_STATUSES] } };
|
|
422
|
+
const [found] = await jobs.aggregate([{ $facet: {
|
|
423
|
+
byStatus: [{ $group: {
|
|
424
|
+
_id: "$status",
|
|
425
|
+
n: { $sum: 1 }
|
|
426
|
+
} }],
|
|
427
|
+
needingMemory: [{ $match: {
|
|
428
|
+
status: { $in: [...NEEDING_STATUSES] },
|
|
429
|
+
needsMemoryMb: { $exists: true }
|
|
430
|
+
} }, { $group: {
|
|
431
|
+
_id: "$status",
|
|
432
|
+
n: { $sum: 1 },
|
|
433
|
+
most: { $max: "$needsMemoryMb" }
|
|
434
|
+
} }],
|
|
435
|
+
waiting: [{ $match: waitingNow }, { $group: {
|
|
436
|
+
_id: {
|
|
437
|
+
kind: "$target.kind",
|
|
438
|
+
trigger: "$target.trigger"
|
|
439
|
+
},
|
|
440
|
+
n: { $sum: 1 },
|
|
441
|
+
oldest: { $min: "$dueAt" }
|
|
442
|
+
} }],
|
|
443
|
+
spaces: [
|
|
444
|
+
{ $match: waitingNow },
|
|
445
|
+
{ $sort: { updatedAt: 1 } },
|
|
446
|
+
{ $group: {
|
|
447
|
+
_id: "$spaceId",
|
|
448
|
+
waiting: { $sum: 1 },
|
|
449
|
+
calls: { $sum: { $cond: [
|
|
450
|
+
{ $eq: ["$target.trigger", "call"] },
|
|
451
|
+
1,
|
|
452
|
+
0
|
|
453
|
+
] } },
|
|
454
|
+
oldestDueAt: { $min: "$dueAt" },
|
|
455
|
+
lastError: { $last: "$error" }
|
|
456
|
+
} },
|
|
457
|
+
{ $sort: {
|
|
458
|
+
waiting: -1,
|
|
459
|
+
oldestDueAt: 1
|
|
460
|
+
} },
|
|
461
|
+
{ $limit: Math.max(1, spaces) }
|
|
462
|
+
]
|
|
463
|
+
} }]).toArray();
|
|
464
|
+
const byStatus = noJobsByStatus();
|
|
465
|
+
found.byStatus.forEach((each) => {
|
|
466
|
+
byStatus[each._id] = each.n;
|
|
467
|
+
});
|
|
468
|
+
const waiting = {
|
|
469
|
+
calls: 0,
|
|
470
|
+
schedules: 0,
|
|
471
|
+
later: 0,
|
|
472
|
+
functionJobs: 0,
|
|
473
|
+
other: 0
|
|
474
|
+
};
|
|
475
|
+
let oldestDueAt;
|
|
476
|
+
found.waiting.forEach((each) => {
|
|
477
|
+
waiting[waitingKindOf(each._id.kind, each._id.trigger)] += each.n;
|
|
478
|
+
oldestDueAt = oldestDueAt === void 0 ? each.oldest : Math.min(oldestDueAt, each.oldest);
|
|
479
|
+
});
|
|
480
|
+
const waitingForMemory = found.needingMemory.find((each) => each._id === "pending");
|
|
481
|
+
return {
|
|
482
|
+
byStatus,
|
|
483
|
+
waiting,
|
|
484
|
+
...oldestDueAt === void 0 ? {} : { oldestDueAt },
|
|
485
|
+
needingMemory: {
|
|
486
|
+
waiting: waitingForMemory?.n ?? 0,
|
|
487
|
+
paused: found.needingMemory.find((each) => each._id === "paused")?.n ?? 0,
|
|
488
|
+
...waitingForMemory ? { mostMb: waitingForMemory.most } : {}
|
|
489
|
+
},
|
|
490
|
+
spaces: found.spaces.slice(0, spaces).map((each) => ({
|
|
491
|
+
spaceId: each._id,
|
|
492
|
+
waiting: each.waiting,
|
|
493
|
+
calls: each.calls,
|
|
494
|
+
oldestDueAt: each.oldestDueAt,
|
|
495
|
+
...each.lastError ? { lastError: each.lastError } : {}
|
|
496
|
+
}))
|
|
497
|
+
};
|
|
498
|
+
},
|
|
499
|
+
flow: async ({ from, to }) => {
|
|
500
|
+
const { jobs } = await collections();
|
|
501
|
+
const touching = await jobs.find({ $or: [{ dueAt: {
|
|
502
|
+
$gte: from,
|
|
503
|
+
$lt: to
|
|
504
|
+
} }, { updatedAt: { $gte: from } }] }, { projection: {
|
|
505
|
+
_id: 0,
|
|
506
|
+
dueAt: 1,
|
|
507
|
+
history: 1,
|
|
508
|
+
status: 1,
|
|
509
|
+
updatedAt: 1,
|
|
510
|
+
attempts: 1
|
|
511
|
+
} }).toArray();
|
|
512
|
+
return flowOf(touching, from, to);
|
|
513
|
+
},
|
|
514
|
+
countDue: async ({ spaces, memoryMb } = {}) => {
|
|
515
|
+
const { jobs } = await collections();
|
|
516
|
+
return jobs.countDocuments(claimable(await clock.now(), spaces, memoryMb));
|
|
517
|
+
},
|
|
518
|
+
getJob: async (spaceIds, jobId) => {
|
|
519
|
+
const { jobs } = await collections();
|
|
520
|
+
const job = await jobs.findOne({
|
|
521
|
+
_id: jobId,
|
|
522
|
+
spaceId: { $in: spaceIds }
|
|
523
|
+
});
|
|
524
|
+
return job ? toJob(job) : void 0;
|
|
525
|
+
},
|
|
526
|
+
listSchedules: async (spaceIds) => {
|
|
527
|
+
const { schedules } = await collections();
|
|
528
|
+
return (await schedules.find({ spaceId: { $in: spaceIds } }).sort({ nextRunAt: 1 }).toArray()).map(toSchedule);
|
|
529
|
+
},
|
|
530
|
+
requeue: async (spaceIds, jobId, { input, fresh = false } = {}) => {
|
|
531
|
+
const { jobs } = await collections();
|
|
532
|
+
const at = await clock.now();
|
|
533
|
+
return (await jobs.updateOne({
|
|
534
|
+
_id: jobId,
|
|
535
|
+
spaceId: { $in: spaceIds },
|
|
536
|
+
status: { $in: TERMINAL }
|
|
537
|
+
}, {
|
|
538
|
+
$set: {
|
|
539
|
+
status: "pending",
|
|
540
|
+
runAt: at,
|
|
541
|
+
attempts: 0,
|
|
542
|
+
updatedAt: at,
|
|
543
|
+
...input ? { input } : {}
|
|
544
|
+
},
|
|
545
|
+
$unset: {
|
|
546
|
+
workerId: "",
|
|
547
|
+
leaseUntil: "",
|
|
548
|
+
error: "",
|
|
549
|
+
expiresAt: "",
|
|
550
|
+
result: "",
|
|
551
|
+
cancelRequested: "",
|
|
552
|
+
pauseRequested: "",
|
|
553
|
+
...fresh ? {
|
|
554
|
+
state: "",
|
|
555
|
+
progress: "",
|
|
556
|
+
activeMs: ""
|
|
557
|
+
} : {}
|
|
558
|
+
}
|
|
559
|
+
})).matchedCount === 1;
|
|
560
|
+
},
|
|
561
|
+
cancel: async (spaceIds, jobId) => {
|
|
562
|
+
const { jobs } = await collections();
|
|
563
|
+
const at = await clock.now();
|
|
564
|
+
if ((await jobs.updateOne({
|
|
565
|
+
_id: jobId,
|
|
566
|
+
spaceId: { $in: spaceIds },
|
|
567
|
+
status: { $in: ["pending", "paused"] }
|
|
568
|
+
}, {
|
|
569
|
+
$set: {
|
|
570
|
+
status: "cancelled",
|
|
571
|
+
updatedAt: at,
|
|
572
|
+
expiresAt: expiryOf(at)
|
|
573
|
+
},
|
|
574
|
+
$unset: {
|
|
575
|
+
workerId: "",
|
|
576
|
+
pauseRequested: ""
|
|
577
|
+
}
|
|
578
|
+
})).matchedCount === 1) return true;
|
|
579
|
+
return (await jobs.updateOne({
|
|
580
|
+
_id: jobId,
|
|
581
|
+
spaceId: { $in: spaceIds },
|
|
582
|
+
status: "running"
|
|
583
|
+
}, { $set: {
|
|
584
|
+
cancelRequested: true,
|
|
585
|
+
updatedAt: at
|
|
586
|
+
} })).matchedCount === 1;
|
|
587
|
+
},
|
|
588
|
+
pause: async (spaceIds, jobId) => {
|
|
589
|
+
const { jobs } = await collections();
|
|
590
|
+
const at = await clock.now();
|
|
591
|
+
const own = {
|
|
592
|
+
_id: jobId,
|
|
593
|
+
spaceId: { $in: spaceIds },
|
|
594
|
+
"target.kind": "function"
|
|
595
|
+
};
|
|
596
|
+
if ((await jobs.updateOne({
|
|
597
|
+
...own,
|
|
598
|
+
status: "pending"
|
|
599
|
+
}, { $set: {
|
|
600
|
+
status: "paused",
|
|
601
|
+
updatedAt: at
|
|
602
|
+
} })).matchedCount === 1) return true;
|
|
603
|
+
return (await jobs.updateOne({
|
|
604
|
+
...own,
|
|
605
|
+
status: "running",
|
|
606
|
+
pauseRequested: { $ne: true }
|
|
607
|
+
}, { $set: {
|
|
608
|
+
pauseRequested: true,
|
|
609
|
+
updatedAt: at
|
|
610
|
+
} })).matchedCount === 1;
|
|
611
|
+
},
|
|
612
|
+
resume: async (spaceIds, jobId) => {
|
|
613
|
+
const { jobs } = await collections();
|
|
614
|
+
const at = await clock.now();
|
|
615
|
+
return (await jobs.updateOne({
|
|
616
|
+
_id: jobId,
|
|
617
|
+
spaceId: { $in: spaceIds },
|
|
618
|
+
status: "paused"
|
|
619
|
+
}, [{ $set: {
|
|
620
|
+
status: "pending",
|
|
621
|
+
runAt: at,
|
|
622
|
+
updatedAt: at,
|
|
623
|
+
attempts: { $cond: [
|
|
624
|
+
{ $gte: ["$attempts", "$maxAttempts"] },
|
|
625
|
+
0,
|
|
626
|
+
"$attempts"
|
|
627
|
+
] }
|
|
628
|
+
} }])).matchedCount === 1;
|
|
629
|
+
},
|
|
630
|
+
cancelPending: async ({ spaceId, key, olderThan }) => {
|
|
631
|
+
const { jobs } = await collections();
|
|
632
|
+
const newest = olderThan === void 0 ? void 0 : await jobs.findOne({ _id: olderThan });
|
|
633
|
+
const at = await clock.now();
|
|
634
|
+
return (await jobs.updateMany({
|
|
635
|
+
spaceId,
|
|
636
|
+
key,
|
|
637
|
+
status: "pending",
|
|
638
|
+
...newest ? { $or: [{ createdAt: { $lt: newest.createdAt } }, {
|
|
639
|
+
createdAt: newest.createdAt,
|
|
640
|
+
_id: { $lt: newest._id }
|
|
641
|
+
}] } : {}
|
|
642
|
+
}, {
|
|
643
|
+
$set: {
|
|
644
|
+
status: "cancelled",
|
|
645
|
+
updatedAt: at,
|
|
646
|
+
expiresAt: expiryOf(at)
|
|
647
|
+
},
|
|
648
|
+
$unset: { workerId: "" }
|
|
649
|
+
})).modifiedCount;
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
};
|
|
653
|
+
// src/mongo/kv.ts
|
|
654
|
+
/** Mongo's code for a unique index that refused a second document with the same key. */
|
|
655
|
+
var DUPLICATE_KEY = 11e3;
|
|
656
|
+
/**
|
|
657
|
+
* Whether a key is still alive, by the SERVER's clock.
|
|
658
|
+
*
|
|
659
|
+
* Mongo's TTL monitor sweeps once a minute, so a document past its lifetime can still be there to read. Expiry is
|
|
660
|
+
* decided here, against `$$NOW`, rather than by whether the sweeper has been round yet — the same answer Redis gives
|
|
661
|
+
* the instant a key lapses.
|
|
662
|
+
*/
|
|
663
|
+
var LIVE = { $or: [{ $eq: [{ $ifNull: ["$expiresAt", null] }, null] }, { $gt: ["$expiresAt", "$$NOW"] }] };
|
|
664
|
+
var expiryIn = (ttlSeconds) => ({ $add: ["$$NOW", ttlSeconds * 1e3] });
|
|
665
|
+
/**
|
|
666
|
+
* An {@link ActionKvAdapter} over a collection of a Mongo database the deployment owns.
|
|
667
|
+
*
|
|
668
|
+
* What the run guards' single-flight keys and the `kv` tasks' counters need from a store the replicas share: a TTL the
|
|
669
|
+
* store enforces and an increment nobody can race. Each operation is ONE document update, which Mongo applies
|
|
670
|
+
* atomically — so two replicas incrementing the same counter at once both count.
|
|
671
|
+
*/
|
|
672
|
+
var createMongoKv = ({ db, collection = "action_kv" }) => {
|
|
673
|
+
const keys = () => resolveDb(db).collection(collection);
|
|
674
|
+
let ready;
|
|
675
|
+
const store = async () => {
|
|
676
|
+
ready ??= keys().createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }).then(() => void 0).catch((error) => {
|
|
677
|
+
ready = void 0;
|
|
678
|
+
throw error;
|
|
679
|
+
});
|
|
680
|
+
await ready;
|
|
681
|
+
return keys();
|
|
682
|
+
};
|
|
683
|
+
/**
|
|
684
|
+
* An upsert two replicas race for can collide on `_id` before either has written; the server retries that itself
|
|
685
|
+
* from 4.2 on, and this covers the rest. Once is enough: the second attempt finds the document the first one made.
|
|
686
|
+
*/
|
|
687
|
+
const upserting = async (write) => {
|
|
688
|
+
try {
|
|
689
|
+
return await write();
|
|
690
|
+
} catch (error) {
|
|
691
|
+
if (error.code !== DUPLICATE_KEY) throw error;
|
|
692
|
+
return write();
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
return {
|
|
696
|
+
get: async (key) => {
|
|
697
|
+
return (await (await store()).findOne({
|
|
698
|
+
_id: key,
|
|
699
|
+
$expr: LIVE
|
|
700
|
+
}))?.value;
|
|
701
|
+
},
|
|
702
|
+
set: async (key, value, ttlSeconds) => {
|
|
703
|
+
const keysNow = await store();
|
|
704
|
+
await upserting(() => keysNow.updateOne({ _id: key }, [{ $set: {
|
|
705
|
+
value,
|
|
706
|
+
expiresAt: ttlSeconds === void 0 ? null : expiryIn(ttlSeconds)
|
|
707
|
+
} }], { upsert: true }));
|
|
708
|
+
},
|
|
709
|
+
delete: async (key) => {
|
|
710
|
+
await (await store()).deleteOne({ _id: key });
|
|
711
|
+
},
|
|
712
|
+
increment: async (key, amount) => {
|
|
713
|
+
const keysNow = await store();
|
|
714
|
+
const updated = await upserting(() => keysNow.findOneAndUpdate({ _id: key }, [
|
|
715
|
+
{ $set: { live: LIVE } },
|
|
716
|
+
{ $set: {
|
|
717
|
+
value: { $toString: { $add: [{ $cond: [
|
|
718
|
+
"$live",
|
|
719
|
+
{ $convert: {
|
|
720
|
+
input: "$value",
|
|
721
|
+
to: "double",
|
|
722
|
+
onError: 0,
|
|
723
|
+
onNull: 0
|
|
724
|
+
} },
|
|
725
|
+
0
|
|
726
|
+
] }, amount] } },
|
|
727
|
+
expiresAt: { $cond: [
|
|
728
|
+
"$live",
|
|
729
|
+
{ $ifNull: ["$expiresAt", null] },
|
|
730
|
+
null
|
|
731
|
+
] }
|
|
732
|
+
} },
|
|
733
|
+
{ $unset: "live" }
|
|
734
|
+
], {
|
|
735
|
+
upsert: true,
|
|
736
|
+
returnDocument: "after"
|
|
737
|
+
}));
|
|
738
|
+
return Number(updated?.value ?? amount);
|
|
739
|
+
},
|
|
740
|
+
expire: async (key, ttlSeconds) => {
|
|
741
|
+
await (await store()).updateOne({
|
|
742
|
+
_id: key,
|
|
743
|
+
$expr: LIVE
|
|
744
|
+
}, [{ $set: { expiresAt: expiryIn(ttlSeconds) } }]);
|
|
745
|
+
},
|
|
746
|
+
/**
|
|
747
|
+
* Each branch is one update Mongo applies to the document atomically. Expecting a value, the filter names it.
|
|
748
|
+
* Expecting nothing is two cases: a lapsed document, taken over by a filter that matches only a lapsed one; and no
|
|
749
|
+
* document, inserted by an upsert whose filter no stored document satisfies — so a live one makes it collide on
|
|
750
|
+
* `_id`, which is the refusal, not an error. (An upsert may not filter with `$expr`, or this would be one step.)
|
|
751
|
+
*/
|
|
752
|
+
swap: async (key, expected, next, ttlSeconds) => {
|
|
753
|
+
const keysNow = await store();
|
|
754
|
+
const write = [{ $set: {
|
|
755
|
+
value: next,
|
|
756
|
+
expiresAt: ttlSeconds === void 0 ? null : expiryIn(ttlSeconds)
|
|
757
|
+
} }];
|
|
758
|
+
if (expected !== void 0) return (await keysNow.updateOne({
|
|
759
|
+
_id: key,
|
|
760
|
+
value: expected,
|
|
761
|
+
$expr: LIVE
|
|
762
|
+
}, write)).matchedCount === 1;
|
|
763
|
+
if ((await keysNow.updateOne({
|
|
764
|
+
_id: key,
|
|
765
|
+
$expr: { $not: [LIVE] }
|
|
766
|
+
}, write)).matchedCount === 1) return true;
|
|
767
|
+
try {
|
|
768
|
+
return (await keysNow.updateOne({
|
|
769
|
+
_id: key,
|
|
770
|
+
value: { $exists: false }
|
|
771
|
+
}, write, { upsert: true })).upsertedCount === 1;
|
|
772
|
+
} catch (error) {
|
|
773
|
+
if (error.code === DUPLICATE_KEY) return false;
|
|
774
|
+
throw error;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
};
|
|
778
|
+
};
|
|
779
|
+
export { createMongoJobQueue, createMongoKv };
|