@vite-hub/queue 0.1.0 → 0.4.1
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/README.md +152 -29
- package/dist/client-B53_G4ky.js +182 -0
- package/dist/{cloudflare-client-COzQ8fHk.js → cloudflare-client-CoISDpIx.js} +28 -21
- package/dist/{cloudflare-resource-name-CCuLDvSP.js → cloudflare-resource-name-BIfBglC2.js} +1 -1
- package/dist/config-B2eaXaT5.js +105 -0
- package/dist/durability.d.ts +13 -0
- package/dist/durability.js +47 -0
- package/dist/duration-tujyhAKt.js +111 -0
- package/dist/error-diagnostics-CQ4BUqRe.js +270 -0
- package/dist/error-diagnostics-mJXBjmQx.js +181 -0
- package/dist/{handler-response-CBwIkmTS.js → handler-response-B6lz9nCn.js} +9 -4
- package/dist/index.d.ts +20 -32
- package/dist/index.js +39 -17
- package/dist/internal/runtime/cloudflare-client.d.ts +2 -2
- package/dist/internal/runtime/cloudflare-client.js +1 -1
- package/dist/internal/runtime/cloudflare-vite.d.ts +30 -2
- package/dist/internal/runtime/cloudflare-vite.js +111 -1
- package/dist/internal/runtime/local-client.d.ts +17 -0
- package/dist/internal/runtime/local-client.js +71 -0
- package/dist/internal/runtime/postgres-client.d.ts +46 -0
- package/dist/internal/runtime/postgres-client.js +570 -0
- package/dist/internal/runtime/state.d.ts +11 -4
- package/dist/internal/runtime/state.js +2 -2
- package/dist/internal/runtime/vercel-client.d.ts +2 -2
- package/dist/internal/runtime/vercel-client.js +66 -28
- package/dist/internal/runtime/worker-client.d.ts +6 -0
- package/dist/internal/runtime/worker-client.js +11 -0
- package/dist/invariant-D8_xBqmZ.js +22 -0
- package/dist/local-CUaWoRUx.d.ts +23 -0
- package/dist/local-Di0FrVUw.js +553 -0
- package/dist/object-D8pRdprI.js +15 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
- package/dist/operations-BVV-9Q0N.js +129 -0
- package/dist/operations.d.ts +47 -9
- package/dist/operations.js +186 -69
- package/dist/runtime/hosted.d.ts +3 -5
- package/dist/runtime/hosted.js +21 -45
- package/dist/{state-G9s378-e.js → state-DLqTqF6V.js} +59 -47
- package/dist/types-CiuSIPR0.d.ts +440 -0
- package/dist/types-Dsbb_Pvp.d.ts +10 -0
- package/dist/vercel-region-B95MAMXN.js +26 -0
- package/dist/virtual.d.ts +4 -0
- package/dist/vite.d.ts +366 -49
- package/dist/vite.js +2071 -2
- package/package.json +39 -46
- package/dist/client-CIc3jsj2.js +0 -114
- package/dist/cloudflare-vite-BCuJOXcT.js +0 -111
- package/dist/cloudflare-vite-CjdP5yBN.d.ts +0 -29
- package/dist/config-BINujLv4.js +0 -74
- package/dist/enqueue-CnQ0QR3O.js +0 -22
- package/dist/error-diagnostics-A_8Kp-48.js +0 -116
- package/dist/error-diagnostics-qzRF6IVB.js +0 -109
- package/dist/errors-DIFaM9tW.js +0 -42
- package/dist/nuxt.d.ts +0 -39
- package/dist/nuxt.js +0 -34
- package/dist/object-B1NW521B.js +0 -7
- package/dist/operations-Cnjbz8kk.js +0 -63
- package/dist/types-1GRMYES1.d.ts +0 -180
- package/dist/vercel-region-cjskrOKl.js +0 -122
- package/dist/vite-ChWLzOVu.js +0 -1512
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
import { t as queueErrorDiagnostics } from "./error-diagnostics-mJXBjmQx.js";
|
|
2
|
+
import { c as queueRemovedOptionsError, d as normalizeQueueEnqueueInput, i as localUnsupportedEnqueueOptions, l as queueUnsupportedOptionsError, n as cloudflareUnsupportedEnqueueOptions, o as postgresUnsupportedEnqueueOptions, s as queueProviderResult, t as readQueueTimes, u as createQueueMessageId } from "./duration-tujyhAKt.js";
|
|
3
|
+
import { i as reportQueueDeliveryError, n as createQueueDeliveryErrorReport, r as isNonRetryableQueueError, t as checkQueueHandlerResponse } from "./handler-response-B6lz9nCn.js";
|
|
4
|
+
import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { join, resolve } from "pathe";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
|
|
8
|
+
const maxTimerDelay = 2 ** 31 - 1;
|
|
9
|
+
/** Retries after 1, 2, and 4 seconds, up to 60 seconds. The local and postgres providers use it. */
|
|
10
|
+
function defaultRetryDelayMs(attempts) {
|
|
11
|
+
return Math.min(2 ** (attempts - 1), 60) * 1e3;
|
|
12
|
+
}
|
|
13
|
+
const day = 86400;
|
|
14
|
+
/**
|
|
15
|
+
* Delivery rules per provider. `vite dev` runs the jobs of a Cloudflare or Vercel app with the local engine and the
|
|
16
|
+
* documented defaults of that provider, so a handler fails, retries, and stops in dev as it does on the host.
|
|
17
|
+
*/
|
|
18
|
+
const localQueueDeliveryRules = {
|
|
19
|
+
cloudflare: {
|
|
20
|
+
maxAttempts: 4,
|
|
21
|
+
maxBatchBytes: 262144,
|
|
22
|
+
maxBatchJobs: 100,
|
|
23
|
+
maxDelaySeconds: day,
|
|
24
|
+
maxPayloadBytes: 130972,
|
|
25
|
+
retryDelayMs: () => 0,
|
|
26
|
+
rules: "cloudflare",
|
|
27
|
+
unsupportedOptions: cloudflareUnsupportedEnqueueOptions
|
|
28
|
+
},
|
|
29
|
+
local: {
|
|
30
|
+
maxAttempts: 4,
|
|
31
|
+
retryDelayMs: defaultRetryDelayMs,
|
|
32
|
+
rules: "local",
|
|
33
|
+
unsupportedOptions: localUnsupportedEnqueueOptions
|
|
34
|
+
},
|
|
35
|
+
postgres: {
|
|
36
|
+
maxAttempts: 4,
|
|
37
|
+
retryDelayMs: defaultRetryDelayMs,
|
|
38
|
+
rules: "postgres",
|
|
39
|
+
unsupportedOptions: postgresUnsupportedEnqueueOptions
|
|
40
|
+
},
|
|
41
|
+
vercel: {
|
|
42
|
+
maxAttempts: Number.POSITIVE_INFINITY,
|
|
43
|
+
maxBatchJobs: 100,
|
|
44
|
+
maxDelaySeconds: 7 * day,
|
|
45
|
+
maxPayloadBytes: 104857600,
|
|
46
|
+
retention: {
|
|
47
|
+
defaultSeconds: day,
|
|
48
|
+
maxSeconds: 7 * day,
|
|
49
|
+
minSeconds: 60
|
|
50
|
+
},
|
|
51
|
+
retryDelayMs: () => 6e4,
|
|
52
|
+
rules: "vercel",
|
|
53
|
+
unsupportedOptions: ["contentType"]
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
function isStoredJob(value) {
|
|
57
|
+
if (!value || typeof value !== "object") return false;
|
|
58
|
+
const job = value;
|
|
59
|
+
return typeof job.key === "string" && typeof job.id === "string" && typeof job.queue === "string" && typeof job.attempts === "number" && typeof job.availableAt === "number" && typeof job.enqueuedAt === "number" && (job.state === "pending" || job.state === "dead" || job.state === "done");
|
|
60
|
+
}
|
|
61
|
+
const providerNames = {
|
|
62
|
+
cloudflare: "Cloudflare",
|
|
63
|
+
local: "The local provider",
|
|
64
|
+
postgres: "The postgres provider",
|
|
65
|
+
vercel: "Vercel"
|
|
66
|
+
};
|
|
67
|
+
/** The JSON copy of the payload and its size in bytes. */
|
|
68
|
+
function toStoredPayload(payload) {
|
|
69
|
+
const text = JSON.stringify(payload);
|
|
70
|
+
return text === void 0 ? {
|
|
71
|
+
bytes: 0,
|
|
72
|
+
stored: {}
|
|
73
|
+
} : {
|
|
74
|
+
bytes: Buffer.byteLength(text),
|
|
75
|
+
stored: { payload: JSON.parse(text) }
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function delayMs(delaySeconds, rules) {
|
|
79
|
+
if (delaySeconds === void 0) return 0;
|
|
80
|
+
if (!Number.isFinite(delaySeconds) || delaySeconds < 0) throw queueErrorDiagnostics.QUEUE_LOCAL_LIMIT_EXCEEDED({
|
|
81
|
+
limit: "delay",
|
|
82
|
+
provider: providerNames[rules.rules],
|
|
83
|
+
value: String(delaySeconds)
|
|
84
|
+
});
|
|
85
|
+
if (rules.maxDelaySeconds !== void 0 && delaySeconds > rules.maxDelaySeconds) throw queueErrorDiagnostics.QUEUE_LOCAL_LIMIT_EXCEEDED({
|
|
86
|
+
limit: "delay-max",
|
|
87
|
+
max: rules.maxDelaySeconds,
|
|
88
|
+
provider: providerNames[rules.rules],
|
|
89
|
+
value: delaySeconds
|
|
90
|
+
});
|
|
91
|
+
return delaySeconds * 1e3;
|
|
92
|
+
}
|
|
93
|
+
function retentionMs(retentionSeconds, rules) {
|
|
94
|
+
const retention = rules.retention;
|
|
95
|
+
if (!retention) return void 0;
|
|
96
|
+
const seconds = retentionSeconds ?? retention.defaultSeconds;
|
|
97
|
+
if (!Number.isFinite(seconds) || seconds < retention.minSeconds || seconds > retention.maxSeconds) throw queueErrorDiagnostics.QUEUE_LOCAL_LIMIT_EXCEEDED({
|
|
98
|
+
limit: "retention",
|
|
99
|
+
max: retention.maxSeconds,
|
|
100
|
+
min: retention.minSeconds,
|
|
101
|
+
provider: providerNames[rules.rules],
|
|
102
|
+
value: String(seconds)
|
|
103
|
+
});
|
|
104
|
+
return seconds * 1e3;
|
|
105
|
+
}
|
|
106
|
+
function checkPayloadSize(bytes, rules) {
|
|
107
|
+
if (rules.maxPayloadBytes !== void 0 && bytes > rules.maxPayloadBytes) throw queueErrorDiagnostics.QUEUE_LOCAL_LIMIT_EXCEEDED({
|
|
108
|
+
limit: "payload",
|
|
109
|
+
max: rules.maxPayloadBytes,
|
|
110
|
+
provider: providerNames[rules.rules],
|
|
111
|
+
value: bytes
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
function checkBatch(entries, bytes, rules) {
|
|
115
|
+
if (rules.rules === "vercel" && entries.length === 0) throw queueErrorDiagnostics.QUEUE_LOCAL_LIMIT_EXCEEDED({
|
|
116
|
+
limit: "batch-empty",
|
|
117
|
+
provider: providerNames[rules.rules],
|
|
118
|
+
value: 0
|
|
119
|
+
});
|
|
120
|
+
if (entries.length < 2) return;
|
|
121
|
+
if (rules.maxBatchJobs !== void 0 && entries.length > rules.maxBatchJobs) throw queueErrorDiagnostics.QUEUE_LOCAL_LIMIT_EXCEEDED({
|
|
122
|
+
limit: "batch-jobs",
|
|
123
|
+
max: rules.maxBatchJobs,
|
|
124
|
+
provider: providerNames[rules.rules],
|
|
125
|
+
value: entries.length
|
|
126
|
+
});
|
|
127
|
+
if (rules.maxBatchBytes !== void 0 && bytes > rules.maxBatchBytes) throw queueErrorDiagnostics.QUEUE_LOCAL_LIMIT_EXCEEDED({
|
|
128
|
+
limit: "batch-bytes",
|
|
129
|
+
max: rules.maxBatchBytes,
|
|
130
|
+
provider: providerNames[rules.rules],
|
|
131
|
+
value: bytes
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
const isoTime = (time) => new Date(time).toISOString();
|
|
135
|
+
function toJobSummary(job, running) {
|
|
136
|
+
return {
|
|
137
|
+
attempts: job.attempts,
|
|
138
|
+
availableAt: isoTime(job.availableAt),
|
|
139
|
+
enqueuedAt: isoTime(job.enqueuedAt),
|
|
140
|
+
...job.error ? { error: job.error } : {},
|
|
141
|
+
...job.expiresAt === void 0 ? {} : { expiresAt: isoTime(job.expiresAt) },
|
|
142
|
+
...job.failedAt === void 0 ? {} : { failedAt: isoTime(job.failedAt) },
|
|
143
|
+
id: job.id,
|
|
144
|
+
queue: job.queue,
|
|
145
|
+
state: job.state === "dead" ? "dead" : running ? "running" : "pending"
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function createLocalQueueEngine(options) {
|
|
149
|
+
const base = resolve(options.base);
|
|
150
|
+
const rules = options.rules ?? localQueueDeliveryRules.local;
|
|
151
|
+
const retryDelayMs = options.retryDelayMs ?? rules.retryDelayMs;
|
|
152
|
+
const jobs = /* @__PURE__ */ new Map();
|
|
153
|
+
const running = /* @__PURE__ */ new Map();
|
|
154
|
+
const runningKeys = /* @__PURE__ */ new Set();
|
|
155
|
+
const writingKeys = /* @__PURE__ */ new Set();
|
|
156
|
+
const expiringKeys = /* @__PURE__ */ new Set();
|
|
157
|
+
const concurrency = /* @__PURE__ */ new Map();
|
|
158
|
+
let enqueueTail = Promise.resolve();
|
|
159
|
+
let started;
|
|
160
|
+
let timer;
|
|
161
|
+
let closed = false;
|
|
162
|
+
const file = (job) => join(base, `${job.key}.json`);
|
|
163
|
+
async function persist(job) {
|
|
164
|
+
const target = file(job);
|
|
165
|
+
await writeFile(`${target}.tmp`, JSON.stringify(job), "utf8");
|
|
166
|
+
await rename(`${target}.tmp`, target);
|
|
167
|
+
}
|
|
168
|
+
async function unlink(job) {
|
|
169
|
+
await rm(`${file(job)}.tmp`, { force: true });
|
|
170
|
+
await rm(file(job), { force: true });
|
|
171
|
+
}
|
|
172
|
+
function arm(at) {
|
|
173
|
+
if (timer) clearTimeout(timer);
|
|
174
|
+
timer = void 0;
|
|
175
|
+
if (closed || at === Number.POSITIVE_INFINITY) return;
|
|
176
|
+
timer = setTimeout(schedule, Math.min(Math.max(0, at - Date.now()), maxTimerDelay));
|
|
177
|
+
timer.unref?.();
|
|
178
|
+
}
|
|
179
|
+
function schedule() {
|
|
180
|
+
if (closed) return;
|
|
181
|
+
const now = Date.now();
|
|
182
|
+
let next = Number.POSITIVE_INFINITY;
|
|
183
|
+
for (const job of jobs.values()) {
|
|
184
|
+
if (job.state !== "pending" || runningKeys.has(job.key) || writingKeys.has(job.key) || expiringKeys.has(job.key)) continue;
|
|
185
|
+
if (job.expiresAt !== void 0 && job.expiresAt <= now) {
|
|
186
|
+
expire(job);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (job.availableAt > now) {
|
|
190
|
+
next = Math.min(next, job.availableAt, job.expiresAt ?? Number.POSITIVE_INFINITY);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if ((running.get(job.queue) ?? 0) < (concurrency.get(job.queue) ?? 1)) deliver(job);
|
|
194
|
+
}
|
|
195
|
+
arm(next);
|
|
196
|
+
}
|
|
197
|
+
/** Deletes the oldest dead jobs of `queue` above `localQueueDeadLimit`. */
|
|
198
|
+
async function pruneDead(queue) {
|
|
199
|
+
const dead = [...jobs.values()].filter((job) => job.queue === queue && job.state === "dead").sort((a, b) => (a.failedAt ?? 0) - (b.failedAt ?? 0));
|
|
200
|
+
for (const job of dead.slice(0, Math.max(0, dead.length - 100))) {
|
|
201
|
+
jobs.delete(job.key);
|
|
202
|
+
await unlink(job).catch((error) => {
|
|
203
|
+
console.error(`[vitehub:queue] The local provider cannot delete the dead job file ${file(job)}.`, error);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async function markDead(job, error, reason = `after ${job.attempts} attempts`) {
|
|
208
|
+
job.state = "dead";
|
|
209
|
+
job.error = error;
|
|
210
|
+
job.failedAt = Date.now();
|
|
211
|
+
console.error(`[vitehub:queue] The local provider stopped delivery of a "${job.queue}" job ${reason}. The job stays in ${file(job)}.`);
|
|
212
|
+
await persist(job);
|
|
213
|
+
delete job.payload;
|
|
214
|
+
await pruneDead(job.queue);
|
|
215
|
+
}
|
|
216
|
+
/** A job with a retention is not delivered after it expires, as on Vercel. */
|
|
217
|
+
async function expire(job) {
|
|
218
|
+
expiringKeys.add(job.key);
|
|
219
|
+
try {
|
|
220
|
+
await markDead(job, {
|
|
221
|
+
message: "[vitehub] The job expired at the end of its retention period.",
|
|
222
|
+
name: "Error"
|
|
223
|
+
}, "because its retention period ended");
|
|
224
|
+
} catch (error) {
|
|
225
|
+
console.error(`[vitehub:queue] The local provider cannot update the job file in ${base}.`, error);
|
|
226
|
+
} finally {
|
|
227
|
+
expiringKeys.delete(job.key);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
async function complete(job) {
|
|
231
|
+
job.state = "done";
|
|
232
|
+
try {
|
|
233
|
+
await unlink(job);
|
|
234
|
+
jobs.delete(job.key);
|
|
235
|
+
} catch (error) {
|
|
236
|
+
console.error(`[vitehub:queue] The local provider ran a job, but cannot delete ${file(job)}.`, error);
|
|
237
|
+
await persist(job).catch(() => {});
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
async function deliver(job) {
|
|
241
|
+
runningKeys.add(job.key);
|
|
242
|
+
running.set(job.queue, (running.get(job.queue) ?? 0) + 1);
|
|
243
|
+
try {
|
|
244
|
+
if (job.attempts >= rules.maxAttempts) {
|
|
245
|
+
await markDead(job, {
|
|
246
|
+
message: "[vitehub] The process stopped during the last attempt of this job.",
|
|
247
|
+
name: "Error"
|
|
248
|
+
});
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const attempts = job.attempts + 1;
|
|
252
|
+
await persist({
|
|
253
|
+
...job,
|
|
254
|
+
attempts
|
|
255
|
+
});
|
|
256
|
+
job.attempts = attempts;
|
|
257
|
+
let handled = false;
|
|
258
|
+
try {
|
|
259
|
+
const definition = await options.load(job.queue);
|
|
260
|
+
if (!definition) throw options.missing(job.queue);
|
|
261
|
+
const limit = Number(definition.concurrency ?? 1);
|
|
262
|
+
concurrency.set(job.queue, Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 1);
|
|
263
|
+
schedule();
|
|
264
|
+
await runInRunScopes(async () => {
|
|
265
|
+
checkQueueHandlerResponse(await definition.handler({
|
|
266
|
+
attempts: job.attempts,
|
|
267
|
+
id: job.id,
|
|
268
|
+
payload: job.payload
|
|
269
|
+
}));
|
|
270
|
+
});
|
|
271
|
+
handled = true;
|
|
272
|
+
} catch (error) {
|
|
273
|
+
const context = {
|
|
274
|
+
attempts: job.attempts,
|
|
275
|
+
development: options.development,
|
|
276
|
+
id: job.id,
|
|
277
|
+
provider: "local",
|
|
278
|
+
queue: job.queue
|
|
279
|
+
};
|
|
280
|
+
reportQueueDeliveryError(error, context);
|
|
281
|
+
if (isNonRetryableQueueError(error) || job.attempts >= rules.maxAttempts) await markDead(job, createQueueDeliveryErrorReport(error, context).error);
|
|
282
|
+
else {
|
|
283
|
+
job.availableAt = Date.now() + retryDelayMs(job.attempts);
|
|
284
|
+
job.error = createQueueDeliveryErrorReport(error, context).error;
|
|
285
|
+
await persist(job);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (handled) await complete(job);
|
|
289
|
+
} catch (storeError) {
|
|
290
|
+
job.availableAt = Date.now() + retryDelayMs(Math.max(1, job.attempts));
|
|
291
|
+
console.error(`[vitehub:queue] The local provider cannot update the job file in ${base}.`, storeError);
|
|
292
|
+
} finally {
|
|
293
|
+
runningKeys.delete(job.key);
|
|
294
|
+
running.set(job.queue, (running.get(job.queue) ?? 1) - 1);
|
|
295
|
+
schedule();
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async function recover() {
|
|
299
|
+
await mkdir(base, { recursive: true });
|
|
300
|
+
const recovered = [];
|
|
301
|
+
for (const name of await readdir(base)) {
|
|
302
|
+
if (!name.endsWith(".json")) continue;
|
|
303
|
+
try {
|
|
304
|
+
const job = JSON.parse(await readFile(join(base, name), "utf8"));
|
|
305
|
+
if (!isStoredJob(job) || `${job.key}.json` !== name) {
|
|
306
|
+
console.error(`[vitehub:queue] The local provider skips ${join(base, name)}: it is not a stored job.`);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (job.state === "done") {
|
|
310
|
+
await unlink(job).catch(() => {});
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (options.development !== true && job.error && !job.error.code) {
|
|
314
|
+
job.error = {
|
|
315
|
+
message: "[vitehub] Queue Delivery failed.",
|
|
316
|
+
name: "Error"
|
|
317
|
+
};
|
|
318
|
+
await persist(job);
|
|
319
|
+
}
|
|
320
|
+
if (job.state === "dead") delete job.payload;
|
|
321
|
+
recovered.push(job);
|
|
322
|
+
} catch (error) {
|
|
323
|
+
console.error(`[vitehub:queue] The local provider skips ${join(base, name)}: it cannot read it.`, error);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
for (const job of recovered.sort((a, b) => a.enqueuedAt - b.enqueuedAt)) jobs.set(job.key, job);
|
|
327
|
+
for (const queue of new Set(recovered.map((job) => job.queue))) await pruneDead(queue);
|
|
328
|
+
schedule();
|
|
329
|
+
}
|
|
330
|
+
/** The newest job with this message ID. Message IDs from the caller can repeat. */
|
|
331
|
+
function findJob(id) {
|
|
332
|
+
let found;
|
|
333
|
+
for (const job of jobs.values()) {
|
|
334
|
+
if (job.id !== id || job.state === "done" || writingKeys.has(job.key)) continue;
|
|
335
|
+
if (!found || job.enqueuedAt >= found.enqueuedAt) found = job;
|
|
336
|
+
}
|
|
337
|
+
return found;
|
|
338
|
+
}
|
|
339
|
+
/** Memory drops the payload of a dead job. Its file keeps it. */
|
|
340
|
+
async function readPayload(job) {
|
|
341
|
+
if (job.state !== "dead") return Object.hasOwn(job, "payload") ? { payload: job.payload } : {};
|
|
342
|
+
const stored = JSON.parse(await readFile(file(job), "utf8"));
|
|
343
|
+
return isStoredJob(stored) && Object.hasOwn(stored, "payload") ? { payload: stored.payload } : {};
|
|
344
|
+
}
|
|
345
|
+
return {
|
|
346
|
+
base,
|
|
347
|
+
async clear(filter = {}) {
|
|
348
|
+
await this.start();
|
|
349
|
+
let cleared = 0;
|
|
350
|
+
for (const job of [...jobs.values()]) {
|
|
351
|
+
if (job.state === "done" || runningKeys.has(job.key) || writingKeys.has(job.key) || expiringKeys.has(job.key)) continue;
|
|
352
|
+
if (filter.queue !== void 0 && job.queue !== filter.queue) continue;
|
|
353
|
+
if (filter.state !== void 0 && job.state !== filter.state) continue;
|
|
354
|
+
jobs.delete(job.key);
|
|
355
|
+
await unlink(job);
|
|
356
|
+
cleared++;
|
|
357
|
+
}
|
|
358
|
+
return cleared;
|
|
359
|
+
},
|
|
360
|
+
close() {
|
|
361
|
+
closed = true;
|
|
362
|
+
arm(Number.POSITIVE_INFINITY);
|
|
363
|
+
},
|
|
364
|
+
async enqueue(queue, entries) {
|
|
365
|
+
await this.start();
|
|
366
|
+
const enqueued = enqueueTail.then(async () => {
|
|
367
|
+
const now = Date.now();
|
|
368
|
+
const created = [];
|
|
369
|
+
const ids = [];
|
|
370
|
+
const prepared = entries.map((entry) => {
|
|
371
|
+
const { bytes, stored } = toStoredPayload(entry.payload);
|
|
372
|
+
checkPayloadSize(bytes, rules);
|
|
373
|
+
const retention = retentionMs(entry.retentionSeconds, rules);
|
|
374
|
+
return {
|
|
375
|
+
availableAt: now + delayMs(entry.delaySeconds, rules),
|
|
376
|
+
bytes,
|
|
377
|
+
entry,
|
|
378
|
+
...retention === void 0 ? {} : { expiresAt: now + retention },
|
|
379
|
+
stored
|
|
380
|
+
};
|
|
381
|
+
});
|
|
382
|
+
checkBatch(entries, prepared.reduce((total, item) => total + item.bytes, 0), rules);
|
|
383
|
+
for (const { availableAt, entry, expiresAt, stored } of prepared) {
|
|
384
|
+
const duplicate = entry.idempotencyKey === void 0 ? void 0 : [...jobs.values(), ...created].find((job) => job.queue === queue && job.state === "pending" && job.idempotencyKey === entry.idempotencyKey);
|
|
385
|
+
if (duplicate) {
|
|
386
|
+
ids.push(duplicate.id);
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
const job = {
|
|
390
|
+
attempts: 0,
|
|
391
|
+
availableAt,
|
|
392
|
+
enqueuedAt: now,
|
|
393
|
+
...expiresAt === void 0 ? {} : { expiresAt },
|
|
394
|
+
id: entry.id,
|
|
395
|
+
...entry.idempotencyKey === void 0 ? {} : { idempotencyKey: entry.idempotencyKey },
|
|
396
|
+
key: randomUUID(),
|
|
397
|
+
...stored,
|
|
398
|
+
queue,
|
|
399
|
+
state: "pending"
|
|
400
|
+
};
|
|
401
|
+
created.push(job);
|
|
402
|
+
ids.push(job.id);
|
|
403
|
+
}
|
|
404
|
+
for (const job of created) {
|
|
405
|
+
jobs.set(job.key, job);
|
|
406
|
+
writingKeys.add(job.key);
|
|
407
|
+
}
|
|
408
|
+
const written = await Promise.allSettled(created.map(persist));
|
|
409
|
+
for (const job of created) writingKeys.delete(job.key);
|
|
410
|
+
const failed = written.find((result) => result.status === "rejected");
|
|
411
|
+
if (failed) {
|
|
412
|
+
for (const job of created) jobs.delete(job.key);
|
|
413
|
+
await Promise.allSettled(created.map(unlink));
|
|
414
|
+
throw failed.reason;
|
|
415
|
+
}
|
|
416
|
+
schedule();
|
|
417
|
+
return ids;
|
|
418
|
+
});
|
|
419
|
+
enqueueTail = enqueued.then(() => void 0, () => void 0);
|
|
420
|
+
return enqueued;
|
|
421
|
+
},
|
|
422
|
+
async job(id) {
|
|
423
|
+
await this.start();
|
|
424
|
+
const job = findJob(id);
|
|
425
|
+
if (!job) return void 0;
|
|
426
|
+
return {
|
|
427
|
+
...toJobSummary(job, runningKeys.has(job.key)),
|
|
428
|
+
file: file(job),
|
|
429
|
+
...job.idempotencyKey === void 0 ? {} : { idempotencyKey: job.idempotencyKey },
|
|
430
|
+
...await readPayload(job)
|
|
431
|
+
};
|
|
432
|
+
},
|
|
433
|
+
async jobs() {
|
|
434
|
+
await this.start();
|
|
435
|
+
return [...jobs.values()].filter((job) => job.state !== "done" && !writingKeys.has(job.key)).sort((a, b) => b.enqueuedAt - a.enqueuedAt).map((job) => toJobSummary(job, runningKeys.has(job.key)));
|
|
436
|
+
},
|
|
437
|
+
async retry(id) {
|
|
438
|
+
await this.start();
|
|
439
|
+
const job = findJob(id);
|
|
440
|
+
if (!job) return "missing";
|
|
441
|
+
if (runningKeys.has(job.key) || expiringKeys.has(job.key)) return "running";
|
|
442
|
+
const now = Date.now();
|
|
443
|
+
if (job.state === "dead") {
|
|
444
|
+
const { payload } = await readPayload(job);
|
|
445
|
+
const retry = {
|
|
446
|
+
...job,
|
|
447
|
+
attempts: 0,
|
|
448
|
+
...payload === void 0 ? {} : { payload },
|
|
449
|
+
state: "pending"
|
|
450
|
+
};
|
|
451
|
+
delete retry.error;
|
|
452
|
+
delete retry.failedAt;
|
|
453
|
+
if (job.expiresAt !== void 0) {
|
|
454
|
+
retry.retentionMs = job.retentionMs ?? job.expiresAt - job.enqueuedAt;
|
|
455
|
+
retry.expiresAt = now + retry.retentionMs;
|
|
456
|
+
}
|
|
457
|
+
retry.availableAt = now;
|
|
458
|
+
await persist(retry);
|
|
459
|
+
jobs.set(job.key, retry);
|
|
460
|
+
schedule();
|
|
461
|
+
return toJobSummary(retry, runningKeys.has(retry.key));
|
|
462
|
+
}
|
|
463
|
+
job.availableAt = now;
|
|
464
|
+
await persist(job);
|
|
465
|
+
schedule();
|
|
466
|
+
return toJobSummary(job, runningKeys.has(job.key));
|
|
467
|
+
},
|
|
468
|
+
provider: "local",
|
|
469
|
+
rules,
|
|
470
|
+
start() {
|
|
471
|
+
started ??= recover();
|
|
472
|
+
return started;
|
|
473
|
+
},
|
|
474
|
+
async status() {
|
|
475
|
+
await this.start();
|
|
476
|
+
const queues = {};
|
|
477
|
+
for (const job of jobs.values()) {
|
|
478
|
+
if (job.state === "done") continue;
|
|
479
|
+
const entry = queues[job.queue] ??= {
|
|
480
|
+
dead: 0,
|
|
481
|
+
pending: 0,
|
|
482
|
+
running: 0
|
|
483
|
+
};
|
|
484
|
+
if (job.state === "dead") entry.dead++;
|
|
485
|
+
else if (runningKeys.has(job.key)) entry.running++;
|
|
486
|
+
else entry.pending++;
|
|
487
|
+
}
|
|
488
|
+
return {
|
|
489
|
+
base,
|
|
490
|
+
deadLimit: 100,
|
|
491
|
+
durability: "single-host",
|
|
492
|
+
queues
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
/** The provider of the rules rejects the option, so `vite dev` fails as the host does. */
|
|
498
|
+
function unsupportedOptions(options, rules) {
|
|
499
|
+
return queueUnsupportedOptionsError(options, rules.rules, rules.unsupportedOptions);
|
|
500
|
+
}
|
|
501
|
+
function createLocalQueueClient(engine, queue) {
|
|
502
|
+
const round = engine.rules.rules === "vercel" || engine.rules.rules === "cloudflare" ? "ceil" : void 0;
|
|
503
|
+
return {
|
|
504
|
+
provider: "local",
|
|
505
|
+
native: engine,
|
|
506
|
+
queue,
|
|
507
|
+
async send(payload, options) {
|
|
508
|
+
const normalized = normalizeQueueEnqueueInput(payload, options);
|
|
509
|
+
const optionsError = unsupportedOptions(normalized.options, engine.rules);
|
|
510
|
+
if (optionsError) return [optionsError, void 0];
|
|
511
|
+
const [timeError, times] = readQueueTimes(normalized.options, round);
|
|
512
|
+
if (timeError) return [timeError, void 0];
|
|
513
|
+
const [error, ids] = await queueProviderResult("local", "send", () => engine.enqueue(queue, [{
|
|
514
|
+
...times,
|
|
515
|
+
id: normalized.id,
|
|
516
|
+
idempotencyKey: normalized.options.idempotencyKey,
|
|
517
|
+
payload: normalized.payload
|
|
518
|
+
}]));
|
|
519
|
+
if (error) return [error, void 0];
|
|
520
|
+
return [void 0, {
|
|
521
|
+
messageId: ids[0],
|
|
522
|
+
status: "queued"
|
|
523
|
+
}];
|
|
524
|
+
},
|
|
525
|
+
async sendBatch(items, options) {
|
|
526
|
+
const removed = queueRemovedOptionsError(engine.rules.rules, options, items);
|
|
527
|
+
if (removed) return [removed, void 0];
|
|
528
|
+
const entries = [];
|
|
529
|
+
for (const item of items) {
|
|
530
|
+
const retention = ("retention" in item ? item.retention : void 0) ?? (options && "retention" in options ? options.retention : void 0);
|
|
531
|
+
const [timeError, times] = readQueueTimes({
|
|
532
|
+
delay: item.delay ?? options?.delay,
|
|
533
|
+
retention
|
|
534
|
+
}, round);
|
|
535
|
+
if (timeError) return [timeError, void 0];
|
|
536
|
+
entries.push({
|
|
537
|
+
...times,
|
|
538
|
+
id: createQueueMessageId(),
|
|
539
|
+
idempotencyKey: item.idempotencyKey,
|
|
540
|
+
payload: item.body
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
const [error, ids] = await queueProviderResult("local", "send-batch", () => engine.enqueue(queue, entries));
|
|
544
|
+
if (error) return [error, void 0];
|
|
545
|
+
return [void 0, ids.map((messageId) => ({
|
|
546
|
+
messageId,
|
|
547
|
+
status: "queued"
|
|
548
|
+
}))];
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
//#endregion
|
|
553
|
+
export { localQueueDeliveryRules as i, createLocalQueueEngine as n, delayMs as r, createLocalQueueClient as t };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//#region ../internal/src/object.ts
|
|
2
|
+
/** A non-null object that is not an array. Functions do not pass. */
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
/** A non-null object or a function that is not an array. */
|
|
7
|
+
function isRecordOrFunction(value) {
|
|
8
|
+
return Object(value) === value && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
/** A shallow copy of a non-array object, or an empty object for any other value. */
|
|
11
|
+
function cloneRecord(value) {
|
|
12
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { isRecord as n, isRecordOrFunction as r, cloneRecord as t };
|
|
@@ -75,7 +75,7 @@ declare namespace StandardSchemaV1 {
|
|
|
75
75
|
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
|
76
76
|
}
|
|
77
77
|
//#endregion
|
|
78
|
-
//#region ../internal/src/
|
|
78
|
+
//#region ../internal/src/operation-definition.d.ts
|
|
79
79
|
/** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
|
|
80
80
|
type OperationKind = "read" | "write" | "destructive";
|
|
81
81
|
/** The signed-in user of a call. */
|
|
@@ -98,7 +98,9 @@ interface OperationAccess {
|
|
|
98
98
|
readonly mode: string;
|
|
99
99
|
/**
|
|
100
100
|
* The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
|
|
101
|
-
* operation of the section)
|
|
101
|
+
* operation of the section), `"<section>:read"` (only the operations that read), or `"<section>:<scope>"` (only the
|
|
102
|
+
* calls of a scoped operation for that scope, such as `"blob:media"` for one Blob store). `"<section>:<scope>:read"`
|
|
103
|
+
* allows only the reads of that scope.
|
|
102
104
|
*/
|
|
103
105
|
readonly sections: "all" | readonly string[];
|
|
104
106
|
readonly user?: OperationUser;
|
|
@@ -113,9 +115,20 @@ interface OperationContext {
|
|
|
113
115
|
surface: "console" | "cli" | "mcp" | "agent";
|
|
114
116
|
/** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
|
|
115
117
|
development?: boolean;
|
|
118
|
+
/**
|
|
119
|
+
* The project root of a development server, for operations that read build files, such as `bundle.report`. Hosts set
|
|
120
|
+
* it only with `development`, so a deployed server never reads project files through it.
|
|
121
|
+
*/
|
|
122
|
+
projectRoot?: string;
|
|
116
123
|
env?: Record<string, unknown>;
|
|
117
124
|
waitUntil?: (task: Promise<unknown>) => void;
|
|
118
125
|
request?: Request;
|
|
126
|
+
/**
|
|
127
|
+
* The request event of the HTTP request that carries the call, when there is one: the Request of the Console route,
|
|
128
|
+
* with its Standard Context. Operations hand it to app hooks that read the request's own session, such as `identify`
|
|
129
|
+
* of Comments.
|
|
130
|
+
*/
|
|
131
|
+
event?: unknown;
|
|
119
132
|
/** Operations set a success status here, such as 202 for an accepted call. */
|
|
120
133
|
response?: {
|
|
121
134
|
status?: number;
|
|
@@ -138,9 +151,16 @@ interface OperationDefinition<Input, Output> {
|
|
|
138
151
|
description: string;
|
|
139
152
|
/**
|
|
140
153
|
* Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
|
|
141
|
-
* from the input, for operations that serve several sections.
|
|
154
|
+
* from the input, for operations that serve several sections. Section ids cannot contain `:`; it is reserved for
|
|
155
|
+
* scope and read-only grants. A function that returns an invalid id denies the call.
|
|
142
156
|
*/
|
|
143
157
|
section: string | false | ((input: Input) => string | undefined);
|
|
158
|
+
/**
|
|
159
|
+
* The part of a string `section` that one call uses, such as the Blob store that the input names. The call then needs
|
|
160
|
+
* the section (every scope) or `"<section>:<scope>"` (only this scope). A scope that is empty, is `read`, or has a
|
|
161
|
+
* `:` needs the whole section.
|
|
162
|
+
*/
|
|
163
|
+
scope?: (input: Input) => string | undefined;
|
|
144
164
|
/** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
|
|
145
165
|
kind: OperationKind;
|
|
146
166
|
/** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
|
|
@@ -149,19 +169,14 @@ interface OperationDefinition<Input, Output> {
|
|
|
149
169
|
cli?: {
|
|
150
170
|
/** Defaults: namespace = section, command = verb. */
|
|
151
171
|
namespace?: string;
|
|
172
|
+
/** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
|
|
152
173
|
command?: string;
|
|
153
174
|
/** Input keys read from positional arguments, in order. */
|
|
154
175
|
positional?: string[];
|
|
155
176
|
/** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
|
|
156
177
|
format?: (output: Output) => string;
|
|
157
|
-
/** `vitehub <namespace>` runs this command when no command is named
|
|
178
|
+
/** `vitehub <namespace>` runs this command when no command is named. */
|
|
158
179
|
default?: boolean;
|
|
159
|
-
/**
|
|
160
|
-
* Route of the app that takes a signed dispatch of this operation, such as `/_vitehub/schedules/run`. With `--url`
|
|
161
|
-
* and a dispatch key in the environment (`VITEHUB_DISPATCH_KEY`), the command signs the input and posts it there, so
|
|
162
|
-
* a CI job needs no Console credentials. Without a key it calls the RPC.
|
|
163
|
-
*/
|
|
164
|
-
dispatch?: string;
|
|
165
180
|
};
|
|
166
181
|
/** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
|
|
167
182
|
maxRequestBytes?: number;
|
|
@@ -170,8 +185,16 @@ interface OperationDefinition<Input, Output> {
|
|
|
170
185
|
* confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
|
|
171
186
|
*/
|
|
172
187
|
readOnlyWhen?: (input: Input) => boolean;
|
|
173
|
-
/**
|
|
174
|
-
|
|
188
|
+
/**
|
|
189
|
+
* How MCP offers the operation as a tool. `false`: MCP does not offer it, such as an editor transport that only the
|
|
190
|
+
* Console uses. `title`: the short title that clients show, instead of the name in words. `format`: the text of a
|
|
191
|
+
* result for the Agent, such as a list of lines. The result stays the structured content. Without `format`, the text
|
|
192
|
+
* is the result as JSON.
|
|
193
|
+
*/
|
|
194
|
+
mcp?: false | {
|
|
195
|
+
title?: string;
|
|
196
|
+
format?: (output: NoInfer<Output>) => string;
|
|
197
|
+
};
|
|
175
198
|
/** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
|
|
176
199
|
user?: false;
|
|
177
200
|
/**
|
|
@@ -182,24 +205,28 @@ interface OperationDefinition<Input, Output> {
|
|
|
182
205
|
run: (input: Input, context: OperationContext) => Output | Promise<Output>;
|
|
183
206
|
}
|
|
184
207
|
/** An operation of any input and output, as a registry holds it. */
|
|
185
|
-
interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "output" | "readOnlyWhen" | "run" | "section"> {
|
|
208
|
+
interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
|
|
186
209
|
readOnlyWhen?: (input: never) => boolean;
|
|
187
210
|
cli?: {
|
|
188
211
|
namespace?: string;
|
|
189
212
|
command?: string;
|
|
190
213
|
default?: boolean;
|
|
191
|
-
dispatch?: string;
|
|
192
214
|
positional?: string[];
|
|
193
215
|
format?: (output: never) => string;
|
|
194
216
|
};
|
|
217
|
+
mcp?: false | {
|
|
218
|
+
title?: string;
|
|
219
|
+
format?: (output: never) => string;
|
|
220
|
+
};
|
|
195
221
|
input: StandardSchemaV1;
|
|
196
222
|
output?: StandardSchemaV1;
|
|
197
223
|
run: (input: never, context: OperationContext) => unknown;
|
|
224
|
+
scope?: (input: never) => string | undefined;
|
|
198
225
|
section: string | false | ((input: never) => string | undefined);
|
|
199
226
|
}
|
|
200
227
|
/** The contribution of one plugin: operations, or a module that exports them. */
|
|
201
228
|
interface OperationContributionEntry {
|
|
202
|
-
/**
|
|
229
|
+
/** The absolute path of the module that generated code imports, such as `ownModule(import.meta.url, "operations")`. */
|
|
203
230
|
module: string;
|
|
204
231
|
/** Named export that holds an operation or an array of operations. Defaults to `default`. */
|
|
205
232
|
export?: string;
|