experimental-a2 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +169 -0
- package/dist/ai-B4YhEnfw.d.ts +333 -0
- package/dist/ai-server.d.ts +48 -9
- package/dist/ai-server.js +121 -49
- package/dist/ai.d.ts +2 -303
- package/dist/ai.js +231 -86
- package/dist/cli-B3VuxoDe.js +597 -0
- package/dist/cli-bin.d.ts +1 -0
- package/dist/cli-bin.js +5 -0
- package/dist/cli.d.ts +19 -0
- package/dist/cli.js +2 -0
- package/dist/client-BrfDXQ8A.d.ts +155 -0
- package/dist/client-Bt4tAKi9.js +798 -0
- package/dist/client.d.ts +2 -90
- package/dist/client.js +1 -409
- package/dist/{contract-CG_adnu_.js → contract-48bUMgcL.js} +10 -2
- package/dist/{contract-C_3dIIEU.d.ts → contract-jIfaR085.d.ts} +62 -8
- package/dist/devtools-J_jZ2vQf.d.ts +151 -0
- package/dist/devtools-kJJaORn-.js +338 -0
- package/dist/devtools-server.browser.js +1 -1
- package/dist/devtools-server.d.ts +2 -2
- package/dist/devtools-server.js +224 -43
- package/dist/devtools.d.ts +2 -0
- package/dist/devtools.js +2 -0
- package/dist/{errors-BJRMd-h6.js → errors-BQuJpe82.js} +4 -4
- package/dist/{errors-xL_JTXsY.d.ts → errors-W6nwJ-fm.d.ts} +1 -1
- package/dist/http.d.ts +71 -13
- package/dist/http.js +302 -41
- package/dist/{idempotent-replay-BMyHrP0L.js → idempotent-replay-DuqEkYA7.js} +2 -2
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/{inspection-E7qbD0Xj.js → inspection-DaxB5jM2.js} +2 -1
- package/dist/internal-aEotMzu_.js +209 -0
- package/dist/otel.d.ts +1 -1
- package/dist/platform-B4TnJtWu.js +32 -0
- package/dist/react.d.ts +37 -14
- package/dist/react.js +26 -15
- package/dist/scheduler-qstash.d.ts +78 -0
- package/dist/scheduler-qstash.js +499 -0
- package/dist/scheduler-task-BpzhPnRS.js +54 -0
- package/dist/{recovery-vercel.d.ts → scheduler-vercel.d.ts} +17 -24
- package/dist/scheduler-vercel.js +226 -0
- package/dist/server-CcNnFnoW.js +1405 -0
- package/dist/server-YtPq7hjw.d.ts +260 -0
- package/dist/server.d.ts +4 -155
- package/dist/server.js +2 -2
- package/dist/{log-ldf5g8Cx.d.ts → store-C3sNAaBT.d.ts} +111 -35
- package/dist/{log-yJbXUf72.js → store-N8PXxDAS.js} +1 -1
- package/dist/store-codec-DTG0Ftek.js +8 -0
- package/dist/store-memory.d.ts +11 -0
- package/dist/{log-memory.js → store-memory.js} +127 -24
- package/dist/{log-polling-6COoN60V.js → store-polling-DgrrAE3d.js} +7 -6
- package/dist/{log-postgres.d.ts → store-postgres.d.ts} +6 -6
- package/dist/{log-postgres.js → store-postgres.js} +158 -24
- package/dist/{log-redis.js → store-redis-core-DWqx3F47.js} +294 -156
- package/dist/store-redis-http.d.ts +21 -0
- package/dist/store-redis-http.js +70 -0
- package/dist/store-redis.d.ts +37 -0
- package/dist/store-redis.js +298 -0
- package/dist/{log-sqlite.d.ts → store-sqlite.d.ts} +6 -6
- package/dist/{log-sqlite.js → store-sqlite.js} +116 -22
- package/dist/{telemetry-Cso0qyHQ.d.ts → telemetry-BjYHTfh2.d.ts} +1 -1
- package/dist/testing.browser.d.ts +1 -0
- package/dist/testing.browser.js +4 -0
- package/dist/testing.d.ts +31 -0
- package/dist/testing.js +101 -0
- package/dist/wire-DCUZBUlT.js +222 -0
- package/docs/01-quickstart.mdx +4 -5
- package/docs/concepts/01-contracts.mdx +21 -17
- package/docs/concepts/02-handlers.mdx +7 -7
- package/docs/concepts/03-durability.mdx +26 -29
- package/docs/concepts/04-state.mdx +18 -21
- package/docs/guides/01-timers.mdx +154 -54
- package/docs/guides/02-cancellation.mdx +30 -4
- package/docs/guides/03-react.mdx +20 -21
- package/docs/guides/04-local-first.mdx +1 -1
- package/docs/guides/05-production.mdx +321 -60
- package/docs/guides/06-ai-agents.mdx +249 -49
- package/docs/guides/07-devtools.mdx +137 -12
- package/docs/guides/08-application-data.mdx +1 -1
- package/docs/guides/09-presence.mdx +284 -0
- package/docs/guides/10-transports.mdx +131 -0
- package/docs/index.mdx +22 -46
- package/docs/reference/01-api.mdx +751 -102
- package/docs/reference/02-errors.mdx +10 -5
- package/package.json +23 -6
- package/dist/internal-D6wNxTck.js +0 -36
- package/dist/log-memory.d.ts +0 -11
- package/dist/log-redis.d.ts +0 -31
- package/dist/recovery-vercel.js +0 -119
- package/dist/server-DJgD2YWP.js +0 -877
- package/dist/wire-BVsgR8o9.js +0 -62
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
import { t as A2Error } from "./errors-BQuJpe82.js";
|
|
2
|
+
import { f as classifySchedulerSendFailure, t as DRAIN_TIMINGS, u as assertSchedulerTargets, v as serverInternals } from "./internal-aEotMzu_.js";
|
|
3
|
+
import { n as deliverSchedulerAppend } from "./server-CcNnFnoW.js";
|
|
4
|
+
import { n as platformVercelOidcToken } from "./platform-B4TnJtWu.js";
|
|
5
|
+
import { t as retryableLazy } from "./retryable-lazy-DZWmHpii.js";
|
|
6
|
+
import { n as SYSTEM_CLOCK } from "./store-N8PXxDAS.js";
|
|
7
|
+
import { t as normalizeSchedulerTask } from "./scheduler-task-BpzhPnRS.js";
|
|
8
|
+
//#region src/scheduler-qstash.ts
|
|
9
|
+
/**
|
|
10
|
+
* experimental-a2/scheduler-qstash — HTTP scheduler over Upstash QStash.
|
|
11
|
+
*
|
|
12
|
+
* QStash publishes one signed HTTP delivery per scheduler task. Drain tasks
|
|
13
|
+
* use an absolute, whole-second `notBefore` and a fixed-size deduplication id;
|
|
14
|
+
* append tasks hash their stable task id with the callback URL.
|
|
15
|
+
* Store-outage successors carry a signed private generation and back off to
|
|
16
|
+
* one day without deriving their deduplication identity from the local clock.
|
|
17
|
+
* `handler(...servers)` verifies the signature over the raw request body
|
|
18
|
+
* before parsing it, then applies the same drain protocol as the Vercel
|
|
19
|
+
* scheduler adapter.
|
|
20
|
+
*
|
|
21
|
+
* `@upstash/qstash` is an optional peer dependency, imported lazily. The
|
|
22
|
+
* structural `transport` option keeps its types out of A2's public surface and
|
|
23
|
+
* gives tests a provider-faithful injection seam.
|
|
24
|
+
*/
|
|
25
|
+
const qstashTransport = async (options, developmentMode) => {
|
|
26
|
+
const sdk = await import("@upstash/qstash").catch(() => {
|
|
27
|
+
throw classifySchedulerSendFailure(/* @__PURE__ */ new Error("experimental-a2/scheduler-qstash needs the '@upstash/qstash' package (optional peer dependency) — install it, or inject a transport"), "terminal");
|
|
28
|
+
});
|
|
29
|
+
const developmentOverride = developmentMode === void 0 ? {} : { devMode: developmentMode };
|
|
30
|
+
const client = options.client ?? new sdk.Client({
|
|
31
|
+
...options.token === void 0 ? {} : { token: options.token },
|
|
32
|
+
...developmentOverride
|
|
33
|
+
});
|
|
34
|
+
const receiver = new sdk.Receiver({
|
|
35
|
+
...options.currentSigningKey === void 0 ? {} : { currentSigningKey: options.currentSigningKey },
|
|
36
|
+
...options.nextSigningKey === void 0 ? {} : { nextSigningKey: options.nextSigningKey },
|
|
37
|
+
...developmentOverride
|
|
38
|
+
});
|
|
39
|
+
return {
|
|
40
|
+
publish: (request) => {
|
|
41
|
+
const clientRequest = {
|
|
42
|
+
url: request.url,
|
|
43
|
+
body: request.body,
|
|
44
|
+
...request.headers === void 0 ? {} : { headers: { ...request.headers } },
|
|
45
|
+
...request.redact === void 0 ? {} : { redact: { header: [...request.redact.header] } },
|
|
46
|
+
deduplicationId: request.deduplicationId,
|
|
47
|
+
...request.retries === void 0 ? {} : { retries: request.retries },
|
|
48
|
+
...request.notBefore === void 0 ? {} : { notBefore: request.notBefore }
|
|
49
|
+
};
|
|
50
|
+
return client.publishJSON(clientRequest);
|
|
51
|
+
},
|
|
52
|
+
verify: (request) => receiver.verify(request)
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
const digestId = async (parts) => {
|
|
56
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(parts)));
|
|
57
|
+
return `a2_${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
58
|
+
};
|
|
59
|
+
const recordOf = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
60
|
+
const TRUSTED_SOURCE_HEADER = "x-vercel-trusted-oidc-idp-token";
|
|
61
|
+
const TRUSTED_SOURCE_DELIVERY_MARGIN_MS = 6e4;
|
|
62
|
+
const RESERVED_CALLBACK_HEADERS = /* @__PURE__ */ new Set([
|
|
63
|
+
"connection",
|
|
64
|
+
"content-length",
|
|
65
|
+
"host",
|
|
66
|
+
"keep-alive",
|
|
67
|
+
"proxy-authenticate",
|
|
68
|
+
"proxy-authorization",
|
|
69
|
+
"te",
|
|
70
|
+
"trailer",
|
|
71
|
+
"transfer-encoding",
|
|
72
|
+
"upgrade",
|
|
73
|
+
"x-vercel-oidc-token",
|
|
74
|
+
TRUSTED_SOURCE_HEADER
|
|
75
|
+
]);
|
|
76
|
+
const callbackHeaders = (value) => {
|
|
77
|
+
if (value === void 0) return void 0;
|
|
78
|
+
let entries;
|
|
79
|
+
try {
|
|
80
|
+
entries = Object.entries(value);
|
|
81
|
+
} catch {
|
|
82
|
+
throw new TypeError("qstash() headers must be an HTTP header record");
|
|
83
|
+
}
|
|
84
|
+
const normalized = [];
|
|
85
|
+
const seen = /* @__PURE__ */ new Set();
|
|
86
|
+
for (const [name, headerValue] of entries) {
|
|
87
|
+
if (typeof headerValue !== "string") throw new TypeError("qstash() header values must be strings");
|
|
88
|
+
let entry;
|
|
89
|
+
try {
|
|
90
|
+
entry = [...new Headers([[name, headerValue]]).entries()][0];
|
|
91
|
+
} catch {
|
|
92
|
+
throw new TypeError("qstash() headers must contain valid HTTP header names and values");
|
|
93
|
+
}
|
|
94
|
+
if (entry === void 0) throw new TypeError("qstash() headers must contain valid HTTP header names and values");
|
|
95
|
+
const [normalizedName, normalizedValue] = entry;
|
|
96
|
+
if (seen.has(normalizedName)) throw new TypeError(`qstash() headers contain duplicate name '${normalizedName}'`);
|
|
97
|
+
if (normalizedName.startsWith("upstash-") || normalizedName.startsWith("content-type") || RESERVED_CALLBACK_HEADERS.has(normalizedName)) throw new TypeError(`qstash() headers cannot set reserved header '${normalizedName}'`);
|
|
98
|
+
seen.add(normalizedName);
|
|
99
|
+
normalized.push([normalizedName, normalizedValue]);
|
|
100
|
+
}
|
|
101
|
+
return normalized.length === 0 ? void 0 : Object.freeze(Object.fromEntries(normalized));
|
|
102
|
+
};
|
|
103
|
+
const publishHeaders = (configured, generated) => {
|
|
104
|
+
if (configured === void 0 && generated === void 0) return void 0;
|
|
105
|
+
const headers = new Headers();
|
|
106
|
+
const redacted = /* @__PURE__ */ new Set();
|
|
107
|
+
for (const [name, value] of Object.entries(configured ?? {})) {
|
|
108
|
+
headers.set(name, value);
|
|
109
|
+
redacted.add(name);
|
|
110
|
+
}
|
|
111
|
+
for (const [name, value] of Object.entries(generated?.headers ?? {})) {
|
|
112
|
+
headers.set(name, value);
|
|
113
|
+
redacted.add(name);
|
|
114
|
+
}
|
|
115
|
+
for (const name of generated?.redact?.header ?? []) {
|
|
116
|
+
const normalized = [...new Headers([[name, "redacted"]]).keys()][0];
|
|
117
|
+
if (normalized === void 0) throw new TypeError("qstash generated an invalid redaction header");
|
|
118
|
+
redacted.add(normalized);
|
|
119
|
+
}
|
|
120
|
+
const headerEntries = [...headers.entries()];
|
|
121
|
+
return {
|
|
122
|
+
...headerEntries.length === 0 ? {} : { headers: Object.fromEntries(headerEntries) },
|
|
123
|
+
...redacted.size === 0 ? {} : { redact: { header: [...redacted].toSorted() } }
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
const jwtExpirationMs = (token) => {
|
|
127
|
+
const parts = token.split(".");
|
|
128
|
+
const payloadPart = parts.length === 3 ? parts[1] : void 0;
|
|
129
|
+
if (payloadPart === void 0 || payloadPart.length === 0 || !/^[A-Za-z0-9_-]+$/.test(payloadPart) || payloadPart.length % 4 === 1) return null;
|
|
130
|
+
try {
|
|
131
|
+
const decode = globalThis.atob;
|
|
132
|
+
if (typeof decode !== "function") return null;
|
|
133
|
+
const binary = decode(payloadPart.replaceAll("-", "+").replaceAll("_", "/").padEnd(payloadPart.length + (4 - payloadPart.length % 4) % 4, "="));
|
|
134
|
+
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
135
|
+
const expiration = recordOf(JSON.parse(new TextDecoder().decode(bytes)))?.["exp"];
|
|
136
|
+
if (typeof expiration !== "number" || !Number.isSafeInteger(expiration) || expiration <= 0 || expiration > Number.MAX_SAFE_INTEGER / 1e3) return null;
|
|
137
|
+
return expiration * 1e3;
|
|
138
|
+
} catch {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
const previewTrustedSource = (firstDeliveryAt) => {
|
|
143
|
+
const token = platformVercelOidcToken();
|
|
144
|
+
if (token === null) return void 0;
|
|
145
|
+
const expiration = jwtExpirationMs(token);
|
|
146
|
+
if (expiration === null || firstDeliveryAt + TRUSTED_SOURCE_DELIVERY_MARGIN_MS > expiration) return;
|
|
147
|
+
return {
|
|
148
|
+
headers: { [TRUSTED_SOURCE_HEADER]: token },
|
|
149
|
+
redact: { header: [TRUSTED_SOURCE_HEADER] }
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
const RETRYABLE_HTTP_CLIENT_STATUSES = /* @__PURE__ */ new Set([
|
|
153
|
+
408,
|
|
154
|
+
409,
|
|
155
|
+
425,
|
|
156
|
+
429
|
|
157
|
+
]);
|
|
158
|
+
const httpStatusOf = (error) => {
|
|
159
|
+
try {
|
|
160
|
+
const record = recordOf(error);
|
|
161
|
+
if (!record) return void 0;
|
|
162
|
+
const response = recordOf(record["response"]);
|
|
163
|
+
const statuses = [
|
|
164
|
+
record["status"],
|
|
165
|
+
record["statusCode"],
|
|
166
|
+
response?.["status"]
|
|
167
|
+
].filter((value) => typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599);
|
|
168
|
+
const [status] = statuses;
|
|
169
|
+
if (status === void 0) return void 0;
|
|
170
|
+
return statuses.every((candidate) => candidate === status) ? status : void 0;
|
|
171
|
+
} catch {
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const classifyQStashPublishFailure = (error) => {
|
|
176
|
+
const status = httpStatusOf(error);
|
|
177
|
+
const terminal = status !== void 0 && status >= 400 && status < 500 && !RETRYABLE_HTTP_CLIENT_STATUSES.has(status);
|
|
178
|
+
return classifySchedulerSendFailure(error, terminal ? "terminal" : "retryable");
|
|
179
|
+
};
|
|
180
|
+
const parseTask = (body) => {
|
|
181
|
+
let value;
|
|
182
|
+
try {
|
|
183
|
+
value = JSON.parse(body);
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
const task = normalizeSchedulerTask(value);
|
|
188
|
+
const record = recordOf(value);
|
|
189
|
+
if (!task || !record) return null;
|
|
190
|
+
const encodedOutage = record["_a2QStash"];
|
|
191
|
+
if (encodedOutage === void 0) return { task };
|
|
192
|
+
const outage = recordOf(encodedOutage);
|
|
193
|
+
const generation = outage?.["generation"];
|
|
194
|
+
if (!outage || outage["version"] !== 1 || typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0 || generation >= Number.MAX_SAFE_INTEGER) return null;
|
|
195
|
+
const rootDueAt = outage["rootDueAt"];
|
|
196
|
+
if (task.kind === "drain") {
|
|
197
|
+
if (typeof rootDueAt !== "number" || !Number.isInteger(rootDueAt) || rootDueAt % 1e3 !== 0) return null;
|
|
198
|
+
} else if (rootDueAt !== void 0) return null;
|
|
199
|
+
return {
|
|
200
|
+
task,
|
|
201
|
+
outage: {
|
|
202
|
+
version: 1,
|
|
203
|
+
generation,
|
|
204
|
+
...rootDueAt === void 0 ? {} : { rootDueAt }
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
const DEFAULT_MAX_BODY_BYTES = 1048576;
|
|
209
|
+
const STORE_OUTAGE_BASE_DELAY_MS = 3e4;
|
|
210
|
+
const STORE_OUTAGE_MAX_DELAY_MS = 864e5;
|
|
211
|
+
const readBoundedBody = async (request, maxBytes) => {
|
|
212
|
+
const declared = request.headers.get("content-length");
|
|
213
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) return null;
|
|
214
|
+
if (request.body === null) return "";
|
|
215
|
+
const reader = request.body.getReader();
|
|
216
|
+
const chunks = [];
|
|
217
|
+
let length = 0;
|
|
218
|
+
try {
|
|
219
|
+
for (;;) {
|
|
220
|
+
const { done, value } = await reader.read();
|
|
221
|
+
if (done) break;
|
|
222
|
+
length += value.byteLength;
|
|
223
|
+
if (length > maxBytes) {
|
|
224
|
+
await reader.cancel().catch(() => {});
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
chunks.push(value);
|
|
228
|
+
}
|
|
229
|
+
} finally {
|
|
230
|
+
reader.releaseLock();
|
|
231
|
+
}
|
|
232
|
+
const bytes = new Uint8Array(length);
|
|
233
|
+
let offset = 0;
|
|
234
|
+
for (const chunk of chunks) {
|
|
235
|
+
bytes.set(chunk, offset);
|
|
236
|
+
offset += chunk.byteLength;
|
|
237
|
+
}
|
|
238
|
+
return new TextDecoder().decode(bytes);
|
|
239
|
+
};
|
|
240
|
+
const storeUnavailable = (error) => error instanceof A2Error && error.code === "STORE_UNAVAILABLE";
|
|
241
|
+
const response = {
|
|
242
|
+
ok: () => new Response("ok"),
|
|
243
|
+
unauthorized: () => new Response("unauthorized", { status: 401 }),
|
|
244
|
+
malformed: () => new Response("invalid a2 scheduler message", {
|
|
245
|
+
status: 489,
|
|
246
|
+
headers: { "Upstash-NonRetryable-Error": "true" }
|
|
247
|
+
}),
|
|
248
|
+
tooLarge: () => new Response("a2 scheduler message is too large", {
|
|
249
|
+
status: 489,
|
|
250
|
+
headers: { "Upstash-NonRetryable-Error": "true" }
|
|
251
|
+
})
|
|
252
|
+
};
|
|
253
|
+
const CALLBACK_PATH = "/api/a2/scheduler";
|
|
254
|
+
const DEFAULT_DEVELOPMENT_PORT = 3e3;
|
|
255
|
+
const developmentCallbackUrl = (portValue) => {
|
|
256
|
+
const port = portValue === void 0 || portValue === "" ? DEFAULT_DEVELOPMENT_PORT : Number(portValue);
|
|
257
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65535 || portValue !== void 0 && portValue !== "" && !/^\d+$/.test(portValue)) throw new TypeError("qstash() could not infer url: PORT must be an integer from 1 to 65535 for local development");
|
|
258
|
+
return `http://localhost:${String(port)}${CALLBACK_PATH}`;
|
|
259
|
+
};
|
|
260
|
+
const inferCallbackUrl = () => {
|
|
261
|
+
const env = typeof process === "undefined" ? void 0 : process.env;
|
|
262
|
+
const vercelEnv = env?.["VERCEL_ENV"];
|
|
263
|
+
const variable = env?.["VERCEL"] !== "1" ? null : vercelEnv === "production" ? "VERCEL_PROJECT_PRODUCTION_URL" : vercelEnv === "preview" ? "VERCEL_BRANCH_URL" : null;
|
|
264
|
+
if (variable !== null) {
|
|
265
|
+
const host = env?.[variable];
|
|
266
|
+
if (!host) throw new TypeError(`qstash() could not infer url: ${variable} is missing`);
|
|
267
|
+
let origin;
|
|
268
|
+
try {
|
|
269
|
+
origin = new URL(`https://${host}`);
|
|
270
|
+
} catch {
|
|
271
|
+
throw new TypeError(`qstash() could not infer url: ${variable} must be a hostname`);
|
|
272
|
+
}
|
|
273
|
+
if (origin.host !== host || origin.pathname !== "/" || origin.search !== "" || origin.hash !== "" || origin.username !== "" || origin.password !== "" || origin.port !== "") throw new TypeError(`qstash() could not infer url: ${variable} must be a hostname`);
|
|
274
|
+
return {
|
|
275
|
+
callbackUrl: new URL(CALLBACK_PATH, origin).toString(),
|
|
276
|
+
developmentMode: false,
|
|
277
|
+
...vercelEnv === "preview" ? { inferredVercelPreview: true } : {}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
if (env === void 0) throw new TypeError("qstash() needs url when the runtime cannot identify local development");
|
|
281
|
+
if (env["NODE_ENV"] === "production") throw new TypeError("qstash() needs url in production outside a Vercel production or preview deployment");
|
|
282
|
+
return {
|
|
283
|
+
callbackUrl: developmentCallbackUrl(env["PORT"]),
|
|
284
|
+
developmentMode: true
|
|
285
|
+
};
|
|
286
|
+
};
|
|
287
|
+
function qstash(options = {}) {
|
|
288
|
+
const env = typeof process === "undefined" ? void 0 : process.env;
|
|
289
|
+
const { callbackUrl, developmentMode, inferredVercelPreview } = options.url === void 0 ? inferCallbackUrl() : {
|
|
290
|
+
callbackUrl: options.url,
|
|
291
|
+
...env?.["NODE_ENV"] === "production" ? { developmentMode: false } : {}
|
|
292
|
+
};
|
|
293
|
+
let parsedUrl;
|
|
294
|
+
try {
|
|
295
|
+
parsedUrl = new URL(callbackUrl);
|
|
296
|
+
} catch {
|
|
297
|
+
throw new TypeError("qstash() needs an absolute callback url");
|
|
298
|
+
}
|
|
299
|
+
if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") throw new TypeError("qstash() callback url must use http or https");
|
|
300
|
+
if (options.client !== void 0 && options.transport !== void 0) throw new TypeError("qstash() cannot combine client and transport");
|
|
301
|
+
if (options.client !== void 0 && options.token !== void 0) throw new TypeError("qstash() cannot combine client and token");
|
|
302
|
+
const url = parsedUrl.toString();
|
|
303
|
+
const configuredHeaders = callbackHeaders(options.headers);
|
|
304
|
+
const { retries } = options;
|
|
305
|
+
if (retries !== void 0 && (!Number.isSafeInteger(retries) || retries < 0)) throw new TypeError("qstash() retries must be a non-negative integer");
|
|
306
|
+
const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
|
307
|
+
if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) throw new TypeError("qstash() maxBodyBytes must be a positive integer");
|
|
308
|
+
const clock = options.clock ?? SYSTEM_CLOCK;
|
|
309
|
+
const transport = retryableLazy(() => options.transport ? Promise.resolve(options.transport) : qstashTransport(options, developmentMode)).get;
|
|
310
|
+
const storeOutageDeduplicationId = (task, outage) => {
|
|
311
|
+
if (task.kind === "append") return digestId([
|
|
312
|
+
"a2:scheduler-qstash:store-outage:append:v1",
|
|
313
|
+
url,
|
|
314
|
+
task.contract,
|
|
315
|
+
task.sessionId,
|
|
316
|
+
task.id,
|
|
317
|
+
outage.generation
|
|
318
|
+
]);
|
|
319
|
+
const { rootDueAt } = outage;
|
|
320
|
+
if (rootDueAt === void 0) throw new TypeError("qstash store-outage drain needs a root dueAt");
|
|
321
|
+
return digestId([
|
|
322
|
+
"a2:scheduler-qstash:store-outage:drain:v1",
|
|
323
|
+
url,
|
|
324
|
+
task.contract,
|
|
325
|
+
task.sessionId,
|
|
326
|
+
rootDueAt,
|
|
327
|
+
outage.generation
|
|
328
|
+
]);
|
|
329
|
+
};
|
|
330
|
+
const sendTask = async (task, outage) => {
|
|
331
|
+
const nowMs = clock.now().getTime();
|
|
332
|
+
const requestedDueAt = task.dueAt;
|
|
333
|
+
if (!Number.isFinite(requestedDueAt)) throw classifySchedulerSendFailure(/* @__PURE__ */ new TypeError("qstash scheduler dueAt must be a finite number"), "terminal");
|
|
334
|
+
const dueAt = requestedDueAt <= nowMs ? Math.floor(nowMs / 1e3) * 1e3 : Math.ceil(requestedDueAt / 1e3) * 1e3;
|
|
335
|
+
const normalizedTask = task.kind === "append" ? {
|
|
336
|
+
version: 1,
|
|
337
|
+
kind: "append",
|
|
338
|
+
id: task.id,
|
|
339
|
+
contract: task.contract,
|
|
340
|
+
sessionId: task.sessionId,
|
|
341
|
+
dueAt,
|
|
342
|
+
events: task.events
|
|
343
|
+
} : {
|
|
344
|
+
version: 1,
|
|
345
|
+
kind: "drain",
|
|
346
|
+
contract: task.contract,
|
|
347
|
+
sessionId: task.sessionId,
|
|
348
|
+
dueAt
|
|
349
|
+
};
|
|
350
|
+
const message = {
|
|
351
|
+
...normalizedTask,
|
|
352
|
+
...outage === void 0 ? {} : { _a2QStash: outage }
|
|
353
|
+
};
|
|
354
|
+
const sizeCheckedMessage = outage === void 0 ? {
|
|
355
|
+
...normalizedTask,
|
|
356
|
+
_a2QStash: normalizedTask.kind === "append" ? {
|
|
357
|
+
version: 1,
|
|
358
|
+
generation: Number.MAX_SAFE_INTEGER
|
|
359
|
+
} : {
|
|
360
|
+
version: 1,
|
|
361
|
+
generation: Number.MAX_SAFE_INTEGER,
|
|
362
|
+
rootDueAt: dueAt
|
|
363
|
+
}
|
|
364
|
+
} : message;
|
|
365
|
+
let bodyBytes;
|
|
366
|
+
try {
|
|
367
|
+
bodyBytes = new TextEncoder().encode(JSON.stringify(sizeCheckedMessage)).byteLength;
|
|
368
|
+
} catch (error) {
|
|
369
|
+
throw classifySchedulerSendFailure(error, "terminal");
|
|
370
|
+
}
|
|
371
|
+
if (bodyBytes > maxBodyBytes) throw classifySchedulerSendFailure(/* @__PURE__ */ new RangeError("qstash scheduler message exceeds maxBodyBytes"), "terminal");
|
|
372
|
+
const deduplicationId = outage !== void 0 ? await storeOutageDeduplicationId(task, outage) : task.kind === "append" ? await digestId([
|
|
373
|
+
"a2:scheduler-qstash:append:v1",
|
|
374
|
+
url,
|
|
375
|
+
task.id
|
|
376
|
+
]) : await digestId([
|
|
377
|
+
"a2:scheduler-qstash:v1",
|
|
378
|
+
url,
|
|
379
|
+
task.contract,
|
|
380
|
+
task.sessionId,
|
|
381
|
+
dueAt
|
|
382
|
+
]);
|
|
383
|
+
const trustedSource = inferredVercelPreview === true ? previewTrustedSource(Math.max(nowMs, dueAt)) : void 0;
|
|
384
|
+
const deliveryHeaders = publishHeaders(configuredHeaders, trustedSource);
|
|
385
|
+
const t = await transport();
|
|
386
|
+
try {
|
|
387
|
+
await t.publish({
|
|
388
|
+
url,
|
|
389
|
+
body: message,
|
|
390
|
+
...deliveryHeaders,
|
|
391
|
+
...dueAt <= nowMs ? {} : { notBefore: dueAt / 1e3 },
|
|
392
|
+
deduplicationId,
|
|
393
|
+
...retries === void 0 ? {} : { retries }
|
|
394
|
+
});
|
|
395
|
+
} catch (error) {
|
|
396
|
+
throw classifyQStashPublishFailure(error);
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
const sendStoreOutageSuccessor = async (task, outage) => {
|
|
400
|
+
const generation = (outage?.generation ?? -1) + 1;
|
|
401
|
+
const delayMs = Math.min(STORE_OUTAGE_MAX_DELAY_MS, STORE_OUTAGE_BASE_DELAY_MS * 4 ** Math.min(generation, 6));
|
|
402
|
+
const nowMs = clock.now().getTime();
|
|
403
|
+
const dueAt = Math.ceil((nowMs + delayMs) / 1e3) * 1e3;
|
|
404
|
+
const nextOutage = task.kind === "append" ? {
|
|
405
|
+
version: 1,
|
|
406
|
+
generation
|
|
407
|
+
} : {
|
|
408
|
+
version: 1,
|
|
409
|
+
generation,
|
|
410
|
+
rootDueAt: outage?.rootDueAt ?? task.dueAt
|
|
411
|
+
};
|
|
412
|
+
await sendTask({
|
|
413
|
+
...task,
|
|
414
|
+
dueAt
|
|
415
|
+
}, nextOutage);
|
|
416
|
+
};
|
|
417
|
+
const successorDueAt = (message) => {
|
|
418
|
+
const minimumDueAt = clock.now().getTime() + DRAIN_TIMINGS.claimTtlMs + DRAIN_TIMINGS.watchdogGraceMs;
|
|
419
|
+
const beats = Math.max(1, Math.ceil((minimumDueAt - message.dueAt) / DRAIN_TIMINGS.claimHeartbeatMs));
|
|
420
|
+
return message.dueAt + beats * DRAIN_TIMINGS.claimHeartbeatMs;
|
|
421
|
+
};
|
|
422
|
+
return {
|
|
423
|
+
async schedule(task) {
|
|
424
|
+
await sendTask(task);
|
|
425
|
+
},
|
|
426
|
+
handler(...servers) {
|
|
427
|
+
assertSchedulerTargets(servers, { allowStructural: true });
|
|
428
|
+
const byContract = /* @__PURE__ */ new Map();
|
|
429
|
+
for (const server of servers) byContract.set(server.contract.name, server);
|
|
430
|
+
return async (req) => {
|
|
431
|
+
const signature = req.headers.get("upstash-signature");
|
|
432
|
+
if (!signature) return response.unauthorized();
|
|
433
|
+
const body = await readBoundedBody(req, maxBodyBytes);
|
|
434
|
+
if (body === null) return response.tooLarge();
|
|
435
|
+
const upstashRegion = req.headers.get("upstash-region");
|
|
436
|
+
const t = await transport();
|
|
437
|
+
try {
|
|
438
|
+
if (!await t.verify({
|
|
439
|
+
signature,
|
|
440
|
+
body,
|
|
441
|
+
url,
|
|
442
|
+
...upstashRegion === null ? {} : { upstashRegion }
|
|
443
|
+
})) return response.unauthorized();
|
|
444
|
+
} catch {
|
|
445
|
+
return response.unauthorized();
|
|
446
|
+
}
|
|
447
|
+
const parsed = parseTask(body);
|
|
448
|
+
if (!parsed) return response.malformed();
|
|
449
|
+
const { task, outage } = parsed;
|
|
450
|
+
const server = byContract.get(task.contract);
|
|
451
|
+
if (!server) throw new Error(`a2 scheduler: no server for contract '${task.contract}' — pass it to schedulerHandler(...)`);
|
|
452
|
+
const internals = serverInternals.get(server);
|
|
453
|
+
if (task.kind === "append") {
|
|
454
|
+
try {
|
|
455
|
+
await deliverSchedulerAppend(server, task);
|
|
456
|
+
} catch (error) {
|
|
457
|
+
if (!storeUnavailable(error)) throw error;
|
|
458
|
+
await sendStoreOutageSuccessor(task, outage);
|
|
459
|
+
}
|
|
460
|
+
return response.ok();
|
|
461
|
+
}
|
|
462
|
+
const nextDueAt = successorDueAt(task);
|
|
463
|
+
let result;
|
|
464
|
+
try {
|
|
465
|
+
result = internals ? await internals.schedulerDrain(task.sessionId, { watchdogDueAt: nextDueAt }) : {
|
|
466
|
+
...await server.drain(task.sessionId),
|
|
467
|
+
outcome: "unknown"
|
|
468
|
+
};
|
|
469
|
+
} catch (error) {
|
|
470
|
+
if (!storeUnavailable(error)) throw error;
|
|
471
|
+
await sendStoreOutageSuccessor(task, outage);
|
|
472
|
+
return response.ok();
|
|
473
|
+
}
|
|
474
|
+
if (result.settled) return response.ok();
|
|
475
|
+
if (result.outcome === "busy") {
|
|
476
|
+
if (result.schedulerArm) await result.schedulerArm;
|
|
477
|
+
else await sendTask({
|
|
478
|
+
version: 1,
|
|
479
|
+
kind: "drain",
|
|
480
|
+
contract: task.contract,
|
|
481
|
+
sessionId: task.sessionId,
|
|
482
|
+
dueAt: nextDueAt
|
|
483
|
+
});
|
|
484
|
+
return response.ok();
|
|
485
|
+
}
|
|
486
|
+
await sendTask({
|
|
487
|
+
version: 1,
|
|
488
|
+
kind: "drain",
|
|
489
|
+
contract: task.contract,
|
|
490
|
+
sessionId: task.sessionId,
|
|
491
|
+
dueAt: nextDueAt
|
|
492
|
+
});
|
|
493
|
+
return response.ok();
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
//#endregion
|
|
499
|
+
export { qstash };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
//#region src/scheduler-task.ts
|
|
2
|
+
const recordOf = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3
|
+
const validName = (value) => typeof value === "string" && value.length > 0;
|
|
4
|
+
const validDueAt = (value) => typeof value === "number" && Number.isInteger(value) && value % 1e3 === 0;
|
|
5
|
+
const baseTask = (record) => Object.hasOwn(record, "contract") && Object.hasOwn(record, "sessionId") && validName(record["contract"]) && validName(record["sessionId"]) ? {
|
|
6
|
+
contract: record["contract"],
|
|
7
|
+
sessionId: record["sessionId"]
|
|
8
|
+
} : null;
|
|
9
|
+
/**
|
|
10
|
+
* Validate one delivered task.
|
|
11
|
+
* Adapters call this only after their transport authentication has succeeded.
|
|
12
|
+
*/
|
|
13
|
+
function normalizeSchedulerTask(value) {
|
|
14
|
+
const record = recordOf(value);
|
|
15
|
+
if (!record) return null;
|
|
16
|
+
const base = baseTask(record);
|
|
17
|
+
if (!base) return null;
|
|
18
|
+
if (record["version"] !== 1) return null;
|
|
19
|
+
if (record["kind"] === "drain") {
|
|
20
|
+
const dueAt = record["dueAt"];
|
|
21
|
+
if (!validDueAt(dueAt)) return null;
|
|
22
|
+
return {
|
|
23
|
+
version: 1,
|
|
24
|
+
kind: "drain",
|
|
25
|
+
...base,
|
|
26
|
+
dueAt
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
if (record["kind"] !== "append") return null;
|
|
30
|
+
const { dueAt, events, id } = record;
|
|
31
|
+
if (!validName(id) || !validDueAt(dueAt)) return null;
|
|
32
|
+
if (!Array.isArray(events) || events.length === 0) return null;
|
|
33
|
+
const parsedEvents = [];
|
|
34
|
+
for (const event of events) {
|
|
35
|
+
const item = recordOf(event);
|
|
36
|
+
if (!item || typeof item["id"] !== "string" || typeof item["type"] !== "string" || !Object.hasOwn(item, "payload")) return null;
|
|
37
|
+
parsedEvents.push({
|
|
38
|
+
id: item["id"],
|
|
39
|
+
type: item["type"],
|
|
40
|
+
payload: item["payload"]
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
if (new Set(parsedEvents.map((event) => event.id)).size !== parsedEvents.length) return null;
|
|
44
|
+
return {
|
|
45
|
+
version: 1,
|
|
46
|
+
kind: "append",
|
|
47
|
+
id,
|
|
48
|
+
...base,
|
|
49
|
+
dueAt,
|
|
50
|
+
events: parsedEvents
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
export { normalizeSchedulerTask as t };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as Clock } from "./
|
|
2
|
-
import {
|
|
3
|
-
//#region src/
|
|
1
|
+
import { i as Clock } from "./store-C3sNAaBT.js";
|
|
2
|
+
import { D as SchedulerTask, t as A2Scheduler } from "./server-YtPq7hjw.js";
|
|
3
|
+
//#region src/scheduler-vercel.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* The "not settled yet" signal for a stalled handler — an expected state,
|
|
6
6
|
* not a transport failure. The default transport classifies it in
|
|
@@ -10,51 +10,44 @@ import { A2Recovery } from "./server.js";
|
|
|
10
10
|
* fresh watchdog instead. Custom transports should treat this class the
|
|
11
11
|
* same way when their protocol has a polite reschedule.
|
|
12
12
|
*/
|
|
13
|
-
declare class
|
|
14
|
-
/** The message a2 puts on the queue. Application state lives in the log. */
|
|
15
|
-
type RecoveryMessage = {
|
|
16
|
-
contract: string;
|
|
17
|
-
sessionId: string;
|
|
18
|
-
/** Whole-second epoch time this watchdog was scheduled to become visible. */
|
|
19
|
-
dueAt?: number;
|
|
20
|
-
};
|
|
13
|
+
declare class DrainUnsettled extends Error {}
|
|
21
14
|
type QueueDeliveryMetadata = {
|
|
22
15
|
messageId: string;
|
|
23
16
|
deliveryCount: number;
|
|
24
17
|
};
|
|
25
|
-
/**
|
|
26
|
-
* What this module needs from a queue — `@vercel/queue`'s `send` and
|
|
27
|
-
* `handleCallback` match it structurally.
|
|
28
|
-
*/
|
|
18
|
+
/** What this module needs from a Vercel Queues-compatible transport. */
|
|
29
19
|
type QueueTransport = {
|
|
30
|
-
send(topic: string, message:
|
|
20
|
+
send(topic: string, message: SchedulerTask, options?: {
|
|
31
21
|
delaySeconds?: number;
|
|
32
22
|
idempotencyKey?: string;
|
|
23
|
+
retentionSeconds?: number;
|
|
24
|
+
}, routing?: {
|
|
25
|
+
deployment: "deployment" | "deploymentless";
|
|
33
26
|
}): Promise<unknown>;
|
|
34
27
|
/**
|
|
35
28
|
* Wrap the delivery handler into a route. The handler throws
|
|
36
|
-
* `
|
|
29
|
+
* `DrainUnsettled` when the session needs redelivery — transports
|
|
37
30
|
* with a polite reschedule (visibility change) should use it there
|
|
38
31
|
* instead of surfacing an error; anything else thrown is a genuine
|
|
39
32
|
* failure and should stay loud.
|
|
40
33
|
*/
|
|
41
|
-
handleCallback(handler: (message:
|
|
34
|
+
handleCallback(handler: (message: unknown, metadata: QueueDeliveryMetadata) => Promise<void>): (req: Request) => Promise<Response>;
|
|
42
35
|
/** Is this send error the idempotency-key collision? (= success) */
|
|
43
36
|
isDuplicate(error: unknown): boolean;
|
|
44
37
|
};
|
|
45
38
|
type VercelQueuesOptions = {
|
|
46
|
-
/** Queue topic
|
|
39
|
+
/** Queue topic matching `[A-Za-z0-9_-]+`. Default `'a2'`. */
|
|
47
40
|
topic?: string;
|
|
48
41
|
/**
|
|
49
|
-
*
|
|
50
|
-
*
|
|
42
|
+
* Deployment affinity for scheduled append tasks. Recovery drain tasks
|
|
43
|
+
* always target the publishing deployment. Default `'deployment'`.
|
|
51
44
|
*/
|
|
52
|
-
|
|
45
|
+
scheduledAppends?: "deployment" | "deploymentless";
|
|
53
46
|
/** Injectable transport (tests). Default: `@vercel/queue`. */
|
|
54
47
|
transport?: QueueTransport;
|
|
55
48
|
/** Injectable clock for due-time calculations (tests). */
|
|
56
49
|
clock?: Clock;
|
|
57
50
|
};
|
|
58
|
-
declare function vercelQueues(options?: VercelQueuesOptions):
|
|
51
|
+
declare function vercelQueues(options?: VercelQueuesOptions): A2Scheduler;
|
|
59
52
|
//#endregion
|
|
60
|
-
export { QueueDeliveryMetadata, QueueTransport,
|
|
53
|
+
export { DrainUnsettled, QueueDeliveryMetadata, QueueTransport, VercelQueuesOptions, vercelQueues };
|