@velajs/cloudflare 1.30.0 → 1.32.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 +174 -0
- package/README.md +407 -77
- package/dist/bindings.js +93 -0
- package/dist/bindings.js.map +1 -0
- package/dist/cloudflare-application-CXDy9C1R.d.ts +199 -0
- package/dist/cloudflare-application.js +15 -34
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
- package/dist/cloudflare-factory.js +227 -38
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/diagnostics.js +18 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/durable-object/boot.js +76 -0
- package/dist/durable-object/boot.js.map +1 -0
- package/dist/durable-object/host-dispatch.js +134 -0
- package/dist/durable-object/host-dispatch.js.map +1 -0
- package/dist/durable-object/host-methods.js +47 -0
- package/dist/durable-object/host-methods.js.map +1 -0
- package/dist/durable-object/tokens.js +17 -0
- package/dist/durable-object/tokens.js.map +1 -0
- package/dist/durable-object/vela-durable-object.js +121 -0
- package/dist/durable-object/vela-durable-object.js.map +1 -0
- package/dist/durable-objects.d.ts +136 -10
- package/dist/durable-objects.js +3 -1
- package/dist/email/email-dispatch.js +65 -0
- package/dist/email/email-dispatch.js.map +1 -0
- package/dist/email/on-email.js +57 -0
- package/dist/email/on-email.js.map +1 -0
- package/dist/email.d.ts +51 -0
- package/dist/email.js +3 -0
- package/dist/entrypoint/vela-entrypoint.js +160 -0
- package/dist/entrypoint/vela-entrypoint.js.map +1 -0
- package/dist/entrypoints.d.ts +93 -0
- package/dist/entrypoints.js +2 -0
- package/dist/host/host-invoker.js +276 -0
- package/dist/host/host-invoker.js.map +1 -0
- package/dist/host/host-members.js +73 -0
- package/dist/host/host-members.js.map +1 -0
- package/dist/host-members-DECj_4yz.d.ts +13 -0
- package/dist/index.d.ts +211 -445
- package/dist/index.js +8 -13
- package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
- package/dist/platform.js +22 -0
- package/dist/platform.js.map +1 -0
- package/dist/queue/cloudflare-queues.js +7 -7
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
- package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
- package/dist/root-module.js +19 -0
- package/dist/root-module.js.map +1 -0
- package/dist/rpc/entrypoint-error.js +145 -0
- package/dist/rpc/entrypoint-error.js.map +1 -0
- package/dist/schedule-diagnostics.js +8 -15
- package/dist/schedule-diagnostics.js.map +1 -1
- package/dist/services/kv-cache.store.js +33 -7
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/storage/r2-storage.js +30 -0
- package/dist/storage/r2-storage.js.map +1 -0
- package/dist/storage.d.ts +28 -0
- package/dist/storage.js +2 -0
- package/dist/tail/on-tail.js +46 -0
- package/dist/tail/on-tail.js.map +1 -0
- package/dist/tail/tail-dispatch.js +67 -0
- package/dist/tail/tail-dispatch.js.map +1 -0
- package/dist/tail.d.ts +39 -0
- package/dist/tail.js +2 -0
- package/dist/testing.d.ts +148 -0
- package/dist/testing.js +188 -0
- package/dist/testing.js.map +1 -0
- package/dist/websocket/binding-gateways.js +33 -0
- package/dist/websocket/binding-gateways.js.map +1 -0
- package/dist/websocket/cf-room-registry.js +3 -1
- package/dist/websocket/cf-room-registry.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +64 -40
- package/dist/websocket/do-bootstrap.js.map +1 -1
- package/dist/websocket/do-live.js +49 -90
- package/dist/websocket/do-live.js.map +1 -1
- package/dist/websocket/do-state.js.map +1 -1
- package/dist/websocket/live-driver.js +149 -0
- package/dist/websocket/live-driver.js.map +1 -0
- package/dist/websocket/room-id.js +11 -1
- package/dist/websocket/room-id.js.map +1 -1
- package/dist/websocket/websocket.durable-object.js +51 -18
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/websocket/worker-transport.js +80 -0
- package/dist/websocket/worker-transport.js.map +1 -0
- package/dist/worker-events.js +49 -0
- package/dist/worker-events.js.map +1 -0
- package/dist/workflow/vela-workflow.js +104 -0
- package/dist/workflow/vela-workflow.js.map +1 -0
- package/dist/workflows.d.ts +82 -0
- package/dist/workflows.js +2 -0
- package/package.json +39 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
- package/dist/storage/r2-storage.driver.js +0 -67
- package/dist/storage/r2-storage.driver.js.map +0 -1
- package/dist/storage/storage-key-claim.js +0 -74
- package/dist/storage/storage-key-claim.js.map +0 -1
- package/dist/storage/storage-manager.service.js +0 -38
- package/dist/storage/storage-manager.service.js.map +0 -1
- package/dist/storage/storage.controller.js +0 -64
- package/dist/storage/storage.controller.js.map +0 -1
- package/dist/storage/storage.module.js +0 -25
- package/dist/storage/storage.module.js.map +0 -1
- package/dist/storage/storage.service.js +0 -64
- package/dist/storage/storage.service.js.map +0 -1
- package/dist/storage/storage.tokens.js +0 -7
- package/dist/storage/storage.tokens.js.map +0 -1
- package/dist/websocket/broadcast.js +0 -32
- package/dist/websocket/broadcast.js.map +0 -1
- package/dist/websocket/cloudflare-websocket.module.js +0 -25
- package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
- package/dist/websocket/websocket-routing.js +0 -133
- package/dist/websocket/websocket-routing.js.map +0 -1
- package/dist/websocket/ws-server-holder.js +0 -38
- package/dist/websocket/ws-server-holder.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,21 +1,16 @@
|
|
|
1
1
|
import { durableObjectRoomName } from "./websocket/room-id.js";
|
|
2
2
|
import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
|
|
3
3
|
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { StorageController } from "./storage/storage.controller.js";
|
|
10
|
-
import { StorageService } from "./storage/storage.service.js";
|
|
11
|
-
import { StorageModule } from "./storage/storage.module.js";
|
|
12
|
-
import { KVCacheInvalidationStore, KVCacheStore } from "./services/kv-cache.store.js";
|
|
4
|
+
import { d1, durableObject, kv, queue, r2, rateLimit, workflow } from "./bindings.js";
|
|
5
|
+
import { durableObjectLive } from "./websocket/live-driver.js";
|
|
6
|
+
import { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp } from "./cloudflare-factory.js";
|
|
7
|
+
import { EntrypointError, isEntrypointError } from "./rpc/entrypoint-error.js";
|
|
8
|
+
import { KVCacheInvalidationStore, KVCacheStore, kvCache, kvCacheInvalidation } from "./services/kv-cache.store.js";
|
|
13
9
|
import { FlagshipFlagDriver, flagshipFlagDriver } from "./services/flagship-flag.driver.js";
|
|
14
10
|
import { KvFlagDriver, kvFlagDriver } from "./services/kv-flag.driver.js";
|
|
15
11
|
import { QueueConsumer } from "./decorators/queue-consumer.js";
|
|
16
12
|
import { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark } from "./websocket/do-pitr.js";
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import { cloudflareRateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
|
|
13
|
+
import { DoCursorLog, liveInvalidateToRoom } from "./websocket/do-live.js";
|
|
14
|
+
import { rateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
|
|
20
15
|
import { durableObjectNonceStore } from "./nonce/durable-object-nonce.store.js";
|
|
21
|
-
export { CLOUDFLARE_SCHEDULED_EVENT,
|
|
16
|
+
export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, CloudflareApplication, DoCursorLog, DoPitrUnavailableError, EntrypointError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, d1, defineCloudflareApp, durableObject, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagshipFlagDriver, isCloudflareApp, isDoPitrUnavailable, isEntrypointError, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark, workflow };
|
|
@@ -1,14 +1,4 @@
|
|
|
1
1
|
import { DurableObject } from "cloudflare:workers";
|
|
2
|
-
import { DynamicModule, Type } from "@velajs/vela";
|
|
3
|
-
//#region src/root-module.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* The root a Worker or Durable Object is built from: a module class or a
|
|
6
|
-
* `DynamicModule`, declared once at module scope. Configuration that needs
|
|
7
|
-
* bindings belongs in providers and `forRootAsync({ inject: [ENV] })`
|
|
8
|
-
* factories, which run for each application with that application's ENV.
|
|
9
|
-
*/
|
|
10
|
-
type CloudflareRoot = Type | DynamicModule;
|
|
11
|
-
//#endregion
|
|
12
2
|
//#region src/websocket/do-pitr.d.ts
|
|
13
3
|
/**
|
|
14
4
|
* Durable Object point-in-time recovery (PITR) — thin, testable wrappers over a
|
|
@@ -140,4 +130,4 @@ declare class VelaNonceDurableObject extends DurableObject<Record<string, unknow
|
|
|
140
130
|
claim(nonce: string, expEpochSeconds: number): Promise<boolean>;
|
|
141
131
|
}
|
|
142
132
|
//#endregion
|
|
143
|
-
export { DoPitrId as a, DoPitrUnavailableError as c, isDoPitrUnavailable as d, readDoPitrBookmark as f, DoPitrBookmarkRead as i, VelaDoPitrRpc as l, DoPitrArmOptions as n, DoPitrNamespace as o,
|
|
133
|
+
export { DoPitrId as a, DoPitrUnavailableError as c, isDoPitrUnavailable as d, readDoPitrBookmark as f, DoPitrBookmarkRead as i, VelaDoPitrRpc as l, DoPitrArmOptions as n, DoPitrNamespace as o, DoPitrArmResult as r, DoPitrStorage as s, VelaNonceDurableObject as t, armDoPitr as u };
|
package/dist/platform.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { registerCloudflareEnvironment } from "./environment.js";
|
|
2
|
+
import { defineProvider } from "@velajs/vela";
|
|
3
|
+
import { LIVE_PLATFORM } from "@velajs/vela/live";
|
|
4
|
+
import { WS_TRANSPORT } from "@velajs/vela/websocket";
|
|
5
|
+
//#region src/platform.ts
|
|
6
|
+
/**
|
|
7
|
+
* Seed the application's ENV and its platform wiring, as global tokens,
|
|
8
|
+
* before any module loads: `WebSocketModule` and `LiveModule` read
|
|
9
|
+
* `WS_TRANSPORT` and `LIVE_PLATFORM` from here. Module providers are never
|
|
10
|
+
* replaced; an application without those modules never reads either token.
|
|
11
|
+
*/
|
|
12
|
+
function registerCloudflarePlatform(container, env, platform) {
|
|
13
|
+
registerCloudflareEnvironment(container, env);
|
|
14
|
+
container.register(defineProvider(WS_TRANSPORT, { useValue: platform.websocket }));
|
|
15
|
+
container.markGlobalToken(WS_TRANSPORT);
|
|
16
|
+
container.register(defineProvider(LIVE_PLATFORM, { useValue: platform.live }));
|
|
17
|
+
container.markGlobalToken(LIVE_PLATFORM);
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
export { registerCloudflarePlatform };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=platform.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform.js","names":[],"sources":["../src/platform.ts"],"sourcesContent":["import { defineProvider } from '@velajs/vela';\nimport type { VelaEnv } from '@velajs/vela';\nimport { LIVE_PLATFORM, type LivePlatform } from '@velajs/vela/live';\nimport type { Container } from '@velajs/vela/module-kit';\nimport { WS_TRANSPORT, type WebSocketTransport } from '@velajs/vela/websocket';\nimport { registerCloudflareEnvironment } from './environment';\n\n/** What one isolate, the Worker or a WebSocket Durable Object, gives the application. */\nexport interface CloudflarePlatform {\n websocket: WebSocketTransport;\n live: LivePlatform;\n}\n\n/**\n * Seed the application's ENV and its platform wiring, as global tokens,\n * before any module loads: `WebSocketModule` and `LiveModule` read\n * `WS_TRANSPORT` and `LIVE_PLATFORM` from here. Module providers are never\n * replaced; an application without those modules never reads either token.\n */\nexport function registerCloudflarePlatform(\n container: Container,\n env: VelaEnv,\n platform: CloudflarePlatform,\n): void {\n registerCloudflareEnvironment(container, env);\n container.register(defineProvider(WS_TRANSPORT, { useValue: platform.websocket }));\n container.markGlobalToken(WS_TRANSPORT);\n container.register(defineProvider(LIVE_PLATFORM, { useValue: platform.live }));\n container.markGlobalToken(LIVE_PLATFORM);\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAgB,2BACd,WACA,KACA,UACM;CACN,8BAA8B,WAAW,GAAG;CAC5C,UAAU,SAAS,eAAe,cAAc,EAAE,UAAU,SAAS,UAAU,CAAC,CAAC;CACjF,UAAU,gBAAgB,YAAY;CACtC,UAAU,SAAS,eAAe,eAAe,EAAE,UAAU,SAAS,KAAK,CAAC,CAAC;CAC7E,UAAU,gBAAgB,aAAa;AACzC"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { QUEUE_PRODUCER } from "../bindings.js";
|
|
2
|
+
import { resolveBinding } from "@velajs/vela/module-kit";
|
|
1
3
|
import { QueueBatchError, observeMessage, parseQueueJob } from "@velajs/vela/queue";
|
|
2
4
|
//#region src/queue/cloudflare-queues.ts
|
|
3
5
|
/** The Cloudflare Queues send limits `addBulk` is chunked to (bytes are decimal kilobytes). */
|
|
@@ -66,9 +68,6 @@ function delaySeconds(options) {
|
|
|
66
68
|
if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > MAX_DELAY_MS) throw new RangeError("Queue delayMs must be between 0 and 86400000.");
|
|
67
69
|
return Math.ceil(delayMs / 1e3);
|
|
68
70
|
}
|
|
69
|
-
function isProducer(value) {
|
|
70
|
-
return typeof value === "object" && value !== null && typeof Reflect.get(value, "send") === "function";
|
|
71
|
-
}
|
|
72
71
|
function nativeBatch(payload) {
|
|
73
72
|
if (typeof payload !== "object" || payload === null || !("queue" in payload) || typeof payload.queue !== "string" || !("messages" in payload) || !Array.isArray(payload.messages)) throw new TypeError("Invalid native queue batch.");
|
|
74
73
|
const messages = [];
|
|
@@ -105,10 +104,11 @@ function createDriver({ env, queues }) {
|
|
|
105
104
|
const registration = queues.get(name);
|
|
106
105
|
if (!registration) throw new Error(`Queue '${name}' is not registered. Add QueueModule.registerQueue({ name: '${name}', binding }) to the module that produces it.`);
|
|
107
106
|
if (registration.binding === void 0) throw new Error(`Queue '${name}' has no producer binding. Register it with QueueModule.registerQueue({ name: '${name}', binding: 'YOUR_QUEUE' }), where the binding is a queues.producers[].binding of this Worker.`);
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
107
|
+
try {
|
|
108
|
+
return resolveBinding(env, { binding: registration.binding }, QUEUE_PRODUCER);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
throw new Error(`Queue '${name}' cannot send: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
111
|
+
}
|
|
112
112
|
};
|
|
113
113
|
return {
|
|
114
114
|
kind: "cloudflare",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-queues.js","names":[],"sources":["../../src/queue/cloudflare-queues.ts"],"sourcesContent":["import { observeMessage, parseQueueJob, QueueBatchError } from '@velajs/vela/queue';\nimport type {\n AddJobOptions,\n QueueDispatchFn,\n QueueDispatchResult,\n QueueDriver,\n QueueDriverContext,\n QueueDriverFactory,\n QueueEnqueueRequest,\n QueueJob,\n QueueMessageLike,\n} from '@velajs/vela/queue';\n\n/** The native producer surface the driver uses: a Wrangler `queues.producers` binding. */\nexport interface CloudflareQueueProducer {\n // Both older void-returning bindings and current metric-returning bindings work.\n send(message: QueueJob, options?: QueueSendOptions): Promise<unknown>;\n sendBatch?(messages: Iterable<MessageSendRequest<QueueJob>>): Promise<unknown>;\n}\n\n/** The Cloudflare Queues send limits `addBulk` is chunked to (bytes are decimal kilobytes). */\nexport const QUEUE_SEND_LIMITS = Object.freeze({\n /** Messages per `sendBatch` call. */\n messages: 100,\n /** Estimated bytes per `sendBatch` call. */\n batchBytes: 256_000,\n /** Estimated bytes per message. */\n messageBytes: 128_000,\n});\n\n/** Allowance for the platform's per-message framing on top of the body estimate. */\nconst MESSAGE_MARGIN_BYTES = 256;\nconst MAX_DELAY_MS = 86_400_000;\n\n/**\n * A string's size as JSON (UTF-8, quoted, escaped) or as V8 serializes it\n * (one byte per character, two for a string holding any character above\n * U+00FF), whichever is larger.\n */\nfunction stringBytes(text: string): number {\n let json = 2;\n let wide = false;\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index);\n if (code > 0xff) wide = true;\n if (code < 0x20) json += 6;\n else if (code === 0x22 || code === 0x5c) json += 2;\n else if (code < 0x80) json += 1;\n else if (code < 0x800) json += 2;\n else if (code >= 0xd800 && code <= 0xdfff) json += 2;\n else json += 3;\n }\n return Math.max(json, (wide ? text.length * 2 : text.length) + 5);\n}\n\nfunction measure(value: unknown, seen: Set<object>): number {\n switch (typeof value) {\n case 'string':\n return stringBytes(value);\n case 'number':\n return Math.max(String(value).length, 9);\n case 'bigint':\n return String(value).length + 9;\n case 'boolean':\n return 5;\n case 'object':\n break;\n default:\n return 9;\n }\n if (value === null) return 4;\n // V8 serializes a repeated reference as a back-reference.\n if (seen.has(value)) return 9;\n seen.add(value);\n let bytes = 2;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n bytes += value.byteLength + 9;\n } else if (value instanceof Date) {\n bytes += 26;\n } else if (value instanceof Map) {\n for (const [key, item] of value) bytes += measure(key, seen) + measure(item, seen) + 2;\n } else if (value instanceof Set) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else if (Array.isArray(value)) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else {\n for (const key of Object.keys(value)) {\n bytes += stringBytes(key) + measure(Reflect.get(value, key), seen) + 2;\n }\n }\n return bytes;\n}\n\n/**\n * A conservative size estimate of one native queue message: the larger of the\n * body's JSON and V8 sizes, plus a per-message margin.\n */\nexport function estimateQueueMessageBytes(body: unknown): number {\n return measure(body, new Set()) + MESSAGE_MARGIN_BYTES;\n}\n\nfunction delaySeconds(options: AddJobOptions | undefined): number | undefined {\n const delayMs = options?.delayMs;\n if (delayMs === undefined) return undefined;\n if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > MAX_DELAY_MS) {\n throw new RangeError('Queue delayMs must be between 0 and 86400000.');\n }\n return Math.ceil(delayMs / 1000);\n}\n\nfunction isProducer(value: unknown): value is CloudflareQueueProducer {\n return (\n typeof value === 'object' && value !== null && typeof Reflect.get(value, 'send') === 'function'\n );\n}\n\nfunction nativeBatch(payload: unknown): { queue: string; messages: QueueMessageLike[] } {\n if (\n typeof payload !== 'object' ||\n payload === null ||\n !('queue' in payload) ||\n typeof payload.queue !== 'string' ||\n !('messages' in payload) ||\n !Array.isArray(payload.messages)\n )\n throw new TypeError('Invalid native queue batch.');\n const messages: QueueMessageLike[] = [];\n for (const message of payload.messages as unknown[]) {\n if (\n typeof message !== 'object' ||\n message === null ||\n !('body' in message) ||\n !('ack' in message) ||\n typeof message.ack !== 'function' ||\n !('retry' in message) ||\n typeof message.retry !== 'function' ||\n !('id' in message) ||\n typeof message.id !== 'string' ||\n !('timestamp' in message) ||\n !(message.timestamp instanceof Date) ||\n !('attempts' in message) ||\n typeof message.attempts !== 'number'\n )\n throw new TypeError('Invalid native queue message.');\n messages.push(message as QueueMessageLike);\n }\n return { queue: payload.queue, messages };\n}\n\ninterface PreparedMessage {\n readonly id: string;\n readonly queue: string;\n readonly bytes: number;\n readonly request: MessageSendRequest<QueueJob>;\n}\n\n/** Split in order: a new call starts at 100 messages, at the byte budget, or at another queue. */\nfunction chunk(messages: readonly PreparedMessage[]): PreparedMessage[][] {\n const chunks: PreparedMessage[][] = [];\n let current: PreparedMessage[] = [];\n let bytes = 0;\n for (const message of messages) {\n if (\n current.length > 0 &&\n (current.length === QUEUE_SEND_LIMITS.messages ||\n bytes + message.bytes > QUEUE_SEND_LIMITS.batchBytes ||\n current[0]!.queue !== message.queue)\n ) {\n chunks.push(current);\n current = [];\n bytes = 0;\n }\n current.push(message);\n bytes += message.bytes;\n }\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\nfunction createDriver({ env, queues }: QueueDriverContext): QueueDriver {\n // Physical queue -> the logical queues registrations pin to it.\n const pins = new Map<string, string[]>();\n for (const queue of queues.all()) {\n for (const physical of queue.consumers) {\n pins.set(physical, [...(pins.get(physical) ?? []), queue.name]);\n }\n }\n\n // Resolved on every send from this application's ENV, never cached.\n const producerFor = (name: string): CloudflareQueueProducer => {\n const registration = queues.get(name);\n if (!registration) {\n throw new Error(\n `Queue '${name}' is not registered. Add QueueModule.registerQueue({ name: '${name}', ` +\n `binding }) to the module that produces it.`,\n );\n }\n if (registration.binding === undefined) {\n throw new Error(\n `Queue '${name}' has no producer binding. Register it with ` +\n `QueueModule.registerQueue({ name: '${name}', binding: 'YOUR_QUEUE' }), where the ` +\n `binding is a queues.producers[].binding of this Worker.`,\n );\n }\n if (env === undefined) {\n throw new Error(\n `cloudflareQueues() needs the Workers ENV to send '${name}' jobs. Build the application ` +\n `with createCloudflareWorker, createCloudflareApp or cloudflareAdapter.`,\n );\n }\n const producer: unknown = Reflect.get(env, registration.binding);\n if (!isProducer(producer)) {\n throw new TypeError(\n `ENV.${registration.binding} is not a Cloudflare queue producer binding (queue ` +\n `'${name}'). Declare it under queues.producers in this Worker's Wrangler configuration.`,\n );\n }\n return producer;\n };\n\n return {\n kind: 'cloudflare',\n entrypoints: [{ kind: 'cf:queue:module', meta: { consumers: [...pins.keys()] } }],\n\n async consume(payload: unknown, dispatch: QueueDispatchFn): Promise<void> {\n const batch = nativeBatch(payload);\n const pinned = pins.get(batch.queue);\n await consumeQueueBatch(\n batch,\n (job) => {\n // A pinned queue is consumed only from the physical queues it names.\n const expected = queues.get(job.queue)?.consumers ?? [];\n if (expected.length > 0 && !expected.includes(batch.queue)) {\n throw new Error(\n `Queue '${job.queue}' is consumed from ` +\n `${expected.map((queue) => `'${queue}'`).join(', ')}, not '${batch.queue}'.`,\n );\n }\n return dispatch(job);\n },\n pinned ? { queues: pinned } : {},\n );\n },\n\n async enqueue(job: QueueJob, options?: AddJobOptions): Promise<void> {\n const delay = delaySeconds(options);\n await producerFor(job.queue).send(\n parseQueueJob(job),\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n },\n\n async enqueueBatch(requests: readonly QueueEnqueueRequest[]): Promise<void> {\n // Validate every job and resolve every binding before the first send.\n const messages = requests.map(({ job, options }): PreparedMessage => {\n const body = parseQueueJob(job);\n const bytes = estimateQueueMessageBytes(body);\n if (bytes > QUEUE_SEND_LIMITS.messageBytes) {\n throw new RangeError(\n `Queue job '${job.id}' is an estimated ${bytes} bytes, over the ` +\n `${QUEUE_SEND_LIMITS.messageBytes}-byte Cloudflare message limit. Store large ` +\n `payloads elsewhere (for example in R2) and enqueue a reference.`,\n );\n }\n const delay = delaySeconds(options);\n return {\n id: job.id,\n queue: job.queue,\n bytes,\n request: delay === undefined ? { body } : { body, delaySeconds: delay },\n };\n });\n const producers = new Map<string, CloudflareQueueProducer>();\n for (const { queue } of messages) {\n if (!producers.has(queue)) producers.set(queue, producerFor(queue));\n }\n const accepted: string[] = [];\n for (const part of chunk(messages)) {\n const producer = producers.get(part[0]!.queue)!;\n try {\n if (typeof producer.sendBatch === 'function') {\n // eslint-disable-next-line no-await-in-loop\n await producer.sendBatch(part.map(({ request }) => request));\n accepted.push(...part.map(({ id }) => id));\n } else {\n for (const { id, request } of part) {\n const delay = request.delaySeconds;\n // eslint-disable-next-line no-await-in-loop\n await producer.send(\n request.body,\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n accepted.push(id);\n }\n }\n } catch (error) {\n throw new QueueBatchError(\n accepted,\n messages.slice(accepted.length).map(({ id }) => id),\n error,\n );\n }\n }\n },\n };\n}\n\n/**\n * The Cloudflare Queues driver for `QueueModule`:\n *\n * ```ts\n * QueueModule.forRoot({ driver: cloudflareQueues() })\n * QueueModule.registerQueue({ name: 'email', binding: 'EMAIL_QUEUE' })\n * ```\n *\n * Each application gets its own driver. Producing reads the registered binding\n * from that application's `ENV` when a job is added and awaits the native\n * send; `addBulk` uses `sendBatch`, chunked to {@link QUEUE_SEND_LIMITS}.\n * Consuming is native too: the Worker's `queue()` handler routes every batch\n * that no `@QueueConsumer` claims through `QueueModule`, one message at a time,\n * by each job's logical `queue`, with the module's dispatch policy (signed\n * dispatch included). A registration's `consumer` pins its queue to that\n * physical queue: the queue's jobs are accepted only from it, and it only\n * carries the queues pinned to it. A message that is not a job envelope,\n * belongs to an unregistered queue, or fails stays unacknowledged, so\n * Cloudflare retries it and then dead-letters it.\n */\nexport function cloudflareQueues(): QueueDriverFactory {\n return (context) => createDriver(context);\n}\n\nexport interface ConsumeQueueBatchOptions {\n /**\n * Accept only jobs of these logical queues; any other message fails and is\n * retried. By default every job envelope is accepted.\n */\n readonly queues?: readonly string[];\n}\n\n/**\n * Settle native messages one job at a time. Attempts come from the host.\n * Process every message; ack successful/unsettled deliveries, then rethrow any\n * failures so the host retries the unsettled remainder. Explicit settlement wins.\n * The callback must await all work that should determine delivery success.\n */\nexport async function consumeQueueBatch(\n batch: { readonly queue: string; readonly messages: readonly QueueMessageLike[] },\n dispatch: (job: QueueJob, message: QueueMessageLike) => Promise<QueueDispatchResult | void>,\n options: ConsumeQueueBatchOptions = {},\n): Promise<void> {\n const errors: unknown[] = [];\n for (const message of batch.messages) {\n try {\n const job = parseQueueJob(message.body, message.attempts);\n if (options.queues && !options.queues.includes(job.queue)) {\n throw new Error(\n `Queue '${job.queue}' is not consumed from '${batch.queue}', which accepts ` +\n `${options.queues.map((queue) => `'${queue}'`).join(', ')}.`,\n );\n }\n const observed = observeMessage(message);\n // eslint-disable-next-line no-await-in-loop\n const result = await dispatch(job, observed.message);\n if (result?.handled === 0) throw new Error(`Queue job '${job.name}' has no handler.`);\n if (observed.disposition().outcome === 'unsettled') observed.message.ack();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Queue batch deliveries failed.');\n}\n"],"mappings":";;;AAqBA,MAAa,oBAAoB,OAAO,OAAO;;CAE7C,UAAU;;CAEV,YAAY;;CAEZ,cAAc;AAChB,CAAC;;AAGD,MAAM,uBAAuB;AAC7B,MAAM,eAAe;;;;;;AAOrB,SAAS,YAAY,MAAsB;CACzC,IAAI,OAAO;CACX,IAAI,OAAO;CACX,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;EAChD,MAAM,OAAO,KAAK,WAAW,KAAK;EAClC,IAAI,OAAO,KAAM,OAAO;EACxB,IAAI,OAAO,IAAM,QAAQ;OACpB,IAAI,SAAS,MAAQ,SAAS,IAAM,QAAQ;OAC5C,IAAI,OAAO,KAAM,QAAQ;OACzB,IAAI,OAAO,MAAO,QAAQ;OAC1B,IAAI,QAAQ,SAAU,QAAQ,OAAQ,QAAQ;OAC9C,QAAQ;CACf;CACA,OAAO,KAAK,IAAI,OAAO,OAAO,KAAK,SAAS,IAAI,KAAK,UAAU,CAAC;AAClE;AAEA,SAAS,QAAQ,OAAgB,MAA2B;CAC1D,QAAQ,OAAO,OAAf;EACE,KAAK,UACH,OAAO,YAAY,KAAK;EAC1B,KAAK,UACH,OAAO,KAAK,IAAI,OAAO,KAAK,CAAC,CAAC,QAAQ,CAAC;EACzC,KAAK,UACH,OAAO,OAAO,KAAK,CAAC,CAAC,SAAS;EAChC,KAAK,WACH,OAAO;EACT,KAAK,UACH;EACF,SACE,OAAO;CACX;CACA,IAAI,UAAU,MAAM,OAAO;CAE3B,IAAI,KAAK,IAAI,KAAK,GAAG,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,CAAC,GACtB;CACf,MAAM,SAAoB,CAAC;CAC3B,KAAK,MAAM,WAAW,MAAM,UAC1B,IAAI;EACF,MAAM,MAAM,cAAc,QAAQ,MAAM,QAAQ,QAAQ;EACxD,IAAI,QAAQ,UAAU,CAAC,QAAQ,OAAO,SAAS,IAAI,KAAK,GACtD,MAAM,IAAI,MACR,UAAU,IAAI,MAAM,0BAA0B,MAAM,MAAM,mBACrD,QAAQ,OAAO,KAAK,UAAU,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,EAC9D;EAEF,MAAM,WAAW,eAAe,OAAO;EAGvC,KAAI,MADiB,SAAS,KAAK,SAAS,OAAO,EAAA,EACvC,YAAY,GAAG,MAAM,IAAI,MAAM,cAAc,IAAI,KAAK,kBAAkB;EACpF,IAAI,SAAS,YAAY,CAAC,CAAC,YAAY,aAAa,SAAS,QAAQ,IAAI;CAC3E,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAEF,IAAI,OAAO,WAAW,GAAG,MAAM,OAAO;CACtC,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,gCAAgC;AAC1F"}
|
|
1
|
+
{"version":3,"file":"cloudflare-queues.js","names":[],"sources":["../../src/queue/cloudflare-queues.ts"],"sourcesContent":["import { observeMessage, parseQueueJob, QueueBatchError } from '@velajs/vela/queue';\nimport { resolveBinding } from '@velajs/vela/module-kit';\nimport { QUEUE_PRODUCER } from '../bindings';\nimport type {\n AddJobOptions,\n QueueDispatchFn,\n QueueDispatchResult,\n QueueDriver,\n QueueDriverContext,\n QueueDriverFactory,\n QueueEnqueueRequest,\n QueueJob,\n QueueMessageLike,\n} from '@velajs/vela/queue';\n\n/** The native producer surface the driver uses: a Wrangler `queues.producers` binding. */\nexport interface CloudflareQueueProducer {\n // Both older void-returning bindings and current metric-returning bindings work.\n send(message: QueueJob, options?: QueueSendOptions): Promise<unknown>;\n sendBatch?(messages: Iterable<MessageSendRequest<QueueJob>>): Promise<unknown>;\n}\n\n/** The Cloudflare Queues send limits `addBulk` is chunked to (bytes are decimal kilobytes). */\nexport const QUEUE_SEND_LIMITS = Object.freeze({\n /** Messages per `sendBatch` call. */\n messages: 100,\n /** Estimated bytes per `sendBatch` call. */\n batchBytes: 256_000,\n /** Estimated bytes per message. */\n messageBytes: 128_000,\n});\n\n/** Allowance for the platform's per-message framing on top of the body estimate. */\nconst MESSAGE_MARGIN_BYTES = 256;\nconst MAX_DELAY_MS = 86_400_000;\n\n/**\n * A string's size as JSON (UTF-8, quoted, escaped) or as V8 serializes it\n * (one byte per character, two for a string holding any character above\n * U+00FF), whichever is larger.\n */\nfunction stringBytes(text: string): number {\n let json = 2;\n let wide = false;\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index);\n if (code > 0xff) wide = true;\n if (code < 0x20) json += 6;\n else if (code === 0x22 || code === 0x5c) json += 2;\n else if (code < 0x80) json += 1;\n else if (code < 0x800) json += 2;\n else if (code >= 0xd800 && code <= 0xdfff) json += 2;\n else json += 3;\n }\n return Math.max(json, (wide ? text.length * 2 : text.length) + 5);\n}\n\nfunction measure(value: unknown, seen: Set<object>): number {\n switch (typeof value) {\n case 'string':\n return stringBytes(value);\n case 'number':\n return Math.max(String(value).length, 9);\n case 'bigint':\n return String(value).length + 9;\n case 'boolean':\n return 5;\n case 'object':\n break;\n default:\n return 9;\n }\n if (value === null) return 4;\n // V8 serializes a repeated reference as a back-reference.\n if (seen.has(value)) return 9;\n seen.add(value);\n let bytes = 2;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n bytes += value.byteLength + 9;\n } else if (value instanceof Date) {\n bytes += 26;\n } else if (value instanceof Map) {\n for (const [key, item] of value) bytes += measure(key, seen) + measure(item, seen) + 2;\n } else if (value instanceof Set) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else if (Array.isArray(value)) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else {\n for (const key of Object.keys(value)) {\n bytes += stringBytes(key) + measure(Reflect.get(value, key), seen) + 2;\n }\n }\n return bytes;\n}\n\n/**\n * A conservative size estimate of one native queue message: the larger of the\n * body's JSON and V8 sizes, plus a per-message margin.\n */\nexport function estimateQueueMessageBytes(body: unknown): number {\n return measure(body, new Set()) + MESSAGE_MARGIN_BYTES;\n}\n\nfunction delaySeconds(options: AddJobOptions | undefined): number | undefined {\n const delayMs = options?.delayMs;\n if (delayMs === undefined) return undefined;\n if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > MAX_DELAY_MS) {\n throw new RangeError('Queue delayMs must be between 0 and 86400000.');\n }\n return Math.ceil(delayMs / 1000);\n}\n\nfunction nativeBatch(payload: unknown): { queue: string; messages: QueueMessageLike[] } {\n if (\n typeof payload !== 'object' ||\n payload === null ||\n !('queue' in payload) ||\n typeof payload.queue !== 'string' ||\n !('messages' in payload) ||\n !Array.isArray(payload.messages)\n )\n throw new TypeError('Invalid native queue batch.');\n const messages: QueueMessageLike[] = [];\n for (const message of payload.messages as unknown[]) {\n if (\n typeof message !== 'object' ||\n message === null ||\n !('body' in message) ||\n !('ack' in message) ||\n typeof message.ack !== 'function' ||\n !('retry' in message) ||\n typeof message.retry !== 'function' ||\n !('id' in message) ||\n typeof message.id !== 'string' ||\n !('timestamp' in message) ||\n !(message.timestamp instanceof Date) ||\n !('attempts' in message) ||\n typeof message.attempts !== 'number'\n )\n throw new TypeError('Invalid native queue message.');\n messages.push(message as QueueMessageLike);\n }\n return { queue: payload.queue, messages };\n}\n\ninterface PreparedMessage {\n readonly id: string;\n readonly queue: string;\n readonly bytes: number;\n readonly request: MessageSendRequest<QueueJob>;\n}\n\n/** Split in order: a new call starts at 100 messages, at the byte budget, or at another queue. */\nfunction chunk(messages: readonly PreparedMessage[]): PreparedMessage[][] {\n const chunks: PreparedMessage[][] = [];\n let current: PreparedMessage[] = [];\n let bytes = 0;\n for (const message of messages) {\n if (\n current.length > 0 &&\n (current.length === QUEUE_SEND_LIMITS.messages ||\n bytes + message.bytes > QUEUE_SEND_LIMITS.batchBytes ||\n current[0]!.queue !== message.queue)\n ) {\n chunks.push(current);\n current = [];\n bytes = 0;\n }\n current.push(message);\n bytes += message.bytes;\n }\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\nfunction createDriver({ env, queues }: QueueDriverContext): QueueDriver {\n // Physical queue -> the logical queues registrations pin to it.\n const pins = new Map<string, string[]>();\n for (const queue of queues.all()) {\n for (const physical of queue.consumers) {\n pins.set(physical, [...(pins.get(physical) ?? []), queue.name]);\n }\n }\n\n // Resolved on every send from this application's ENV, never cached.\n const producerFor = (name: string): CloudflareQueueProducer => {\n const registration = queues.get(name);\n if (!registration) {\n throw new Error(\n `Queue '${name}' is not registered. Add QueueModule.registerQueue({ name: '${name}', ` +\n `binding }) to the module that produces it.`,\n );\n }\n if (registration.binding === undefined) {\n throw new Error(\n `Queue '${name}' has no producer binding. Register it with ` +\n `QueueModule.registerQueue({ name: '${name}', binding: 'YOUR_QUEUE' }), where the ` +\n `binding is a queues.producers[].binding of this Worker.`,\n );\n }\n try {\n return resolveBinding(env, { binding: registration.binding }, QUEUE_PRODUCER);\n } catch (error) {\n throw new Error(\n `Queue '${name}' cannot send: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n };\n\n return {\n kind: 'cloudflare',\n entrypoints: [{ kind: 'cf:queue:module', meta: { consumers: [...pins.keys()] } }],\n\n async consume(payload: unknown, dispatch: QueueDispatchFn): Promise<void> {\n const batch = nativeBatch(payload);\n const pinned = pins.get(batch.queue);\n await consumeQueueBatch(\n batch,\n (job) => {\n // A pinned queue is consumed only from the physical queues it names.\n const expected = queues.get(job.queue)?.consumers ?? [];\n if (expected.length > 0 && !expected.includes(batch.queue)) {\n throw new Error(\n `Queue '${job.queue}' is consumed from ` +\n `${expected.map((queue) => `'${queue}'`).join(', ')}, not '${batch.queue}'.`,\n );\n }\n return dispatch(job);\n },\n pinned ? { queues: pinned } : {},\n );\n },\n\n async enqueue(job: QueueJob, options?: AddJobOptions): Promise<void> {\n const delay = delaySeconds(options);\n await producerFor(job.queue).send(\n parseQueueJob(job),\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n },\n\n async enqueueBatch(requests: readonly QueueEnqueueRequest[]): Promise<void> {\n // Validate every job and resolve every binding before the first send.\n const messages = requests.map(({ job, options }): PreparedMessage => {\n const body = parseQueueJob(job);\n const bytes = estimateQueueMessageBytes(body);\n if (bytes > QUEUE_SEND_LIMITS.messageBytes) {\n throw new RangeError(\n `Queue job '${job.id}' is an estimated ${bytes} bytes, over the ` +\n `${QUEUE_SEND_LIMITS.messageBytes}-byte Cloudflare message limit. Store large ` +\n `payloads elsewhere (for example in R2) and enqueue a reference.`,\n );\n }\n const delay = delaySeconds(options);\n return {\n id: job.id,\n queue: job.queue,\n bytes,\n request: delay === undefined ? { body } : { body, delaySeconds: delay },\n };\n });\n const producers = new Map<string, CloudflareQueueProducer>();\n for (const { queue } of messages) {\n if (!producers.has(queue)) producers.set(queue, producerFor(queue));\n }\n const accepted: string[] = [];\n for (const part of chunk(messages)) {\n const producer = producers.get(part[0]!.queue)!;\n try {\n if (typeof producer.sendBatch === 'function') {\n // eslint-disable-next-line no-await-in-loop\n await producer.sendBatch(part.map(({ request }) => request));\n accepted.push(...part.map(({ id }) => id));\n } else {\n for (const { id, request } of part) {\n const delay = request.delaySeconds;\n // eslint-disable-next-line no-await-in-loop\n await producer.send(\n request.body,\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n accepted.push(id);\n }\n }\n } catch (error) {\n throw new QueueBatchError(\n accepted,\n messages.slice(accepted.length).map(({ id }) => id),\n error,\n );\n }\n }\n },\n };\n}\n\n/**\n * The Cloudflare Queues driver for `QueueModule`:\n *\n * ```ts\n * QueueModule.forRoot({ driver: cloudflareQueues() })\n * QueueModule.registerQueue({ name: 'email', binding: 'EMAIL_QUEUE' })\n * ```\n *\n * Each application gets its own driver. Producing reads the registered binding\n * from that application's `ENV` when a job is added and awaits the native\n * send; `addBulk` uses `sendBatch`, chunked to {@link QUEUE_SEND_LIMITS}.\n * Consuming is native too: the Worker's `queue()` handler routes every batch\n * that no `@QueueConsumer` claims through `QueueModule`, one message at a time,\n * by each job's logical `queue`, with the module's dispatch policy (signed\n * dispatch included). A registration's `consumer` pins its queue to that\n * physical queue: the queue's jobs are accepted only from it, and it only\n * carries the queues pinned to it. A message that is not a job envelope,\n * belongs to an unregistered queue, or fails stays unacknowledged, so\n * Cloudflare retries it and then dead-letters it.\n */\nexport function cloudflareQueues(): QueueDriverFactory {\n return (context) => createDriver(context);\n}\n\nexport interface ConsumeQueueBatchOptions {\n /**\n * Accept only jobs of these logical queues; any other message fails and is\n * retried. By default every job envelope is accepted.\n */\n readonly queues?: readonly string[];\n}\n\n/**\n * Settle native messages one job at a time. Attempts come from the host.\n * Process every message; ack successful/unsettled deliveries, then rethrow any\n * failures so the host retries the unsettled remainder. Explicit settlement wins.\n * The callback must await all work that should determine delivery success.\n */\nexport async function consumeQueueBatch(\n batch: { readonly queue: string; readonly messages: readonly QueueMessageLike[] },\n dispatch: (job: QueueJob, message: QueueMessageLike) => Promise<QueueDispatchResult | void>,\n options: ConsumeQueueBatchOptions = {},\n): Promise<void> {\n const errors: unknown[] = [];\n for (const message of batch.messages) {\n try {\n const job = parseQueueJob(message.body, message.attempts);\n if (options.queues && !options.queues.includes(job.queue)) {\n throw new Error(\n `Queue '${job.queue}' is not consumed from '${batch.queue}', which accepts ` +\n `${options.queues.map((queue) => `'${queue}'`).join(', ')}.`,\n );\n }\n const observed = observeMessage(message);\n // eslint-disable-next-line no-await-in-loop\n const result = await dispatch(job, observed.message);\n if (result?.handled === 0) throw new Error(`Queue job '${job.name}' has no handler.`);\n if (observed.disposition().outcome === 'unsettled') observed.message.ack();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Queue batch deliveries failed.');\n}\n"],"mappings":";;;;;AAuBA,MAAa,oBAAoB,OAAO,OAAO;;CAE7C,UAAU;;C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,IAAI,KAAK,kBAAkB;EACpF,IAAI,SAAS,YAAY,CAAC,CAAC,YAAY,aAAa,SAAS,QAAQ,IAAI;CAC3E,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAEF,IAAI,OAAO,WAAW,GAAG,MAAM,OAAO;CACtC,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,gCAAgC;AAC1F"}
|
|
@@ -1,40 +1,79 @@
|
|
|
1
|
+
import { rateLimit } from "../bindings.js";
|
|
1
2
|
//#region src/rate-limit/cloudflare-rate-limit.store.ts
|
|
3
|
+
/** The periods a Rate Limiting binding supports, in milliseconds. */
|
|
4
|
+
const PERIODS = /* @__PURE__ */ new Set([1e4, 6e4]);
|
|
2
5
|
/**
|
|
3
|
-
*
|
|
6
|
+
* `ThrottlerModule`'s storage over Workers Rate Limiting bindings, read from
|
|
7
|
+
* each application's `ENV` by name:
|
|
4
8
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* ThrottlerModule.forRoot({
|
|
11
|
+
* throttlers: [{ ttl: 60_000, limit: 100 }],
|
|
12
|
+
* storage: rateLimitStore({ binding: 'API_LIMITER' }),
|
|
13
|
+
* })
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* The platform makes the allow/deny decision and exposes no counters or reset
|
|
17
|
+
* times, so the store reports no `remaining` quota. It enforces the limit and
|
|
18
|
+
* period configured on the binding, so it declares `fixedLimits`: a
|
|
19
|
+
* `@Throttle()` override that changes them fails instead of being ignored.
|
|
20
|
+
* Periods are 10 or 60 seconds. `ThrottlerModule` checks the declared
|
|
21
|
+
* throttlers against the bindings when the application starts.
|
|
7
22
|
*/
|
|
8
|
-
function
|
|
9
|
-
if (!binding || typeof binding !== "function" && typeof binding.limit !== "function") throw new TypeError("A Cloudflare Rate Limiting binding is required");
|
|
10
|
-
if (!Number.isSafeInteger(options.limit) || options.limit <= 0 || options.limit >= Number.MAX_SAFE_INTEGER) throw new RangeError("Rate limit must be a positive safe integer");
|
|
11
|
-
if (options.periodSeconds !== 10 && options.periodSeconds !== 60) throw new RangeError("Cloudflare rate-limit periods must be 10 or 60 seconds");
|
|
23
|
+
function rateLimitStore(options) {
|
|
12
24
|
const maxKeyBytes = options.maxKeyBytes ?? 1024;
|
|
13
25
|
if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes <= 0 || maxKeyBytes > 4096) throw new RangeError("maxKeyBytes must be between 1 and 4096");
|
|
14
|
-
const
|
|
26
|
+
const { binding } = options;
|
|
27
|
+
const single = typeof binding === "string" ? rateLimit({ binding }) : void 0;
|
|
28
|
+
const named = new Map(typeof binding === "string" ? [] : Object.entries(binding).map(([name, ref]) => [name, rateLimit({ binding: ref })]));
|
|
29
|
+
if (single === void 0 && named.size === 0) throw new TypeError("rateLimitStore needs a binding, or one per named throttler");
|
|
15
30
|
const encoder = new TextEncoder();
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
ttlMs,
|
|
28
|
-
allowed: decision.success,
|
|
29
|
-
enforcedLimit: options.limit
|
|
31
|
+
const checkPeriod = (name, ttl) => {
|
|
32
|
+
if (!PERIODS.has(ttl)) throw new Error(`Throttler '${name}' has a ${ttl}ms window; Workers Rate Limiting bindings support periods of 10 or 60 seconds.`);
|
|
33
|
+
};
|
|
34
|
+
const unmapped = (name) => /* @__PURE__ */ new Error(`rateLimitStore has no rate limiting binding for throttler '${name}'. Map it in rateLimitStore({ binding: { name: BINDING } }).`);
|
|
35
|
+
return (env) => {
|
|
36
|
+
let shared;
|
|
37
|
+
const assertShared = (name, ttl, limit) => {
|
|
38
|
+
shared ??= {
|
|
39
|
+
name,
|
|
40
|
+
ttl,
|
|
41
|
+
limit
|
|
30
42
|
};
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
43
|
+
if (shared.ttl !== ttl || shared.limit !== limit) throw new Error(`rateLimitStore({ binding: '${String(binding)}' }): one binding enforces one limit and period: throttlers '${shared.name}' (${shared.limit} per ${shared.ttl}ms) and '${name}' (${limit} per ${ttl}ms) need a binding each: rateLimitStore({ binding: { ${shared.name}: ..., ${name}: ... } }).`);
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
fixedLimits: true,
|
|
47
|
+
validate(throttlers) {
|
|
48
|
+
for (const { name, ttl, limit } of throttlers) {
|
|
49
|
+
checkPeriod(name, ttl);
|
|
50
|
+
if (single !== void 0) assertShared(name, ttl, limit);
|
|
51
|
+
else if (!named.has(name)) throw unmapped(name);
|
|
52
|
+
}
|
|
53
|
+
for (const name of named.keys()) if (!throttlers.some((throttler) => throttler.name === name)) throw new Error(`rateLimitStore maps throttler '${name}', which ThrottlerModule does not declare.`);
|
|
54
|
+
},
|
|
55
|
+
async increment(key, ttl, limit, throttlerName) {
|
|
56
|
+
checkPeriod(throttlerName, ttl);
|
|
57
|
+
if (typeof key !== "string" || key.length === 0 || /[\u0000-\u001f\u007f]/.test(key) || encoder.encode(key).byteLength > maxKeyBytes) throw new Error("Refusing an invalid or oversized rate-limit key");
|
|
58
|
+
if (single !== void 0) assertShared(throttlerName, ttl, limit);
|
|
59
|
+
const reference = single ?? named.get(throttlerName);
|
|
60
|
+
if (reference === void 0) throw unmapped(throttlerName);
|
|
61
|
+
const decision = await reference(env).limit({ key });
|
|
62
|
+
const success = typeof decision === "object" && decision !== null ? Reflect.get(decision, "success") : void 0;
|
|
63
|
+
if (typeof success !== "boolean") throw new Error("Cloudflare rate-limit binding returned an invalid decision");
|
|
64
|
+
return {
|
|
65
|
+
count: success ? 0 : limit + 1,
|
|
66
|
+
ttlMs: ttl,
|
|
67
|
+
allowed: success
|
|
68
|
+
};
|
|
69
|
+
},
|
|
70
|
+
reset() {
|
|
71
|
+
throw new Error("Cloudflare Rate Limiting bindings do not support counter reset");
|
|
72
|
+
}
|
|
73
|
+
};
|
|
35
74
|
};
|
|
36
75
|
}
|
|
37
76
|
//#endregion
|
|
38
|
-
export {
|
|
77
|
+
export { rateLimitStore };
|
|
39
78
|
|
|
40
79
|
//# sourceMappingURL=cloudflare-rate-limit.store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-rate-limit.store.js","names":[],"sources":["../../src/rate-limit/cloudflare-rate-limit.store.ts"],"sourcesContent":["import type { ThrottlerStorageRecord, ThrottlerStore } from '@velajs/vela/throttler';\
|
|
1
|
+
{"version":3,"file":"cloudflare-rate-limit.store.js","names":[],"sources":["../../src/rate-limit/cloudflare-rate-limit.store.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { ThrottlerStorageRecord, ThrottlerStore } from '@velajs/vela/throttler';\nimport { rateLimit } from '../bindings';\n\nexport interface RateLimitStoreOptions {\n /**\n * The Workers Rate Limiting binding (declared under `ratelimits`) that\n * serves every throttler, or one binding per named throttler:\n * `{ burst: 'BURST_LIMITER', sustained: 'API_LIMITER' }`. Each binding's\n * `simple.limit` and `simple.period` must equal its throttler's `limit` and\n * `ttl`; the platform enforces them. One binding therefore serves only\n * throttlers that share a limit and window: a throttler with other values,\n * or one the map leaves out, fails the application's bootstrap instead of\n * being enforced at the binding's.\n */\n binding: string | Readonly<Record<string, string>>;\n /** Bound attacker-influenced tracking keys before calling the platform. Default 1024. */\n maxKeyBytes?: number;\n}\n\n/** The periods a Rate Limiting binding supports, in milliseconds. */\nconst PERIODS = new Set([10_000, 60_000]);\n\n/**\n * `ThrottlerModule`'s storage over Workers Rate Limiting bindings, read from\n * each application's `ENV` by name:\n *\n * ```ts\n * ThrottlerModule.forRoot({\n * throttlers: [{ ttl: 60_000, limit: 100 }],\n * storage: rateLimitStore({ binding: 'API_LIMITER' }),\n * })\n * ```\n *\n * The platform makes the allow/deny decision and exposes no counters or reset\n * times, so the store reports no `remaining` quota. It enforces the limit and\n * period configured on the binding, so it declares `fixedLimits`: a\n * `@Throttle()` override that changes them fails instead of being ignored.\n * Periods are 10 or 60 seconds. `ThrottlerModule` checks the declared\n * throttlers against the bindings when the application starts.\n */\nexport function rateLimitStore(options: RateLimitStoreOptions): EnvFactory<ThrottlerStore> {\n const maxKeyBytes = options.maxKeyBytes ?? 1_024;\n if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes <= 0 || maxKeyBytes > 4_096) {\n throw new RangeError('maxKeyBytes must be between 1 and 4096');\n }\n const { binding } = options;\n const single = typeof binding === 'string' ? rateLimit({ binding }) : undefined;\n const named = new Map(\n typeof binding === 'string'\n ? []\n : Object.entries(binding).map(([name, ref]) => [name, rateLimit({ binding: ref })] as const),\n );\n if (single === undefined && named.size === 0) {\n throw new TypeError('rateLimitStore needs a binding, or one per named throttler');\n }\n const encoder = new TextEncoder();\n const checkPeriod = (name: string, ttl: number): void => {\n if (!PERIODS.has(ttl)) {\n throw new Error(\n `Throttler '${name}' has a ${ttl}ms window; Workers Rate Limiting bindings ` +\n 'support periods of 10 or 60 seconds.',\n );\n }\n };\n const unmapped = (name: string): Error =>\n new Error(\n `rateLimitStore has no rate limiting binding for throttler '${name}'. ` +\n 'Map it in rateLimitStore({ binding: { name: BINDING } }).',\n );\n\n return (env: VelaEnv): ThrottlerStore => {\n // The first throttler the single binding served: the binding enforces one\n // limit and period, so it cannot also serve a throttler declaring others.\n let shared: { name: string; ttl: number; limit: number } | undefined;\n const assertShared = (name: string, ttl: number, limit: number): void => {\n shared ??= { name, ttl, limit };\n if (shared.ttl !== ttl || shared.limit !== limit) {\n throw new Error(\n `rateLimitStore({ binding: '${String(binding)}' }): one binding enforces one limit and ` +\n `period: throttlers '${shared.name}' (${shared.limit} per ${shared.ttl}ms) and ` +\n `'${name}' (${limit} per ${ttl}ms) need a binding each: ` +\n `rateLimitStore({ binding: { ${shared.name}: ..., ${name}: ... } }).`,\n );\n }\n };\n return {\n fixedLimits: true,\n\n validate(throttlers) {\n for (const { name, ttl, limit } of throttlers) {\n checkPeriod(name, ttl);\n if (single !== undefined) assertShared(name, ttl, limit);\n else if (!named.has(name)) throw unmapped(name);\n }\n for (const name of named.keys()) {\n if (!throttlers.some((throttler) => throttler.name === name)) {\n throw new Error(\n `rateLimitStore maps throttler '${name}', which ThrottlerModule does not declare.`,\n );\n }\n }\n },\n\n async increment(\n key: string,\n ttl: number,\n limit: number,\n throttlerName: string,\n ): Promise<ThrottlerStorageRecord> {\n checkPeriod(throttlerName, ttl);\n if (\n typeof key !== 'string' ||\n key.length === 0 ||\n /[\\u0000-\\u001f\\u007f]/.test(key) ||\n encoder.encode(key).byteLength > maxKeyBytes\n ) {\n throw new Error('Refusing an invalid or oversized rate-limit key');\n }\n if (single !== undefined) assertShared(throttlerName, ttl, limit);\n const reference = single ?? named.get(throttlerName);\n if (reference === undefined) throw unmapped(throttlerName);\n const decision: unknown = await reference(env).limit({ key });\n const success: unknown =\n typeof decision === 'object' && decision !== null\n ? Reflect.get(decision, 'success')\n : undefined;\n if (typeof success !== 'boolean') {\n throw new Error('Cloudflare rate-limit binding returned an invalid decision');\n }\n return {\n // `allowed` is the authoritative platform decision; these sentinel counts\n // keep the record's shape without inventing a counter.\n count: success ? 0 : limit + 1,\n ttlMs: ttl,\n allowed: success,\n };\n },\n\n reset(): never {\n throw new Error('Cloudflare Rate Limiting bindings do not support counter reset');\n },\n };\n };\n}\n"],"mappings":";;;AAsBA,MAAM,0BAAU,IAAI,IAAI,CAAC,KAAQ,GAAM,CAAC;;;;;;;;;;;;;;;;;;;AAoBxC,SAAgB,eAAe,SAA4D;CACzF,MAAM,cAAc,QAAQ,eAAe;CAC3C,IAAI,CAAC,OAAO,cAAc,WAAW,KAAK,eAAe,KAAK,cAAc,MAC1E,MAAM,IAAI,WAAW,wCAAwC;CAE/D,MAAM,EAAE,YAAY;CACpB,MAAM,SAAS,OAAO,YAAY,WAAW,UAAU,EAAE,QAAQ,CAAC,IAAI,KAA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Y,eAAe,GAAG;IAC9B,IACE,OAAO,QAAQ,YACf,IAAI,WAAW,KACf,wBAAwB,KAAK,GAAG,KAChC,QAAQ,OAAO,GAAG,CAAC,CAAC,aAAa,aAEjC,MAAM,IAAI,MAAM,iDAAiD;IAEnE,IAAI,WAAW,KAAA,GAAW,aAAa,eAAe,KAAK,KAAK;IAChE,MAAM,YAAY,UAAU,MAAM,IAAI,aAAa;IACnD,IAAI,cAAc,KAAA,GAAW,MAAM,SAAS,aAAa;IACzD,MAAM,WAAoB,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC;IAC5D,MAAM,UACJ,OAAO,aAAa,YAAY,aAAa,OACzC,QAAQ,IAAI,UAAU,SAAS,IAC/B,KAAA;IACN,IAAI,OAAO,YAAY,WACrB,MAAM,IAAI,MAAM,4DAA4D;IAE9E,OAAO;KAGL,OAAO,UAAU,IAAI,QAAQ;KAC7B,OAAO;KACP,SAAS;IACX;GACF;GAEA,QAAe;IACb,MAAM,IAAI,MAAM,gEAAgE;GAClF;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/root-module.ts
|
|
2
|
+
/**
|
|
3
|
+
* @internal `root` with `providers` added to the root module's own providers,
|
|
4
|
+
* so each one injects what the root module can see.
|
|
5
|
+
*/
|
|
6
|
+
function withRootProviders(root, providers) {
|
|
7
|
+
if (typeof root === "function") return {
|
|
8
|
+
module: root,
|
|
9
|
+
providers: [...providers]
|
|
10
|
+
};
|
|
11
|
+
return {
|
|
12
|
+
...root,
|
|
13
|
+
providers: [...root.providers ?? [], ...providers]
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
export { withRootProviders };
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=root-module.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"root-module.js","names":[],"sources":["../src/root-module.ts"],"sourcesContent":["import type { DynamicModule, Type } from '@velajs/vela';\n\n/**\n * The root a Worker or Durable Object is built from: a module class or a\n * `DynamicModule`, declared once at module scope. Configuration that needs\n * bindings belongs in providers and `forRootAsync({ inject: [ENV] })`\n * factories, which run for each application with that application's ENV.\n */\nexport type CloudflareRoot = Type | DynamicModule;\n\n/**\n * @internal `root` with `providers` added to the root module's own providers,\n * so each one injects what the root module can see.\n */\nexport function withRootProviders(root: CloudflareRoot, providers: readonly Type[]): DynamicModule {\n if (typeof root === 'function') return { module: root, providers: [...providers] };\n return { ...root, providers: [...(root.providers ?? []), ...providers] };\n}\n"],"mappings":";;;;;AAcA,SAAgB,kBAAkB,MAAsB,WAA2C;CACjG,IAAI,OAAO,SAAS,YAAY,OAAO;EAAE,QAAQ;EAAM,WAAW,CAAC,GAAG,SAAS;CAAE;CACjF,OAAO;EAAE,GAAG;EAAM,WAAW,CAAC,GAAI,KAAK,aAAa,CAAC,GAAI,GAAG,SAAS;CAAE;AACzE"}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { HttpException, renderHttpError } from "@velajs/vela";
|
|
2
|
+
//#region src/rpc/entrypoint-error.ts
|
|
3
|
+
const NAME = "EntrypointError";
|
|
4
|
+
const CODE = /^[A-Za-z0-9_.:-]{1,160}$/;
|
|
5
|
+
const MAX_MESSAGE_LENGTH = 2048;
|
|
6
|
+
/**
|
|
7
|
+
* The one error the JS-RPC methods of a Vela entrypoint reject with: a
|
|
8
|
+
* Durable Object from `VelaDurableObject()` and a service entrypoint from
|
|
9
|
+
* `VelaEntrypoint()`. The entrypoint reports the original error first, then
|
|
10
|
+
* renders it as HTTP renders a response with server bodies redacted
|
|
11
|
+
* (`renderHttpError`): a 4xx `HttpException` keeps its code, message and
|
|
12
|
+
* details; a branded `VelaError` keeps its code and message at any status, and
|
|
13
|
+
* its details below 500; a 5xx `HttpException` becomes its status's code and
|
|
14
|
+
* title; an unknown error becomes `500 internal "Internal Server Error"`. A 4xx
|
|
15
|
+
* `HttpException` constructed with an object response keeps only its status
|
|
16
|
+
* (code `error`) unless that object is a canonical `{ error: { code, message,
|
|
17
|
+
* details } }` body. Only these own properties cross the RPC boundary: no stack
|
|
18
|
+
* frames, causes or other fields of the original.
|
|
19
|
+
*
|
|
20
|
+
* workerd rebuilds it on the caller's side as a plain `Error` with the same
|
|
21
|
+
* `name`, `status`, `code`, `message` and `details`; read it with
|
|
22
|
+
* {@link isEntrypointError}. That needs a Worker `compatibility_date` of
|
|
23
|
+
* 2026-04-21 or later, or the `enhanced_error_serialization` compatibility
|
|
24
|
+
* flag: before it, workerd delivers only an `Error` whose message is
|
|
25
|
+
* `EntrypointError: <message>`, without the status, code or details
|
|
26
|
+
* (`vela deploy check` warns about it). A host may throw one itself, for
|
|
27
|
+
* example to pass on another entrypoint's failure: a 4xx one keeps its code,
|
|
28
|
+
* message and details, a 5xx one only its status.
|
|
29
|
+
*/
|
|
30
|
+
var EntrypointError = class extends Error {
|
|
31
|
+
name = NAME;
|
|
32
|
+
status;
|
|
33
|
+
code;
|
|
34
|
+
constructor(init) {
|
|
35
|
+
super(init.message);
|
|
36
|
+
this.status = init.status;
|
|
37
|
+
this.code = init.code;
|
|
38
|
+
if (init.details !== void 0) Object.defineProperty(this, "details", {
|
|
39
|
+
value: init.details,
|
|
40
|
+
enumerable: true,
|
|
41
|
+
writable: false,
|
|
42
|
+
configurable: true
|
|
43
|
+
});
|
|
44
|
+
this.stack = `${NAME}: ${this.message}`;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Whether `error` is a failed JS-RPC call of a Vela entrypoint: an
|
|
49
|
+
* {@link EntrypointError}, or the plain `Error` workerd delivers for one to
|
|
50
|
+
* the caller. On a compatibility date before 2026-04-21 without
|
|
51
|
+
* `enhanced_error_serialization`, workerd drops the error's properties, so
|
|
52
|
+
* this is false.
|
|
53
|
+
*/
|
|
54
|
+
function isEntrypointError(error) {
|
|
55
|
+
if (typeof error !== "object" || error === null) return false;
|
|
56
|
+
return Reflect.get(error, "name") === NAME && typeof Reflect.get(error, "status") === "number" && typeof Reflect.get(error, "code") === "string" && typeof Reflect.get(error, "message") === "string";
|
|
57
|
+
}
|
|
58
|
+
/** @internal The redacted failure of an invocation that failed outside its pipeline. */
|
|
59
|
+
function internalEntrypointError() {
|
|
60
|
+
return new EntrypointError({
|
|
61
|
+
status: 500,
|
|
62
|
+
code: "internal",
|
|
63
|
+
message: "Internal Server Error"
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function clientDetails(value) {
|
|
67
|
+
if (value === void 0) return void 0;
|
|
68
|
+
try {
|
|
69
|
+
const text = JSON.stringify(value);
|
|
70
|
+
return text === void 0 ? void 0 : JSON.parse(text);
|
|
71
|
+
} catch {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function fromRendered(rendered) {
|
|
76
|
+
const status = Number.isInteger(rendered.status) && rendered.status >= 400 && rendered.status <= 599 ? rendered.status : 500;
|
|
77
|
+
const body = rendered.body;
|
|
78
|
+
const wire = typeof body === "object" && body !== null ? Reflect.get(body, "error") : void 0;
|
|
79
|
+
const field = (name) => typeof wire === "object" && wire !== null ? Reflect.get(wire, name) : void 0;
|
|
80
|
+
const rawCode = field("code");
|
|
81
|
+
const rawMessage = field("message");
|
|
82
|
+
const code = typeof rawCode === "string" && CODE.test(rawCode) ? rawCode : status >= 500 ? "internal" : "error";
|
|
83
|
+
return new EntrypointError({
|
|
84
|
+
status,
|
|
85
|
+
code,
|
|
86
|
+
message: status >= 500 && code === "internal" ? "Internal Server Error" : typeof rawMessage === "string" ? rawMessage.slice(0, MAX_MESSAGE_LENGTH) : "Entrypoint request failed",
|
|
87
|
+
details: status < 500 ? clientDetails(field("details")) : void 0
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* An {@link EntrypointError} a host rethrows, such as another entrypoint's
|
|
92
|
+
* failure: a client fault keeps its code, message and details; a server fault
|
|
93
|
+
* keeps only its status, rendered like an `HttpException` of that status.
|
|
94
|
+
*/
|
|
95
|
+
function renderPassedOn(error) {
|
|
96
|
+
if (Number.isInteger(error.status) && error.status >= 400 && error.status < 500) return {
|
|
97
|
+
status: error.status,
|
|
98
|
+
body: { error: {
|
|
99
|
+
code: error.code,
|
|
100
|
+
message: error.message,
|
|
101
|
+
details: error.details
|
|
102
|
+
} }
|
|
103
|
+
};
|
|
104
|
+
return renderHttpError(new HttpException("Entrypoint request failed", error.status));
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Render a failure of a JS-RPC call, after it was reported: the application's
|
|
108
|
+
* `ExceptionHandler.render` first, then the HTTP renderer with server bodies
|
|
109
|
+
* redacted. A 4xx {@link EntrypointError} passes through.
|
|
110
|
+
*/
|
|
111
|
+
function renderEntrypointError(error, reporter, context) {
|
|
112
|
+
if (isEntrypointError(error)) return fromRendered(renderPassedOn(error));
|
|
113
|
+
const override = reporter.render(error, context);
|
|
114
|
+
if (override instanceof Response) {
|
|
115
|
+
override.body?.cancel().catch(() => {});
|
|
116
|
+
return fromRendered(renderHttpError(new HttpException("Entrypoint request failed", override.status)));
|
|
117
|
+
}
|
|
118
|
+
return fromRendered(override ?? renderHttpError(error, {
|
|
119
|
+
catalog: reporter.catalog,
|
|
120
|
+
redactServerBodies: true
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Render a failure of a Durable Object's `fetch()` as the HTTP edge does: the
|
|
125
|
+
* application's `ExceptionHandler.render`, else the canonical JSON error body.
|
|
126
|
+
*/
|
|
127
|
+
function renderEntrypointResponse(error, reporter, context) {
|
|
128
|
+
if (isEntrypointError(error)) {
|
|
129
|
+
const rendered = fromRendered(renderPassedOn(error));
|
|
130
|
+
return Response.json({ error: {
|
|
131
|
+
code: rendered.code,
|
|
132
|
+
message: rendered.message,
|
|
133
|
+
...rendered.details === void 0 ? {} : { details: rendered.details }
|
|
134
|
+
} }, { status: rendered.status });
|
|
135
|
+
}
|
|
136
|
+
const override = reporter.render(error, context);
|
|
137
|
+
if (override instanceof Response) return override;
|
|
138
|
+
const rendered = override ?? renderHttpError(error, { catalog: reporter.catalog });
|
|
139
|
+
const status = rendered.status >= 400 && rendered.status <= 599 ? rendered.status : 500;
|
|
140
|
+
return Response.json(rendered.body, { status });
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
export { EntrypointError, internalEntrypointError, isEntrypointError, renderEntrypointError, renderEntrypointResponse };
|
|
144
|
+
|
|
145
|
+
//# sourceMappingURL=entrypoint-error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entrypoint-error.js","names":[],"sources":["../../src/rpc/entrypoint-error.ts"],"sourcesContent":["import { HttpException, renderHttpError, type RenderedHttpError } from '@velajs/vela';\nimport type { ErrorReporter } from '@velajs/vela/module-kit';\n\nconst NAME = 'EntrypointError';\nconst CODE = /^[A-Za-z0-9_.:-]{1,160}$/;\nconst MAX_MESSAGE_LENGTH = 2048;\n\n/** What a failed JS-RPC call of a Vela entrypoint carries across the RPC boundary. */\nexport interface EntrypointErrorInit {\n /** An HTTP error status, 400–599. */\n readonly status: number;\n /** A stable error code, such as `not_found` or `internal`. */\n readonly code: string;\n readonly message: string;\n /** Client-safe details of a client fault (4xx), such as validation issues. */\n readonly details?: unknown;\n}\n\n/**\n * The one error the JS-RPC methods of a Vela entrypoint reject with: a\n * Durable Object from `VelaDurableObject()` and a service entrypoint from\n * `VelaEntrypoint()`. The entrypoint reports the original error first, then\n * renders it as HTTP renders a response with server bodies redacted\n * (`renderHttpError`): a 4xx `HttpException` keeps its code, message and\n * details; a branded `VelaError` keeps its code and message at any status, and\n * its details below 500; a 5xx `HttpException` becomes its status's code and\n * title; an unknown error becomes `500 internal \"Internal Server Error\"`. A 4xx\n * `HttpException` constructed with an object response keeps only its status\n * (code `error`) unless that object is a canonical `{ error: { code, message,\n * details } }` body. Only these own properties cross the RPC boundary: no stack\n * frames, causes or other fields of the original.\n *\n * workerd rebuilds it on the caller's side as a plain `Error` with the same\n * `name`, `status`, `code`, `message` and `details`; read it with\n * {@link isEntrypointError}. That needs a Worker `compatibility_date` of\n * 2026-04-21 or later, or the `enhanced_error_serialization` compatibility\n * flag: before it, workerd delivers only an `Error` whose message is\n * `EntrypointError: <message>`, without the status, code or details\n * (`vela deploy check` warns about it). A host may throw one itself, for\n * example to pass on another entrypoint's failure: a 4xx one keeps its code,\n * message and details, a 5xx one only its status.\n */\nexport class EntrypointError extends Error implements EntrypointErrorInit {\n override readonly name = NAME;\n readonly status: number;\n readonly code: string;\n declare readonly details?: unknown;\n\n constructor(init: EntrypointErrorInit) {\n super(init.message);\n this.status = init.status;\n this.code = init.code;\n if (init.details !== undefined) {\n Object.defineProperty(this, 'details', {\n value: init.details,\n enumerable: true,\n writable: false,\n configurable: true,\n });\n }\n // workerd serializes the stack across RPC; it would disclose the entrypoint's frames.\n this.stack = `${NAME}: ${this.message}`;\n }\n}\n\n/**\n * Whether `error` is a failed JS-RPC call of a Vela entrypoint: an\n * {@link EntrypointError}, or the plain `Error` workerd delivers for one to\n * the caller. On a compatibility date before 2026-04-21 without\n * `enhanced_error_serialization`, workerd drops the error's properties, so\n * this is false.\n */\nexport function isEntrypointError(error: unknown): error is EntrypointError {\n if (typeof error !== 'object' || error === null) return false;\n return (\n Reflect.get(error, 'name') === NAME &&\n typeof Reflect.get(error, 'status') === 'number' &&\n typeof Reflect.get(error, 'code') === 'string' &&\n typeof Reflect.get(error, 'message') === 'string'\n );\n}\n\n/** @internal The redacted failure of an invocation that failed outside its pipeline. */\nexport function internalEntrypointError(): EntrypointError {\n return new EntrypointError({ status: 500, code: 'internal', message: 'Internal Server Error' });\n}\n\n// JSON-safe client details only: an RPC failure must stay serializable.\nfunction clientDetails(value: unknown): unknown {\n if (value === undefined) return undefined;\n try {\n const text = JSON.stringify(value);\n return text === undefined ? undefined : JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction fromRendered(rendered: Pick<RenderedHttpError, 'status' | 'body'>): EntrypointError {\n const status =\n Number.isInteger(rendered.status) && rendered.status >= 400 && rendered.status <= 599\n ? rendered.status\n : 500;\n const body: unknown = rendered.body;\n const wire: unknown =\n typeof body === 'object' && body !== null ? Reflect.get(body, 'error') : undefined;\n const field = (name: string): unknown =>\n typeof wire === 'object' && wire !== null ? Reflect.get(wire, name) : undefined;\n const rawCode = field('code');\n const rawMessage = field('message');\n const code =\n typeof rawCode === 'string' && CODE.test(rawCode)\n ? rawCode\n : status >= 500\n ? 'internal'\n : 'error';\n const message =\n status >= 500 && code === 'internal'\n ? 'Internal Server Error'\n : typeof rawMessage === 'string'\n ? rawMessage.slice(0, MAX_MESSAGE_LENGTH)\n : 'Entrypoint request failed';\n const details = status < 500 ? clientDetails(field('details')) : undefined;\n return new EntrypointError({ status, code, message, details });\n}\n\n/**\n * An {@link EntrypointError} a host rethrows, such as another entrypoint's\n * failure: a client fault keeps its code, message and details; a server fault\n * keeps only its status, rendered like an `HttpException` of that status.\n */\nfunction renderPassedOn(error: EntrypointError): Pick<RenderedHttpError, 'status' | 'body'> {\n if (Number.isInteger(error.status) && error.status >= 400 && error.status < 500) {\n return {\n status: error.status,\n body: { error: { code: error.code, message: error.message, details: error.details } },\n };\n }\n return renderHttpError(new HttpException('Entrypoint request failed', error.status));\n}\n\n/**\n * Render a failure of a JS-RPC call, after it was reported: the application's\n * `ExceptionHandler.render` first, then the HTTP renderer with server bodies\n * redacted. A 4xx {@link EntrypointError} passes through.\n */\nexport function renderEntrypointError(\n error: unknown,\n reporter: ErrorReporter,\n context: unknown,\n): EntrypointError {\n if (isEntrypointError(error)) return fromRendered(renderPassedOn(error));\n const override = reporter.render(error, context);\n if (override instanceof Response) {\n void override.body?.cancel().catch(() => {});\n return fromRendered(\n renderHttpError(new HttpException('Entrypoint request failed', override.status)),\n );\n }\n return fromRendered(\n override ?? renderHttpError(error, { catalog: reporter.catalog, redactServerBodies: true }),\n );\n}\n\n/**\n * Render a failure of a Durable Object's `fetch()` as the HTTP edge does: the\n * application's `ExceptionHandler.render`, else the canonical JSON error body.\n */\nexport function renderEntrypointResponse(\n error: unknown,\n reporter: ErrorReporter,\n context: unknown,\n): Response {\n if (isEntrypointError(error)) {\n const rendered = fromRendered(renderPassedOn(error));\n return Response.json(\n {\n error: {\n code: rendered.code,\n message: rendered.message,\n ...(rendered.details === undefined ? {} : { details: rendered.details }),\n },\n },\n { status: rendered.status },\n );\n }\n const override = reporter.render(error, context);\n if (override instanceof Response) return override;\n const rendered = override ?? renderHttpError(error, { catalog: reporter.catalog });\n const status = rendered.status >= 400 && rendered.status <= 599 ? rendered.status : 500;\n return Response.json(rendered.body, { status });\n}\n"],"mappings":";;AAGA,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;AAqC3B,IAAa,kBAAb,cAAqC,MAAqC;CACxE,OAAyB;CACzB;CACA;CAGA,YAAY,MAA2B;EACrC,MAAM,KAAK,OAAO;EAClB,KAAK,SAAS,KAAK;EACnB,KAAK,OAAO,KAAK;EACjB,IAAI,KAAK,YAAY,KAAA,GACnB,OAAO,eAAe,MAAM,WAAW;GACrC,OAAO,KAAK;GACZ,YAAY;GACZ,UAAU;GACV,cAAc;EAChB,CAAC;EAGH,KAAK,QAAQ,GAAG,KAAK,IAAI,KAAK;CAChC;AACF;;;;;;;;AASA,SAAgB,kBAAkB,OAA0C;CAC1E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OACE,QAAQ,IAAI,OAAO,MAAM,MAAM,QAC/B,OAAO,QAAQ,IAAI,OAAO,QAAQ,MAAM,YACxC,OAAO,QAAQ,IAAI,OAAO,MAAM,MAAM,YACtC,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM;AAE7C;;AAGA,SAAgB,0BAA2C;CACzD,OAAO,IAAI,gBAAgB;EAAE,QAAQ;EAAK,MAAM;EAAY,SAAS;CAAwB,CAAC;AAChG;AAGA,SAAS,cAAc,OAAyB;CAC9C,IAAI,UA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