@velajs/cloudflare 1.30.0 → 1.31.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 +112 -0
- package/README.md +260 -74
- package/dist/bindings.js +77 -0
- package/dist/bindings.js.map +1 -0
- package/dist/cloudflare-application.js +7 -34
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-eGiet0mg.d.ts +288 -0
- package/dist/cloudflare-factory.js +84 -28
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/diagnostics.js +18 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/durable-objects.d.ts +6 -2
- package/dist/index.d.ts +160 -455
- package/dist/index.js +7 -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-C23bUwt_.d.ts +11 -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/testing.d.ts +96 -0
- package/dist/testing.js +111 -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 +36 -15
- 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 +14 -10
- 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/package.json +23 -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,15 @@
|
|
|
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 { StorageManagerService } from "./storage/storage-manager.service.js";
|
|
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 } from "./bindings.js";
|
|
5
|
+
import { durableObjectLive } from "./websocket/live-driver.js";
|
|
6
|
+
import { CLOUDFLARE_WORKER, cloudflareAdapter, createCloudflareApp, createCloudflareWorker } from "./cloudflare-factory.js";
|
|
7
|
+
import { KVCacheInvalidationStore, KVCacheStore, kvCache, kvCacheInvalidation } from "./services/kv-cache.store.js";
|
|
13
8
|
import { FlagshipFlagDriver, flagshipFlagDriver } from "./services/flagship-flag.driver.js";
|
|
14
9
|
import { KvFlagDriver, kvFlagDriver } from "./services/kv-flag.driver.js";
|
|
15
10
|
import { QueueConsumer } from "./decorators/queue-consumer.js";
|
|
16
11
|
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";
|
|
12
|
+
import { DoCursorLog, liveInvalidateToRoom } from "./websocket/do-live.js";
|
|
13
|
+
import { rateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
|
|
20
14
|
import { durableObjectNonceStore } from "./nonce/durable-object-nonce.store.js";
|
|
21
|
-
export { CLOUDFLARE_SCHEDULED_EVENT,
|
|
15
|
+
export { CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CloudflareApplication, DoCursorLog, DoPitrUnavailableError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, d1, durableObject, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagshipFlagDriver, isDoPitrUnavailable, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark };
|
|
@@ -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,OAAO;CAC5B,KAAK,IAAI,KAAK;CACd,IAAI,QAAQ;CACZ,IAAI,YAAY,OAAO,KAAK,KAAK,iBAAiB,aAChD,SAAS,MAAM,aAAa;MACvB,IAAI,iBAAiB,MAC1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,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;;CAEV,YAAY;;CAEZ,cAAc;AAChB,CAAC;;AAGD,MAAM,uBAAuB;AAC7B,MAAM,eAAe;;;;;;AAOrB,SAAS,YAAY,MAAsB;CACzC,IAAI,OAAO;CACX,IAAI,OAA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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,KAAA;CACtE,MAAM,QAAQ,IAAI,IAChB,OAAO,YAAY,WACf,CAAC,IACD,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,MAAM,SAAS,CAAC,MAAM,UAAU,EAAE,SA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,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,11 @@
|
|
|
1
|
+
import { DynamicModule, Type } from "@velajs/vela";
|
|
2
|
+
//#region src/root-module.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The root a Worker or Durable Object is built from: a module class or a
|
|
5
|
+
* `DynamicModule`, declared once at module scope. Configuration that needs
|
|
6
|
+
* bindings belongs in providers and `forRootAsync({ inject: [ENV] })`
|
|
7
|
+
* factories, which run for each application with that application's ENV.
|
|
8
|
+
*/
|
|
9
|
+
type CloudflareRoot = Type | DynamicModule;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { CloudflareRoot as t };
|
|
@@ -1,15 +1,6 @@
|
|
|
1
|
+
import { reportDiagnostic } from "./diagnostics.js";
|
|
1
2
|
import { cronDialectAmbiguity, parseCronMetadata, parseIntervalMetadata, scheduledJobComponents } from "@velajs/vela/module-kit";
|
|
2
3
|
//#region src/schedule-diagnostics.ts
|
|
3
|
-
const reported = /* @__PURE__ */ new Set();
|
|
4
|
-
/** `'throw'` fails the caller, `'log'` warns once per message in this isolate. */
|
|
5
|
-
function reportScheduleDiagnostic(container, message) {
|
|
6
|
-
const mode = container.getDiagnostics();
|
|
7
|
-
if (mode === "silent") return;
|
|
8
|
-
if (mode === "throw") throw new Error(message);
|
|
9
|
-
if (reported.has(message)) return;
|
|
10
|
-
reported.add(message);
|
|
11
|
-
console.warn(message);
|
|
12
|
-
}
|
|
13
4
|
function jobName(entry) {
|
|
14
5
|
return `${typeof entry.token === "function" ? entry.token.name : String(entry.token)}.${entry.meta.methodName}`;
|
|
15
6
|
}
|
|
@@ -20,7 +11,9 @@ function jobName(entry) {
|
|
|
20
11
|
function reportComponents(container, label, entry) {
|
|
21
12
|
const decorators = scheduledJobComponents(container, entry);
|
|
22
13
|
if (decorators.length === 0) return;
|
|
23
|
-
|
|
14
|
+
const named = decorators.length > 1 ? `${decorators.slice(0, -1).join(", ")} and ${decorators.at(-1)}` : decorators.join("");
|
|
15
|
+
const refused = decorators.includes("@UseGuards") ? ", and one that declares guards refuses to run" : "";
|
|
16
|
+
reportDiagnostic(container, `[vela] ${label} declares ${named}, which do not run for scheduled jobs: a direct job runs no guards, interceptors or filters${refused}. Use signed ScheduleModule dispatch and declare them on the signed route to run the job through the request pipeline.`);
|
|
24
17
|
}
|
|
25
18
|
/**
|
|
26
19
|
* Report schedule declarations a Workers cron trigger cannot honor as written:
|
|
@@ -38,12 +31,12 @@ function reportCloudflareScheduleDiagnostics(container, entrypoints) {
|
|
|
38
31
|
for (const entry of entrypoints.ofKind("schedule:cron", parseCronMetadata)) {
|
|
39
32
|
const cron = `@Cron('${entry.meta.expression}') on ${jobName(entry)}`;
|
|
40
33
|
const ambiguity = cronDialectAmbiguity(entry.meta);
|
|
41
|
-
if (ambiguity)
|
|
42
|
-
if (entry.meta.dialect === "unix")
|
|
43
|
-
if (entry.meta.timeZone === "local")
|
|
34
|
+
if (ambiguity) reportDiagnostic(container, `[vela] ${cron} declares no dialect, and ${ambiguity}. Workers deliver the trigger with Cloudflare semantics while Node reads it with Vela's unix dialect; declare { dialect: 'cloudflare' } so it fires on the same days on every runtime.`);
|
|
35
|
+
if (entry.meta.dialect === "unix") reportDiagnostic(container, `[vela] ${cron} declares dialect 'unix', but Cloudflare delivers its trigger with Cloudflare cron semantics (weekdays 1 = Sunday through 7 = Saturday). Declare { dialect: 'cloudflare' } and write the expression for Cloudflare.`);
|
|
36
|
+
if (entry.meta.timeZone === "local") reportDiagnostic(container, `[vela] ${cron} declares timeZone 'local', but Cloudflare cron triggers run in UTC. Remove timeZone or set it to 'UTC'.`);
|
|
44
37
|
reportComponents(container, cron, entry);
|
|
45
38
|
}
|
|
46
|
-
for (const entry of entrypoints.ofKind("schedule:interval", parseIntervalMetadata))
|
|
39
|
+
for (const entry of entrypoints.ofKind("schedule:interval", parseIntervalMetadata)) reportDiagnostic(container, `[vela] @Interval(${entry.meta.ms}) on ${jobName(entry)} never runs on Workers: cron triggers drive only @Cron jobs. Replace it with a @Cron job and a Wrangler trigger, or run it under ScheduleNodeModule on Node.`);
|
|
47
40
|
}
|
|
48
41
|
//#endregion
|
|
49
42
|
export { reportCloudflareScheduleDiagnostics };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schedule-diagnostics.js","names":[],"sources":["../src/schedule-diagnostics.ts"],"sourcesContent":["import {\n cronDialectAmbiguity,\n parseCronMetadata,\n parseIntervalMetadata,\n scheduledJobComponents,\n} from '@velajs/vela/module-kit';\nimport type { VelaApplication } from '@velajs/vela';\nimport type { Entrypoint, Container } from '@velajs/vela/module-kit';\
|
|
1
|
+
{"version":3,"file":"schedule-diagnostics.js","names":[],"sources":["../src/schedule-diagnostics.ts"],"sourcesContent":["import {\n cronDialectAmbiguity,\n parseCronMetadata,\n parseIntervalMetadata,\n scheduledJobComponents,\n} from '@velajs/vela/module-kit';\nimport type { VelaApplication } from '@velajs/vela';\nimport type { Entrypoint, Container } from '@velajs/vela/module-kit';\nimport { reportDiagnostic as reportScheduleDiagnostic } from './diagnostics';\n\nfunction jobName(entry: Entrypoint<{ methodName: string }>): string {\n const owner = typeof entry.token === 'function' ? entry.token.name : String(entry.token);\n return `${owner}.${entry.meta.methodName}`;\n}\n\n/**\n * Guards, interceptors and filters declared for a job never run on its\n * trigger, and a direct job that declares guards is refused on every trigger.\n */\nfunction reportComponents(\n container: Container,\n label: string,\n entry: Entrypoint<{ methodName: string }>,\n): void {\n const decorators = scheduledJobComponents(container, entry);\n if (decorators.length === 0) return;\n const named =\n decorators.length > 1\n ? `${decorators.slice(0, -1).join(', ')} and ${decorators.at(-1)!}`\n : decorators.join('');\n const refused = decorators.includes('@UseGuards')\n ? ', and one that declares guards refuses to run'\n : '';\n reportScheduleDiagnostic(\n container,\n `[vela] ${label} declares ${named}, which do not run for scheduled jobs: a direct job ` +\n `runs no guards, interceptors or filters${refused}. Use signed ScheduleModule dispatch ` +\n `and declare them on the signed route to run the job through the request pipeline.`,\n );\n}\n\n/**\n * Report schedule declarations a Workers cron trigger cannot honor as written:\n * a dialect-ambiguous `@Cron`, `dialect: 'unix'`, `timeZone: 'local'`,\n * `@Interval` jobs, and guards, interceptors or filters declared for a job\n * (a direct job that declares guards is refused when it fires).\n * The container's diagnostics policy applies: `'throw'` fails bootstrap and the\n * default `'log'` warns once per declaration, so the first event of a Worker\n * (which bootstraps the application) never fails because of these checks.\n * `vela deploy check` rejects the cron declarations, `@Interval` jobs and\n * guarded direct jobs before deployment (`ambiguous-cron-dialect`,\n * `incompatible-cron-options`, `unsupported-interval`, `scheduled-job-guards`).\n */\nexport function reportCloudflareScheduleDiagnostics(\n container: Container,\n entrypoints: VelaApplication['entrypoints'],\n): void {\n for (const entry of entrypoints.ofKind('schedule:cron', parseCronMetadata)) {\n const cron = `@Cron('${entry.meta.expression}') on ${jobName(entry)}`;\n const ambiguity = cronDialectAmbiguity(entry.meta);\n if (ambiguity) {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares no dialect, and ${ambiguity}. Workers deliver the trigger ` +\n `with Cloudflare semantics while Node reads it with Vela's unix dialect; declare ` +\n `{ dialect: 'cloudflare' } so it fires on the same days on every runtime.`,\n );\n }\n if (entry.meta.dialect === 'unix') {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares dialect 'unix', but Cloudflare delivers its trigger with ` +\n `Cloudflare cron semantics (weekdays 1 = Sunday through 7 = Saturday). Declare ` +\n `{ dialect: 'cloudflare' } and write the expression for Cloudflare.`,\n );\n }\n if (entry.meta.timeZone === 'local') {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares timeZone 'local', but Cloudflare cron triggers run in UTC. ` +\n `Remove timeZone or set it to 'UTC'.`,\n );\n }\n reportComponents(container, cron, entry);\n }\n for (const entry of entrypoints.ofKind('schedule:interval', parseIntervalMetadata)) {\n reportScheduleDiagnostic(\n container,\n `[vela] @Interval(${entry.meta.ms}) on ${jobName(entry)} never runs on Workers: cron ` +\n `triggers drive only @Cron jobs. Replace it with a @Cron job and a Wrangler trigger, ` +\n `or run it under ScheduleNodeModule on Node.`,\n );\n }\n}\n"],"mappings":";;;AAUA,SAAS,QAAQ,OAAmD;CAElE,OAAO,GADO,OAAO,MAAM,UAAU,aAAa,MAAM,MAAM,OAAO,OAAO,MAAM,KAAK,EACvE,GAAG,MAAM,KAAK;AAChC;;;;;AAMA,SAAS,iBACP,WACA,OACA,OACM;CACN,MAAM,aAAa,uBAAuB,WAAW,KAAK;CAC1D,IAAI,WAAW,WAAW,GAAG;CAC7B,MAAM,QACJ,WAAW,SAAS,IAChB,GAAG,WAAW,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,WAAW,GAAG,EAAE,MAC7D,WAAW,KAAK,EAAE;CACxB,MAAM,UAAU,WAAW,SAAS,YAAY,IAC5C,kDACA;CACJ,iBACE,WACA,UAAU,MAAM,YAAY,MAAM,6FACU,QAAQ,uHAEtD;AACF;;;;;;;;;;;;;AAcA,SAAgB,oCACd,WACA,aACM;CACN,KAAK,MAAM,SAAS,YAAY,OAAO,iBAAiB,iBAAiB,GAAG;EAC1E,MAAM,OAAO,UAAU,MAAM,KAAK,WAAW,QAAQ,QAAQ,KAAK;EAClE,MAAM,YAAY,qBAAqB,MAAM,IAAI;EACjD,IAAI,WACF,iBACE,WACA,UAAU,KAAK,4BAA4B,UAAU,uLAGvD;EAEF,IAAI,MAAM,KAAK,YAAY,QACzB,iBACE,WACA,UAAU,KAAK,oNAGjB;EAEF,IAAI,MAAM,KAAK,aAAa,SAC1B,iBACE,WACA,UAAU,KAAK,yGAEjB;EAEF,iBAAiB,WAAW,MAAM,KAAK;CACzC;CACA,KAAK,MAAM,SAAS,YAAY,OAAO,qBAAqB,qBAAqB,GAC/E,iBACE,WACA,oBAAoB,MAAM,KAAK,GAAG,OAAO,QAAQ,KAAK,EAAE,6JAG1D;AAEJ"}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
|
+
import { kv } from "../bindings.js";
|
|
1
2
|
//#region src/services/kv-cache.store.ts
|
|
3
|
+
const namespaceOf = (source) => typeof source === "function" ? source : () => source;
|
|
2
4
|
/**
|
|
3
5
|
* Native KV JSON value store. Metadata retains logical expiry even when KV's
|
|
4
6
|
* physical retention rounds up to its 60-second minimum. Legacy values without
|
|
5
7
|
* metadata remain readable, but cannot safely backfill another tier.
|
|
6
8
|
*/
|
|
7
9
|
var KVCacheStore = class {
|
|
8
|
-
|
|
9
|
-
constructor(
|
|
10
|
-
this
|
|
10
|
+
#namespace;
|
|
11
|
+
constructor(namespace) {
|
|
12
|
+
this.#namespace = namespaceOf(namespace);
|
|
13
|
+
}
|
|
14
|
+
get ns() {
|
|
15
|
+
return this.#namespace();
|
|
11
16
|
}
|
|
12
17
|
async get(key) {
|
|
13
18
|
return (await this.getEntry(key))?.value;
|
|
@@ -62,9 +67,12 @@ var KVCacheStore = class {
|
|
|
62
67
|
* this is unsuitable for strict read-after-write or authorization revocation.
|
|
63
68
|
*/
|
|
64
69
|
var KVCacheInvalidationStore = class {
|
|
65
|
-
|
|
66
|
-
constructor(
|
|
67
|
-
this
|
|
70
|
+
#namespace;
|
|
71
|
+
constructor(namespace) {
|
|
72
|
+
this.#namespace = namespaceOf(namespace);
|
|
73
|
+
}
|
|
74
|
+
get ns() {
|
|
75
|
+
return this.#namespace();
|
|
68
76
|
}
|
|
69
77
|
async getVersion(key) {
|
|
70
78
|
const value = await this.ns.get(key, "json");
|
|
@@ -76,7 +84,25 @@ var KVCacheInvalidationStore = class {
|
|
|
76
84
|
await this.ns.put(key, JSON.stringify(crypto.randomUUID()));
|
|
77
85
|
}
|
|
78
86
|
};
|
|
87
|
+
/**
|
|
88
|
+
* `CacheModule`'s value store over the KV namespace named `binding`, read from
|
|
89
|
+
* each application's `ENV` when an operation needs it:
|
|
90
|
+
* `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.
|
|
91
|
+
*/
|
|
92
|
+
function kvCache(ref) {
|
|
93
|
+
const namespace = kv(ref);
|
|
94
|
+
return (env) => new KVCacheStore(() => namespace(env));
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* `CacheModule`'s generation store over a dedicated KV namespace named
|
|
98
|
+
* `binding`, without TTLs or lifecycle cleanup. Eventually consistent; see
|
|
99
|
+
* {@link KVCacheInvalidationStore}.
|
|
100
|
+
*/
|
|
101
|
+
function kvCacheInvalidation(ref) {
|
|
102
|
+
const namespace = kv(ref);
|
|
103
|
+
return (env) => new KVCacheInvalidationStore(() => namespace(env));
|
|
104
|
+
}
|
|
79
105
|
//#endregion
|
|
80
|
-
export { KVCacheInvalidationStore, KVCacheStore };
|
|
106
|
+
export { KVCacheInvalidationStore, KVCacheStore, kvCache, kvCacheInvalidation };
|
|
81
107
|
|
|
82
108
|
//# sourceMappingURL=kv-cache.store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kv-cache.store.js","names":[],"sources":["../../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"kv-cache.store.js","names":[],"sources":["../../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n CacheEntry,\n CacheEntryReader,\n CacheEntryWriter,\n CacheInvalidationStore,\n CacheStore,\n} from '@velajs/vela/cache';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport { kv } from '../bindings';\n\n/** A KV namespace, or a function that reads it when an operation needs it. */\nexport type KVNamespaceSource = KVNamespace | (() => KVNamespace);\n\nconst namespaceOf = (source: KVNamespaceSource): (() => KVNamespace) =>\n typeof source === 'function' ? source : () => source;\n\n/**\n * Native KV JSON value store. Metadata retains logical expiry even when KV's\n * physical retention rounds up to its 60-second minimum. Legacy values without\n * metadata remain readable, but cannot safely backfill another tier.\n */\nexport class KVCacheStore implements CacheStore, CacheEntryReader, CacheEntryWriter {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async get(key: string): Promise<unknown> {\n return (await this.getEntry(key))?.value;\n }\n\n async getEntry(key: string): Promise<{ value: unknown; expiresAt?: number } | undefined> {\n const { value, metadata } = await this.ns.getWithMetadata<unknown, unknown>(key, 'json');\n if (value === null) return undefined;\n if (typeof metadata === 'object' && metadata !== null && 'velaCacheExpiresAt' in metadata) {\n const expiresAt = metadata.velaCacheExpiresAt;\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= Date.now())\n return undefined;\n return { value, expiresAt };\n }\n return { value };\n }\n\n async set(key: string, value: unknown, ttl?: number): Promise<void> {\n if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0))\n throw new TypeError('Cache TTL must be finite and nonnegative.');\n if (ttl !== undefined) return this.setEntry(key, { value, expiresAt: Date.now() + ttl * 1000 });\n await this.ns.put(key, JSON.stringify(value));\n }\n\n async setEntry(key: string, entry: CacheEntry): Promise<void> {\n if (!Number.isFinite(entry.expiresAt)) throw new TypeError('Cache expiry must be finite.');\n const remaining = (entry.expiresAt - Date.now()) / 1000;\n if (remaining <= 0) return this.del(key);\n await this.ns.put(key, JSON.stringify(entry.value), {\n expirationTtl: Math.max(60, Math.ceil(remaining)),\n metadata: { velaCacheExpiresAt: entry.expiresAt },\n });\n }\n\n async del(key: string): Promise<void> {\n await this.ns.delete(key);\n }\n\n /** Namespace-wide, best effort. Use a dedicated value namespace; never use for scoped invalidation. */\n async clear(): Promise<void> {\n let cursor: string | undefined;\n do {\n const list = await this.ns.list(cursor ? { cursor } : undefined);\n await Promise.all(list.keys.map((entry) => this.ns.delete(entry.name)));\n cursor = list.list_complete ? undefined : list.cursor;\n } while (cursor);\n }\n}\n\n/**\n * Optional, eventually consistent generation store. Use a dedicated KV namespace\n * without TTL/lifecycle cleanup. Never delete/reset generations while entries can\n * survive. Concurrent writes and cached/negative reads prevent strong invalidation;\n * this is unsuitable for strict read-after-write or authorization revocation.\n */\nexport class KVCacheInvalidationStore implements CacheInvalidationStore {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async getVersion(key: string): Promise<string> {\n const value: unknown = await this.ns.get(key, 'json');\n if (value === null) return 'initial';\n if (typeof value !== 'string' || value.length === 0 || value.length > 2048)\n throw new TypeError('Invalid cache generation.');\n return value;\n }\n async invalidate(key: string): Promise<void> {\n await this.ns.put(key, JSON.stringify(crypto.randomUUID()));\n }\n}\n\n/**\n * `CacheModule`'s value store over the KV namespace named `binding`, read from\n * each application's `ENV` when an operation needs it:\n * `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\nexport function kvCache(ref: { binding: string }): EnvFactory<CacheStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheStore(() => namespace(env));\n}\n\n/**\n * `CacheModule`'s generation store over a dedicated KV namespace named\n * `binding`, without TTLs or lifecycle cleanup. Eventually consistent; see\n * {@link KVCacheInvalidationStore}.\n */\nexport function kvCacheInvalidation(ref: { binding: string }): EnvFactory<CacheInvalidationStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheInvalidationStore(() => namespace(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|
|
1
|
+
import { r2 } from "../bindings.js";
|
|
2
|
+
import { r2Driver } from "@velajs/storage/drivers/r2";
|
|
3
|
+
//#region src/storage/r2-storage.ts
|
|
4
|
+
/**
|
|
5
|
+
* The native R2 driver for `@velajs/storage`, reading its bucket from the
|
|
6
|
+
* application's `ENV` by name:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* `StorageModule` builds the driver on the first storage operation of each
|
|
13
|
+
* application, so a static module graph serves every environment and boot
|
|
14
|
+
* touches no binding. A missing or mistyped binding fails that operation with
|
|
15
|
+
* a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot
|
|
16
|
+
* presign uploads; serve downloads through `publicBaseUrl` or the module's
|
|
17
|
+
* `http: { download: 'proxy' }` controller.
|
|
18
|
+
*/
|
|
19
|
+
function r2Storage(options) {
|
|
20
|
+
const { binding, ...driver } = options;
|
|
21
|
+
const bucket = r2({ binding });
|
|
22
|
+
return (env) => r2Driver({
|
|
23
|
+
...driver,
|
|
24
|
+
bucket: bucket(env)
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
export { r2Storage };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=r2-storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"r2-storage.js","names":[],"sources":["../../src/storage/r2-storage.ts"],"sourcesContent":["import type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { StorageDriver } from '@velajs/storage';\nimport { r2Driver, type R2DriverOptions } from '@velajs/storage/drivers/r2';\nimport { r2 } from '../bindings';\n\n/** `r2Storage` options: the bucket's binding name and the native driver's settings. */\nexport interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {\n /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */\n binding: string;\n}\n\n/**\n * The native R2 driver for `@velajs/storage`, reading its bucket from the\n * application's `ENV` by name:\n *\n * ```ts\n * StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })\n * ```\n *\n * `StorageModule` builds the driver on the first storage operation of each\n * application, so a static module graph serves every environment and boot\n * touches no binding. A missing or mistyped binding fails that operation with\n * a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot\n * presign uploads; serve downloads through `publicBaseUrl` or the module's\n * `http: { download: 'proxy' }` controller.\n */\nexport function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>> {\n const { binding, ...driver } = options;\n const bucket = r2({ binding });\n return (env) => r2Driver({ ...driver, bucket: bucket(env) });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,SAAgB,UAAU,SAAgE;CACxF,MAAM,EAAE,SAAS,GAAG,WAAW;CAC/B,MAAM,SAAS,GAAG,EAAE,QAAQ,CAAC;CAC7B,QAAQ,QAAQ,SAAS;EAAE,GAAG;EAAQ,QAAQ,OAAO,GAAG;CAAE,CAAC;AAC7D"}
|