@velajs/cloudflare 1.28.0 → 1.29.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 +89 -0
- package/README.md +189 -69
- package/dist/durable-objects.d.ts +9 -8
- package/dist/durable-objects.js +30 -18
- package/dist/durable-objects.js.map +1 -1
- package/dist/index.d.ts +141 -108
- package/dist/index.js +333 -187
- package/dist/index.js.map +1 -1
- package/dist/{nonce-validation-CeVihShV.js → nonce-validation-Dy8z05A9.js} +140 -135
- package/dist/nonce-validation-Dy8z05A9.js.map +1 -0
- package/dist/{nonce.durable-object-DffHMRnU.d.ts → nonce.durable-object-Df4CZi-0.d.ts} +8 -5
- package/dist/queues.d.ts +49 -0
- package/dist/queues.js +215 -0
- package/dist/queues.js.map +1 -0
- package/dist/vela-env-DFvyoNT3.d.ts +10 -0
- package/package.json +11 -10
- package/dist/nonce-validation-CeVihShV.js.map +0 -1
- package/dist/queue.d.ts +0 -32
- package/dist/queue.js +0 -78
- package/dist/queue.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durable-objects.js","names":[],"sources":["../src/websocket/cf-room-registry.ts","../src/websocket/do-websocket-host.ts","../src/websocket/do-bootstrap.ts","../src/websocket/websocket.durable-object.ts","../src/nonce/nonce.durable-object.ts"],"sourcesContent":["import { WebSocketSendGate, type WebSocketSendPolicy } from '@velajs/vela/websocket';\nimport { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n readonly #sendGates = new WeakMap<WsLike, WebSocketSendGate>();\n #sendPolicyForPath?: (path: string) => WebSocketSendPolicy | undefined;\n\n setSendPolicyResolver(resolve: (path: string) => WebSocketSendPolicy | undefined): void {\n this.#sendPolicyForPath = resolve;\n }\n\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const att = this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n if (\n att.state !== 'active' ||\n (att.expiresAtMs !== undefined &&\n (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now()))\n ) {\n try {\n att.state = 'rejected';\n ws.serializeAttachment(att);\n ws.close(1008, 'identity expired or connection rejected');\n } catch {\n // already closed or malformed attachment\n }\n continue;\n }\n if (seen.has(att.connId)) continue;\n seen.add(att.connId);\n if (excludeIds.has(att.connId)) continue;\n if (excludeRooms.some((r) => att.rooms.includes(r))) continue;\n selected.push({ ws, client: this.clientFor(ws) });\n }\n\n if (!this.deliveryAuthorizer) {\n for (const { client } of selected) client.sendRaw(cmd.frame);\n return;\n }\n return Promise.all(\n selected.map(async ({ ws, client }) => {\n let allowed = false;\n try {\n allowed = (await this.deliveryAuthorizer!(client)) === true;\n } catch {\n allowed = false;\n }\n if (allowed) client.sendRaw(cmd.frame);\n else this.reject(ws, 'delivery authorization revoked');\n }),\n ).then(() => undefined);\n }\n\n private collectRooms(rooms: string[]): WsLike[] {\n const set = new Set<WsLike>();\n for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);\n return [...set];\n }\n\n private socketsForRoom(room: string): WsLike[] {\n // Membership is the attachment's `rooms`, NOT the hibernation tag: tags are\n // immutable after acceptWebSocket, so a socket that left its hub room still\n // carries the tag. Since one DO ≈ one room, scanning all sockets in the DO\n // and filtering by attachment is both correct and cheap.\n return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));\n }\n\n private attachmentOf(ws: WsLike): WsAttachment {\n return socketAttachment(ws) ?? rejectedAttachment();\n }\n\n /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */\n clientFor(ws: WsLike): CfWsClient {\n this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n let gate = this.#sendGates.get(ws);\n if (!gate) {\n gate = new WebSocketSendGate(this.#sendPolicyForPath?.(this.attachmentOf(ws).path));\n this.#sendGates.set(ws, gate);\n }\n return new CfWsClient(this.ctx, ws, gate);\n }\n\n private reconcileFrameLimit(ws: WsLike, attachment: WsAttachment): WsAttachment {\n const expected = this.frameLimitForPath?.(attachment.path);\n if (expected !== undefined && attachment.maxFrameBytes !== expected) {\n attachment.maxFrameBytes = expected;\n ws.serializeAttachment(attachment);\n }\n return attachment;\n }\n\n private reject(ws: WsLike, reason: string): void {\n try {\n const attachment = this.attachmentOf(ws);\n attachment.state = 'rejected';\n ws.serializeAttachment(attachment);\n ws.close(1008, reason);\n } catch {\n // already closed or malformed attachment\n }\n }\n}\n","import { socketAttachment } from './ws-attachment';\nimport { WsMessageQueue, assertBroadcastCommandFits } from '@velajs/vela/websocket';\nimport type { BroadcastCommand, WsDispatcher } from '@velajs/vela/websocket';\nimport type { CfRoomRegistry } from './cf-room-registry';\nimport {\n MAX_WS_ATTACHMENT_BYTES,\n type DoStateLike,\n type WsAttachment,\n type WsLike,\n} from './do-state';\nimport { connTag, roomTag } from './room-id';\n\nexport interface WsConnectionPrincipal {\n issuer: string;\n subject: string;\n principalType: 'user' | 'service';\n tenantId: string;\n}\n\n/**\n * The socket lifecycle inside a WebSocket Durable Object, decoupled from the\n * `cloudflare:workers` base class so it is unit-testable with fakes. The thin\n * `VelaWebSocketDurableObject` shell forwards its hibernation callbacks here.\n */\nexport class DoWebSocketHost {\n readonly #messages = new WeakMap<WsLike, WsMessageQueue>();\n constructor(\n private readonly ctx: DoStateLike,\n private readonly dispatcher: WsDispatcher,\n private readonly registry: CfRoomRegistry,\n private readonly gatewayPaths: readonly string[] = [],\n ) {}\n\n /** The single registered gateway's path — a fallback when the Worker didn't forward `x-vela-path`. */\n defaultPath(): string | undefined {\n return this.gatewayPaths[0];\n }\n\n /**\n * Accept a hibernatable socket: tag it with its hub room + connection id,\n * persist the attachment, then await `OnGatewayConnection` before the caller\n * returns 101. A rejected lifecycle hook closes and fails the upgrade.\n */\n async accept(\n ws: WsLike,\n path: string,\n roomId: string,\n userId?: string,\n expiresAtMs?: number,\n principal?: WsConnectionPrincipal,\n ): Promise<boolean> {\n const maxFrameBytes = this.dispatcher.getGatewayMaxFrameBytes(path);\n if (maxFrameBytes === undefined) return false;\n if (\n expiresAtMs !== undefined &&\n (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= Date.now())\n ) {\n return false;\n }\n if (\n (principal !== undefined &&\n (expiresAtMs === undefined ||\n userId !== principal.subject ||\n !principal.issuer ||\n !principal.tenantId)) ||\n (expiresAtMs !== undefined && principal === undefined)\n ) {\n return false;\n }\n\n const connId = crypto.randomUUID();\n const attachment: WsAttachment = {\n version: 1,\n connId,\n state: 'pending',\n userId,\n principal:\n principal === undefined\n ? undefined\n : {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal?.tenantId,\n expiresAtMs,\n path,\n maxFrameBytes,\n rooms: [roomId],\n data: {\n ...(userId ? { userId } : {}),\n ...(principal\n ? {\n principal: {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal.tenantId,\n }\n : {}),\n ...(expiresAtMs !== undefined ? { expiresAtMs } : {}),\n },\n };\n if (new TextEncoder().encode(JSON.stringify(attachment)).byteLength > MAX_WS_ATTACHMENT_BYTES) {\n return false;\n }\n try {\n this.ctx.acceptWebSocket(ws, [roomTag(roomId), connTag(connId)]);\n ws.serializeAttachment(attachment);\n } catch {\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n\n const client = this.registry.clientFor(ws);\n try {\n await this.dispatcher.handleOpen(path, client);\n // Another callback may have rejected the socket while the asynchronous\n // connection hook was still pending. Never resurrect that terminal state\n // after the hook resolves.\n if (!this.transition(ws, 'active', 'pending')) {\n throw new Error('Unable to persist authorized WebSocket state');\n }\n return true;\n } catch (err) {\n await this.dispatcher.handleError(path, client, err).catch(() => {});\n this.transition(ws, 'rejected');\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n }\n\n async onMessage(ws: WsLike, message: string | ArrayBuffer): Promise<void> {\n if (!this.isActive(ws)) {\n this.reject(ws, 'Connection is not authorized');\n return;\n }\n let queue = this.#messages.get(ws);\n if (!queue) {\n const path = socketAttachment(ws)?.path;\n const options = this.dispatcher.collectEntrypoints().find((entry) => entry.meta.path === path)\n ?.meta.options;\n queue = new WsMessageQueue(\n () => this.reject(ws, 'WebSocket message budget exceeded', 1013),\n options?.maxPendingMessages,\n options?.maxPendingBytes,\n );\n this.#messages.set(ws, queue);\n }\n await queue.run(message, async () => {\n if (!this.isActive(ws)) return;\n const client = this.registry.clientFor(ws);\n await this.dispatcher.dispatchMessage(client.path, client, message);\n });\n }\n\n async onClose(ws: WsLike, code: number, reason: string): Promise<void> {\n this.#messages.get(ws)?.stop();\n if (!this.isActive(ws, false)) {\n this.transition(ws, 'rejected');\n try {\n ws.close();\n } catch {\n // already closed\n }\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleClose(client.path, client, code, reason);\n // Complete the closing handshake. Only 1000 and 3000-4999 are valid for\n // close(); reserved/abnormal codes (1005/1006/1015, etc.) throw a RangeError,\n // so fall back to a codeless close on those.\n try {\n if (code === 1000 || (code >= 3000 && code <= 4999)) ws.close(code, reason);\n else ws.close();\n } catch {\n // socket already closed\n }\n }\n\n async onError(ws: WsLike, err: unknown): Promise<void> {\n if (!this.isActive(ws, false)) {\n this.reject(ws, 'Connection failed before authorization');\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleError(client.path, client, err);\n }\n\n /** Deliver a broadcast command to this DO's local sockets (RPC entry point). */\n broadcast(cmd: BroadcastCommand): void | Promise<void> {\n assertBroadcastCommandFits(cmd, this.dispatcher.getMaximumGatewayFrameBytes());\n return this.registry.deliverLocal(cmd);\n }\n\n private transition(\n ws: WsLike,\n state: WsAttachment['state'],\n expectedState?: WsAttachment['state'],\n ): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment) return false;\n if (expectedState !== undefined && attachment.state !== expectedState) return false;\n attachment.state = state;\n ws.serializeAttachment(attachment);\n return true;\n } catch {\n return false;\n }\n }\n\n private isActive(ws: WsLike, checkExpiry = true): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment || attachment.state !== 'active') return false;\n return (\n !checkExpiry ||\n attachment.expiresAtMs === undefined ||\n (Number.isSafeInteger(attachment.expiresAtMs) && attachment.expiresAtMs > Date.now())\n );\n } catch {\n return false;\n }\n }\n\n private reject(ws: WsLike, reason: string, code = 1008): void {\n this.#messages.get(ws)?.stop();\n this.transition(ws, 'rejected');\n try {\n ws.close(code, reason);\n } catch {\n // already closed\n }\n }\n}\n","import { bootstrap, VelaApplication } from '@velajs/vela';\nimport type { InjectionToken, Type } from '@velajs/vela';\nimport {\n local,\n readWsEntrypointMeta,\n WsDispatcher,\n WsServerImpl,\n WS_SERVER,\n} from '@velajs/vela/websocket';\nimport type { WsServer } from '@velajs/vela/websocket';\nimport type { LiveEngine } from '@velajs/vela/live';\nimport { registerCloudflareEnvironment } from '../environment';\nimport { CfWsClient } from './cf-ws-client';\nimport { CfRoomRegistry } from './cf-room-registry';\nimport { initDoLive, initializeDoLiveResources } from './do-live';\nimport type { DoStateLike } from './do-state';\nimport { WsServerHolder } from './ws-server-holder';\n\nexport interface DoRuntime {\n dispatcher: WsDispatcher;\n registry: CfRoomRegistry;\n server: WsServer;\n /** Gateway paths from `app.entrypoints.ofKind('websocket')` (discovery order). */\n gatewayPaths: string[];\n /** The live-query engine (undefined when the app doesn't import LiveModule). */\n live?: LiveEngine;\n close(signal?: string): Promise<void>;\n}\n\n/**\n * Slim DI bootstrap for the Durable Object isolate: wires the container and runs\n * `OnModuleInit`/`OnApplicationBootstrap` (so `WsDispatcher` discovers gateways)\n * WITHOUT building the Hono app/routes the DO never serves. Cloudflare binding\n * refs are initialized straight from the DO's `env`, and the ctx-backed server\n * is bound before bootstrap lifecycle so gateway `afterInit`/handlers see it.\n */\nexport async function buildDoRuntime<T extends object>(\n rootModule: Type,\n ctx: DoStateLike,\n options: { env: T; envToken: InjectionToken<T> },\n): Promise<DoRuntime> {\n const { container, routeManager, loader } = await bootstrap(rootModule, {\n configureContainer: (container) => {\n registerCloudflareEnvironment(container, { token: options.envToken, env: options.env });\n },\n });\n\n const registry = new CfRoomRegistry(ctx);\n const driver = local();\n driver.bind(registry);\n const server = new WsServerImpl(driver);\n\n if (container.has(WS_SERVER)) {\n const holder = await container.resolveAsync(WS_SERVER);\n if (holder instanceof WsServerHolder) holder.setTarget(server);\n }\n\n const app = new VelaApplication(container, routeManager);\n app.setInstances(await loader.resolveAllInstances());\n initializeDoLiveResources(container, ctx);\n await app.callOnModuleInit();\n await app.callOnApplicationBootstrap();\n\n // The entrypoint registry is the transport contract: one 'websocket' entry\n // per discovered gateway ({ meta: { path, dispatcher } }). Built by\n // callOnApplicationBootstrap(), so this slim no-routes path has it too.\n const wsEntrypoints = app.entrypoints.ofKind('websocket', readWsEntrypointMeta);\n const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? app.get(WsDispatcher);\n registry.setSendPolicyResolver(\n (path) => wsEntrypoints.find((entry) => entry.meta.path === path)?.meta.options.sendPolicy,\n );\n registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));\n registry.setDeliveryAuthorizer((client) => {\n const path = client instanceof CfWsClient ? client.path : '';\n return dispatcher.authorizeDelivery(path, client);\n });\n\n // Live queries: wire the SQLite cursor log + local driver mode and replay\n // hibernation-persisted subscriptions into the fresh engine.\n const live = initDoLive(app, ctx, registry);\n\n return {\n // Zero gateways still yields a live dispatcher (module imported, nothing\n // decorated) — fall back to resolving it directly.\n dispatcher,\n registry,\n server,\n gatewayPaths: wsEntrypoints.map((ep) => ep.meta.path),\n live,\n close: (signal?: string) => app.close(signal),\n };\n}\n","import { DurableObject } from 'cloudflare:workers';\nimport type { InjectionToken } from '@velajs/vela';\nimport type { BroadcastCommand } from '@velajs/vela/websocket';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveEngine,\n LiveInspection,\n} from '@velajs/vela/live';\nimport { buildDoRuntime } from './do-bootstrap';\nimport { DoWebSocketHost, type WsConnectionPrincipal } from './do-websocket-host';\nimport { armDoPitr, readDoPitrBookmark } from './do-pitr';\nimport { resolveCloudflareRoot } from '../root-module';\nimport type { CloudflareRoot } from '../root-module';\nimport type {\n DoPitrArmOptions,\n DoPitrArmResult,\n DoPitrBookmarkRead,\n VelaDoPitrRpc,\n} from './do-pitr';\n\nconst PING = '{\"event\":\"$ping\"}';\nconst PONG = '{\"event\":\"$pong\"}';\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\nfunction isIdentityField(value: string | null): value is string {\n return (\n value !== null &&\n value.length > 0 &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/**\n * Base class for the WebSocket Durable Object. The user exports a named subclass\n * (matching their `wrangler.toml` `class_name`) built from their `AppModule`:\n *\n * ```ts\n * export class ChatRoom extends VelaWebSocketDurableObject(AppModule, { envToken: ENV }) {}\n * ```\n *\n * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot\n * bridge DO hibernation) and forwards every event into the runtime-agnostic\n * `WsDispatcher` via {@link DoWebSocketHost}.\n */\nexport function VelaWebSocketDurableObject<T extends object>(\n rootModule: CloudflareRoot<NoInfer<T>>,\n options: { envToken: InjectionToken<T> },\n): new (\n ctx: DurableObjectState,\n env: T,\n) => DurableObject<T> &\n VelaDoPitrRpc & {\n broadcast(cmd: BroadcastCommand): Promise<void>;\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n inspectLive(): Promise<LiveInspection>;\n } {\n return class VelaWsDurableObject extends DurableObject<T> {\n private host!: DoWebSocketHost;\n private liveEngine?: LiveEngine;\n private readonly ready: Promise<void>;\n\n constructor(ctx: DurableObjectState, env: T) {\n super(ctx, env);\n // Application-level ping/pong answered WITHOUT waking a hibernated DO.\n try {\n ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));\n } catch {\n // Older runtimes without auto-response — fine, protocol pings still work.\n }\n this.ready = ctx.blockConcurrencyWhile(async () => {\n const runtime = await buildDoRuntime(await resolveCloudflareRoot(rootModule, env), ctx, {\n ...options,\n env,\n });\n this.host = new DoWebSocketHost(\n ctx,\n runtime.dispatcher,\n runtime.registry,\n runtime.gatewayPaths,\n );\n this.liveEngine = runtime.live;\n });\n }\n\n /** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */\n async inspectLive(): Promise<LiveInspection> {\n await this.ready;\n return this.liveEngine?.inspect() ?? { subscriptions: [], rooms: [] };\n }\n\n override async fetch(request: Request): Promise<Response> {\n await this.ready;\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected WebSocket upgrade', { status: 426 });\n }\n\n const url = new URL(request.url);\n // Headers are primary (carry auth + multi-gateway routing); fall back to the\n // DO's own name (set via idFromName(room)) and the single gateway path so a\n // plain `stub.fetch(request)` forward still works.\n const roomId = request.headers.get('x-vela-room') ?? this.ctx.id.name ?? url.pathname;\n const path = request.headers.get('x-vela-path') ?? this.host.defaultPath() ?? url.pathname;\n const userId = request.headers.get('x-vela-user') || undefined;\n const rawExpiresAtMs = request.headers.get('x-vela-expires-at-ms');\n const parsedExpiresAtMs = rawExpiresAtMs === null ? undefined : Number(rawExpiresAtMs);\n if (\n parsedExpiresAtMs !== undefined &&\n (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)\n ) {\n return new Response('Invalid WebSocket identity expiry', { status: 403 });\n }\n\n const issuer = request.headers.get('x-vela-issuer');\n const subject = request.headers.get('x-vela-subject');\n const principalType = request.headers.get('x-vela-principal-type');\n const tenantId = request.headers.get('x-vela-tenant');\n const hasPrincipalHeader =\n issuer !== null || subject !== null || principalType !== null || tenantId !== null;\n let principal: WsConnectionPrincipal | undefined;\n if (hasPrincipalHeader) {\n if (\n !isIdentityField(issuer) ||\n !isIdentityField(subject) ||\n (principalType !== 'user' && principalType !== 'service') ||\n !isIdentityField(tenantId) ||\n parsedExpiresAtMs === undefined ||\n (userId !== undefined && userId !== subject)\n ) {\n return new Response('Invalid WebSocket principal', { status: 403 });\n }\n principal = { issuer, subject, principalType, tenantId };\n } else if (parsedExpiresAtMs !== undefined) {\n return new Response('WebSocket identity tuple is missing', { status: 403 });\n }\n\n if (parsedExpiresAtMs !== undefined && parsedExpiresAtMs <= Date.now()) {\n return new Response('WebSocket identity expired', { status: 403 });\n }\n\n const { 0: client, 1: server } = new WebSocketPair();\n const accepted = await this.host.accept(\n server,\n path,\n roomId,\n userId,\n parsedExpiresAtMs,\n principal,\n );\n if (!accepted) return new Response('WebSocket connection rejected', { status: 403 });\n return new Response(null, { status: 101, webSocket: client });\n }\n\n override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {\n await this.ready;\n await this.host.onMessage(ws, message);\n }\n\n override async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {\n await this.ready;\n await this.host.onClose(ws, code, reason);\n }\n\n override async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n await this.ready;\n await this.host.onError(ws, error);\n }\n\n /** DO RPC — server-initiated broadcast forwarded from a Worker (see `broadcastToRoom`). */\n async broadcast(cmd: BroadcastCommand): Promise<void> {\n await this.ready;\n await this.host.broadcast(cmd);\n }\n\n /**\n * DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /\n * liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns\n * the commit stamp (what `Vela-Commit-Cursor` carries); the subscription\n * refreshes fan out asynchronously.\n */\n async invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined> {\n await this.ready;\n return this.liveEngine?.applyInvalidation(cmd);\n }\n\n // -- Durable Object PITR (point-in-time recovery) RPC ---------------------\n //\n // GUARD / reachability: these are admin-privileged operations (a restore can\n // roll the DO's SQLite state back up to 30 days and, with `restart`, abort\n // the DO to apply it now). They are safe to expose here because a Durable\n // Object's RPC methods are NOT network-reachable: a `DurableObjectStub` is\n // obtainable ONLY from a Worker that binds this DO namespace, and RPC calls\n // travel Cloudflare's internal capability channel — never the public\n // internet. A WebSocket/HTTP client reaches only `fetch()` above, never these\n // methods. The security boundary is therefore the WORKER-SIDE studio admin\n // gate that fronts the `CloudflareDoTimeTravelPort` (master admin token + the\n // 428 confirm challenge) — the identical trust model as `broadcast()` /\n // `invalidate()` on this same DO. See `do-pitr.ts` for the storage wrappers.\n\n /** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */\n async pitrCurrentBookmark(): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage);\n }\n\n /** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */\n async pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage, time);\n }\n\n /**\n * DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is\n * requested, `ctx.abort()` is called AFTER the undo bookmark is computed so\n * the recovery applies on the immediately-following session; otherwise the\n * restore applies on the next natural restart (`restarted: false`).\n */\n async pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult> {\n await this.ready;\n const result = await armDoPitr(this.ctx.storage, opts);\n if (opts.restart === true) this.ctx.abort('vela PITR restore');\n return result;\n }\n };\n}\n","import { DurableObject } from 'cloudflare:workers';\nimport { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from './nonce-validation';\nconst EXPIRED_DELETE_BATCH = 1_024;\n\nconst CREATE_TABLE =\n 'CREATE TABLE IF NOT EXISTS __vela_nonce_claims (' +\n 'nonce TEXT PRIMARY KEY NOT NULL, ' +\n 'expires_at INTEGER NOT NULL CHECK (expires_at > 0)' +\n ') WITHOUT ROWID';\nconst CREATE_EXPIRY_INDEX =\n 'CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)';\nconst DELETE_EXPIRED =\n 'DELETE FROM __vela_nonce_claims WHERE nonce IN (' +\n 'SELECT nonce FROM __vela_nonce_claims ' +\n 'WHERE expires_at < ? ORDER BY expires_at LIMIT ?' +\n ')';\nconst INSERT_CLAIM =\n 'INSERT INTO __vela_nonce_claims (nonce, expires_at) VALUES (?, ?) ' +\n 'ON CONFLICT(nonce) DO NOTHING RETURNING nonce, expires_at';\n\ninterface NonceSqlCursor {\n toArray(): Record<string, unknown>[];\n}\n\ninterface NonceSqlStorage {\n exec(query: string, ...bindings: unknown[]): NonceSqlCursor;\n}\n\n/**\n * SQLite Durable Object that atomically consumes nonces.\n *\n * Export this class from the Worker entry and register it through a Wrangler\n * `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`\n * is the single-use decision; all SQL runs synchronously before the RPC method\n * yields, and the nonce primary key is the final concurrency boundary.\n */\nexport class VelaNonceDurableObject extends DurableObject<Record<string, unknown>> {\n private sql?: NonceSqlStorage;\n\n constructor(ctx: DurableObjectState, env: Record<string, unknown>) {\n super(ctx, env);\n try {\n const sql = ctx.storage?.sql;\n if (!sql || typeof sql.exec !== 'function') return;\n sql.exec(CREATE_TABLE);\n sql.exec(CREATE_EXPIRY_INDEX);\n this.sql = sql;\n } catch {\n // A non-SQLite/misconfigured class stays fail-closed: every claim denies.\n this.sql = undefined;\n }\n }\n\n async claim(nonce: string, expEpochSeconds: number): Promise<boolean> {\n const sql = this.sql;\n if (!sql) return false;\n\n const now = Math.floor(Date.now() / 1_000);\n if (!isCanonicalBoundedText(nonce, MAX_NONCE_BYTES) || !isValidExpiry(expEpochSeconds, now)) {\n return false;\n }\n\n try {\n // Keep cleanup bounded so one claim cannot monopolize the DO. Entries at\n // exactly `now` remain: Vela's invocation verifier accepts `now === exp`.\n sql.exec(DELETE_EXPIRED, now, EXPIRED_DELETE_BATCH);\n\n const cursor = sql.exec(INSERT_CLAIM, nonce, expEpochSeconds);\n if (!cursor || typeof cursor.toArray !== 'function') return false;\n const rows: unknown = cursor.toArray();\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n\n const row: unknown = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n if (\n !Object.hasOwn(row, 'nonce') ||\n !Object.hasOwn(row, 'expires_at') ||\n !('nonce' in row) ||\n !('expires_at' in row)\n ) {\n return false;\n }\n return row.nonce === nonce && row.expires_at === expEpochSeconds;\n } catch {\n return false;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,IA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AAQ,YAAY,QAAQ,MAAM,OAAO;GACpD,IACE,CAAC,OAAO,OAAO,KAAK,OAAO,KAC3B,CAAC,OAAO,OAAO,KAAK,YAAY,KAChC,EAAE,WAAW,QACb,EAAE,gBAAgB,MAElB,OAAO;GAET,OAAO,IAAI,UAAU,SAAS,IAAI,eAAe;EACnD,QAAQ;GACN,OAAO;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"durable-objects.js","names":[],"sources":["../src/websocket/cf-room-registry.ts","../src/websocket/do-websocket-host.ts","../src/websocket/do-bootstrap.ts","../src/websocket/websocket.durable-object.ts","../src/nonce/nonce.durable-object.ts"],"sourcesContent":["import { WebSocketSendGate, type WebSocketSendPolicy } from '@velajs/vela/websocket';\nimport { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n readonly #sendGates = new WeakMap<WsLike, WebSocketSendGate>();\n // Sockets whose OnGatewayConnection hook is running in this instance. They\n // are still `pending`, so broadcasts skip them; any other pending socket\n // never finished admission and is closed when a broadcast reaches it.\n readonly #admitting = new WeakSet<WsLike>();\n #sendPolicyForPath?: (path: string) => WebSocketSendPolicy | undefined;\n\n setSendPolicyResolver(resolve: (path: string) => WebSocketSendPolicy | undefined): void {\n this.#sendPolicyForPath = resolve;\n }\n\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n /**\n * Run `admit` (the connection hook) with `ws` marked as being admitted, so a\n * broadcast issued meanwhile (for example `server.emit()` announcing the new\n * connection) skips the still-pending socket instead of rejecting it.\n */\n async admitting<T>(ws: WsLike, admit: () => Promise<T>): Promise<T> {\n this.#admitting.add(ws);\n try {\n return await admit();\n } finally {\n this.#admitting.delete(ws);\n }\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const att = this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n // A socket still in its connection hook is not admitted yet: it receives no\n // room frames, and its own accept() settles it. Rejecting it here would\n // close every client whose handleConnection broadcasts to the room. Other\n // pending sockets fall through and are rejected below.\n if (att.state === 'pending' && this.#admitting.has(ws)) continue;\n if (\n att.state !== 'active' ||\n (att.expiresAtMs !== undefined &&\n (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now()))\n ) {\n try {\n att.state = 'rejected';\n ws.serializeAttachment(att);\n ws.close(1008, 'identity expired or connection rejected');\n } catch {\n // already closed or malformed attachment\n }\n continue;\n }\n if (seen.has(att.connId)) continue;\n seen.add(att.connId);\n if (excludeIds.has(att.connId)) continue;\n if (excludeRooms.some((r) => att.rooms.includes(r))) continue;\n selected.push({ ws, client: this.clientFor(ws) });\n }\n\n if (!this.deliveryAuthorizer) {\n for (const { client } of selected) client.sendRaw(cmd.frame);\n return;\n }\n return Promise.all(\n selected.map(async ({ ws, client }) => {\n let allowed = false;\n try {\n allowed = (await this.deliveryAuthorizer!(client)) === true;\n } catch {\n allowed = false;\n }\n if (allowed) client.sendRaw(cmd.frame);\n else this.reject(ws, 'delivery authorization revoked');\n }),\n ).then(() => undefined);\n }\n\n private collectRooms(rooms: string[]): WsLike[] {\n const set = new Set<WsLike>();\n for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);\n return [...set];\n }\n\n private socketsForRoom(room: string): WsLike[] {\n // Membership is the attachment's `rooms`, NOT the hibernation tag: tags are\n // immutable after acceptWebSocket, so a socket that left its hub room still\n // carries the tag. Since one DO ≈ one room, scanning all sockets in the DO\n // and filtering by attachment is both correct and cheap.\n return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));\n }\n\n private attachmentOf(ws: WsLike): WsAttachment {\n return socketAttachment(ws) ?? rejectedAttachment();\n }\n\n /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */\n clientFor(ws: WsLike): CfWsClient {\n this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n let gate = this.#sendGates.get(ws);\n if (!gate) {\n gate = new WebSocketSendGate(this.#sendPolicyForPath?.(this.attachmentOf(ws).path));\n this.#sendGates.set(ws, gate);\n }\n return new CfWsClient(this.ctx, ws, gate);\n }\n\n private reconcileFrameLimit(ws: WsLike, attachment: WsAttachment): WsAttachment {\n const expected = this.frameLimitForPath?.(attachment.path);\n if (expected !== undefined && attachment.maxFrameBytes !== expected) {\n attachment.maxFrameBytes = expected;\n ws.serializeAttachment(attachment);\n }\n return attachment;\n }\n\n private reject(ws: WsLike, reason: string): void {\n try {\n const attachment = this.attachmentOf(ws);\n attachment.state = 'rejected';\n ws.serializeAttachment(attachment);\n ws.close(1008, reason);\n } catch {\n // already closed or malformed attachment\n }\n }\n}\n","import { socketAttachment } from './ws-attachment';\nimport { WsMessageQueue, assertBroadcastCommandFits } from '@velajs/vela/websocket';\nimport type { BroadcastCommand, WsDispatcher } from '@velajs/vela/websocket';\nimport type { CfRoomRegistry } from './cf-room-registry';\nimport {\n MAX_WS_ATTACHMENT_BYTES,\n type DoStateLike,\n type WsAttachment,\n type WsLike,\n} from './do-state';\nimport { connTag, roomTag } from './room-id';\n\nexport interface WsConnectionPrincipal {\n issuer: string;\n subject: string;\n principalType: 'user' | 'service';\n tenantId: string;\n}\n\n/**\n * The socket lifecycle inside a WebSocket Durable Object, decoupled from the\n * `cloudflare:workers` base class so it is unit-testable with fakes. The thin\n * `VelaWebSocketDurableObject` shell forwards its hibernation callbacks here.\n */\nexport class DoWebSocketHost {\n readonly #messages = new WeakMap<WsLike, WsMessageQueue>();\n constructor(\n private readonly ctx: DoStateLike,\n private readonly dispatcher: WsDispatcher,\n private readonly registry: CfRoomRegistry,\n private readonly gatewayPaths: readonly string[] = [],\n ) {}\n\n /** The single registered gateway's path — a fallback when the Worker didn't forward `x-vela-path`. */\n defaultPath(): string | undefined {\n return this.gatewayPaths[0];\n }\n\n /**\n * Accept a hibernatable socket: tag it with its hub room + connection id,\n * persist the attachment, then await `OnGatewayConnection` before the caller\n * returns 101. A rejected lifecycle hook closes and fails the upgrade.\n */\n async accept(\n ws: WsLike,\n path: string,\n roomId: string,\n userId?: string,\n expiresAtMs?: number,\n principal?: WsConnectionPrincipal,\n ): Promise<boolean> {\n const maxFrameBytes = this.dispatcher.getGatewayMaxFrameBytes(path);\n if (maxFrameBytes === undefined) return false;\n if (\n expiresAtMs !== undefined &&\n (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= Date.now())\n ) {\n return false;\n }\n if (\n (principal !== undefined &&\n (expiresAtMs === undefined ||\n userId !== principal.subject ||\n !principal.issuer ||\n !principal.tenantId)) ||\n (expiresAtMs !== undefined && principal === undefined)\n ) {\n return false;\n }\n\n const connId = crypto.randomUUID();\n const attachment: WsAttachment = {\n version: 1,\n connId,\n state: 'pending',\n userId,\n principal:\n principal === undefined\n ? undefined\n : {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal?.tenantId,\n expiresAtMs,\n path,\n maxFrameBytes,\n rooms: [roomId],\n data: {\n ...(userId ? { userId } : {}),\n ...(principal\n ? {\n principal: {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal.tenantId,\n }\n : {}),\n ...(expiresAtMs !== undefined ? { expiresAtMs } : {}),\n },\n };\n if (new TextEncoder().encode(JSON.stringify(attachment)).byteLength > MAX_WS_ATTACHMENT_BYTES) {\n return false;\n }\n try {\n this.ctx.acceptWebSocket(ws, [roomTag(roomId), connTag(connId)]);\n ws.serializeAttachment(attachment);\n } catch {\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n\n const client = this.registry.clientFor(ws);\n try {\n // Broadcasts the hook issues skip this still-pending socket.\n await this.registry.admitting(ws, () => this.dispatcher.handleOpen(path, client));\n // Another callback may have rejected the socket while the asynchronous\n // connection hook was still pending. Never resurrect that terminal state\n // after the hook resolves.\n if (!this.transition(ws, 'active', 'pending')) {\n throw new Error(\n socketAttachment(ws)?.state === 'rejected'\n ? 'WebSocket was rejected while OnGatewayConnection was running: a frame ' +\n 'arrived before the connection hook completed, or the connection closed or failed'\n : 'Unable to persist authorized WebSocket state',\n );\n }\n return true;\n } catch (err) {\n await this.dispatcher.handleError(path, client, err).catch(() => {});\n this.transition(ws, 'rejected');\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n }\n\n async onMessage(ws: WsLike, message: string | ArrayBuffer): Promise<void> {\n if (!this.isActive(ws)) {\n this.reject(ws, 'Connection is not authorized');\n return;\n }\n let queue = this.#messages.get(ws);\n if (!queue) {\n const path = socketAttachment(ws)?.path;\n const options = this.dispatcher.collectEntrypoints().find((entry) => entry.meta.path === path)\n ?.meta.options;\n queue = new WsMessageQueue(\n () => this.reject(ws, 'WebSocket message budget exceeded', 1013),\n options?.maxPendingMessages,\n options?.maxPendingBytes,\n );\n this.#messages.set(ws, queue);\n }\n await queue.run(message, async () => {\n if (!this.isActive(ws)) return;\n const client = this.registry.clientFor(ws);\n await this.dispatcher.dispatchMessage(client.path, client, message);\n });\n }\n\n async onClose(ws: WsLike, code: number, reason: string): Promise<void> {\n this.#messages.get(ws)?.stop();\n if (!this.isActive(ws, false)) {\n this.transition(ws, 'rejected');\n try {\n ws.close();\n } catch {\n // already closed\n }\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleClose(client.path, client, code, reason);\n // Complete the closing handshake. Only 1000 and 3000-4999 are valid for\n // close(); reserved/abnormal codes (1005/1006/1015, etc.) throw a RangeError,\n // so fall back to a codeless close on those.\n try {\n if (code === 1000 || (code >= 3000 && code <= 4999)) ws.close(code, reason);\n else ws.close();\n } catch {\n // socket already closed\n }\n }\n\n async onError(ws: WsLike, err: unknown): Promise<void> {\n if (!this.isActive(ws, false)) {\n this.reject(ws, 'Connection failed before authorization');\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleError(client.path, client, err);\n }\n\n /** Deliver a broadcast command to this DO's local sockets (RPC entry point). */\n broadcast(cmd: BroadcastCommand): void | Promise<void> {\n assertBroadcastCommandFits(cmd, this.dispatcher.getMaximumGatewayFrameBytes());\n return this.registry.deliverLocal(cmd);\n }\n\n private transition(\n ws: WsLike,\n state: WsAttachment['state'],\n expectedState?: WsAttachment['state'],\n ): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment) return false;\n if (expectedState !== undefined && attachment.state !== expectedState) return false;\n attachment.state = state;\n ws.serializeAttachment(attachment);\n return true;\n } catch {\n return false;\n }\n }\n\n private isActive(ws: WsLike, checkExpiry = true): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment || attachment.state !== 'active') return false;\n return (\n !checkExpiry ||\n attachment.expiresAtMs === undefined ||\n (Number.isSafeInteger(attachment.expiresAtMs) && attachment.expiresAtMs > Date.now())\n );\n } catch {\n return false;\n }\n }\n\n private reject(ws: WsLike, reason: string, code = 1008): void {\n this.#messages.get(ws)?.stop();\n this.transition(ws, 'rejected');\n try {\n ws.close(code, reason);\n } catch {\n // already closed\n }\n }\n}\n","import { bootstrap, VelaApplication } from '@velajs/vela';\nimport type { DynamicModule, Type, VelaEnv } from '@velajs/vela';\nimport {\n local,\n readWsEntrypointMeta,\n WsDispatcher,\n WsServerImpl,\n WS_SERVER,\n} from '@velajs/vela/websocket';\nimport type { WsServer } from '@velajs/vela/websocket';\nimport type { LiveEngine } from '@velajs/vela/live';\nimport { registerCloudflareEnvironment } from '../environment';\nimport { CfWsClient } from './cf-ws-client';\nimport { CfRoomRegistry } from './cf-room-registry';\nimport { initDoLive, initializeDoLiveResources } from './do-live';\nimport type { DoStateLike } from './do-state';\nimport { WsServerHolder } from './ws-server-holder';\n\nexport interface DoRuntime {\n dispatcher: WsDispatcher;\n registry: CfRoomRegistry;\n server: WsServer;\n /** Gateway paths from `app.entrypoints.ofKind('websocket')` (discovery order). */\n gatewayPaths: string[];\n /** The live-query engine (undefined when the app doesn't import LiveModule). */\n live?: LiveEngine;\n close(signal?: string): Promise<void>;\n}\n\n/**\n * Slim DI bootstrap for the Durable Object isolate: wires the container and runs\n * `OnModuleInit`/`OnApplicationBootstrap` (so `WsDispatcher` discovers gateways)\n * WITHOUT building the Hono app/routes the DO never serves. The DO's `env` is\n * seeded as the global ENV before providers construct, and the ctx-backed server\n * is bound before bootstrap lifecycle so gateway `afterInit`/handlers see it.\n */\nexport async function buildDoRuntime(\n rootModule: Type | DynamicModule,\n ctx: DoStateLike,\n options: { env: VelaEnv },\n): Promise<DoRuntime> {\n const { container, routeManager, loader } = await bootstrap(rootModule, {\n configureContainer: (container) => {\n registerCloudflareEnvironment(container, options.env);\n },\n });\n\n const registry = new CfRoomRegistry(ctx);\n const driver = local();\n driver.bind(registry);\n const server = new WsServerImpl(driver);\n\n if (container.has(WS_SERVER)) {\n const holder = await container.resolveAsync(WS_SERVER);\n // The core WebSocketModule's server broadcasts through its own sync driver,\n // which never reaches this Durable Object's hibernatable sockets.\n if (!(holder instanceof WsServerHolder)) {\n throw new Error(\n '[vela] The WebSocket Durable Object found a WS_SERVER from the core WebSocketModule, ' +\n 'which cannot reach Durable Object sockets. On Cloudflare, import ' +\n 'CloudflareWebSocketModule.forRoot() instead of WebSocketModule.forRoot().',\n );\n }\n holder.setTarget(server);\n }\n\n const app = new VelaApplication(container, routeManager);\n app.setInstances(await loader.resolveAllInstances());\n initializeDoLiveResources(container, ctx);\n await app.callOnModuleInit();\n await app.callOnApplicationBootstrap();\n\n // The entrypoint registry is the transport contract: one 'websocket' entry\n // per discovered gateway ({ meta: { path, dispatcher } }). Built by\n // callOnApplicationBootstrap(), so this slim no-routes path has it too.\n const wsEntrypoints = app.entrypoints.ofKind('websocket', readWsEntrypointMeta);\n const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? app.get(WsDispatcher);\n registry.setSendPolicyResolver(\n (path) => wsEntrypoints.find((entry) => entry.meta.path === path)?.meta.options.sendPolicy,\n );\n registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));\n registry.setDeliveryAuthorizer((client) => {\n const path = client instanceof CfWsClient ? client.path : '';\n return dispatcher.authorizeDelivery(path, client);\n });\n\n // Live queries: wire the SQLite cursor log + local driver mode and replay\n // hibernation-persisted subscriptions into the fresh engine.\n const live = initDoLive(app, ctx, registry);\n\n return {\n // Zero gateways still yields a live dispatcher (module imported, nothing\n // decorated) — fall back to resolving it directly.\n dispatcher,\n registry,\n server,\n gatewayPaths: wsEntrypoints.map((ep) => ep.meta.path),\n live,\n close: (signal?: string) => app.close(signal),\n };\n}\n","import { DurableObject } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport type { BroadcastCommand } from '@velajs/vela/websocket';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveEngine,\n LiveInspection,\n} from '@velajs/vela/live';\nimport { buildDoRuntime } from './do-bootstrap';\nimport { DoWebSocketHost, type WsConnectionPrincipal } from './do-websocket-host';\nimport { armDoPitr, readDoPitrBookmark } from './do-pitr';\nimport type { CloudflareRoot } from '../root-module';\nimport type {\n DoPitrArmOptions,\n DoPitrArmResult,\n DoPitrBookmarkRead,\n VelaDoPitrRpc,\n} from './do-pitr';\n\nconst PING = '{\"event\":\"$ping\"}';\nconst PONG = '{\"event\":\"$pong\"}';\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\nfunction isIdentityField(value: string | null): value is string {\n return (\n value !== null &&\n value.length > 0 &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/**\n * Base class for the WebSocket Durable Object. The user exports a named subclass\n * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, or\n * from a `DynamicModule` declared at module scope:\n *\n * ```ts\n * export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}\n * ```\n *\n * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot\n * bridge DO hibernation) and forwards every event into the runtime-agnostic\n * `WsDispatcher` via {@link DoWebSocketHost}. The DO's `env` is the\n * application's ENV, as in the Worker.\n */\nexport function VelaWebSocketDurableObject(rootModule: CloudflareRoot): new (\n ctx: DurableObjectState,\n env: VelaEnv,\n) => DurableObject<VelaEnv> &\n VelaDoPitrRpc & {\n broadcast(cmd: BroadcastCommand): Promise<void>;\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n inspectLive(): Promise<LiveInspection>;\n } {\n return class VelaWsDurableObject extends DurableObject<VelaEnv> {\n private host!: DoWebSocketHost;\n private liveEngine?: LiveEngine;\n private readonly ready: Promise<void>;\n\n constructor(ctx: DurableObjectState, env: VelaEnv) {\n super(ctx, env);\n // Application-level ping/pong answered WITHOUT waking a hibernated DO.\n try {\n ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));\n } catch {\n // Older runtimes without auto-response — fine, protocol pings still work.\n }\n this.ready = ctx.blockConcurrencyWhile(async () => {\n // The root is static, so constructing another instance declares no new\n // classes in the isolate-global metadata registry.\n const runtime = await buildDoRuntime(rootModule, ctx, { env });\n this.host = new DoWebSocketHost(\n ctx,\n runtime.dispatcher,\n runtime.registry,\n runtime.gatewayPaths,\n );\n this.liveEngine = runtime.live;\n });\n }\n\n /** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */\n async inspectLive(): Promise<LiveInspection> {\n await this.ready;\n return this.liveEngine?.inspect() ?? { subscriptions: [], rooms: [] };\n }\n\n override async fetch(request: Request): Promise<Response> {\n await this.ready;\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected WebSocket upgrade', { status: 426 });\n }\n\n const url = new URL(request.url);\n // Headers are primary (carry auth + multi-gateway routing); fall back to the\n // DO's own name (set via idFromName(room)) and the single gateway path so a\n // plain `stub.fetch(request)` forward still works.\n const roomId = request.headers.get('x-vela-room') ?? this.ctx.id.name ?? url.pathname;\n const path = request.headers.get('x-vela-path') ?? this.host.defaultPath() ?? url.pathname;\n const userId = request.headers.get('x-vela-user') || undefined;\n const rawExpiresAtMs = request.headers.get('x-vela-expires-at-ms');\n const parsedExpiresAtMs = rawExpiresAtMs === null ? undefined : Number(rawExpiresAtMs);\n if (\n parsedExpiresAtMs !== undefined &&\n (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)\n ) {\n return new Response('Invalid WebSocket identity expiry', { status: 403 });\n }\n\n const issuer = request.headers.get('x-vela-issuer');\n const subject = request.headers.get('x-vela-subject');\n const principalType = request.headers.get('x-vela-principal-type');\n const tenantId = request.headers.get('x-vela-tenant');\n const hasPrincipalHeader =\n issuer !== null || subject !== null || principalType !== null || tenantId !== null;\n let principal: WsConnectionPrincipal | undefined;\n if (hasPrincipalHeader) {\n if (\n !isIdentityField(issuer) ||\n !isIdentityField(subject) ||\n (principalType !== 'user' && principalType !== 'service') ||\n !isIdentityField(tenantId) ||\n parsedExpiresAtMs === undefined ||\n (userId !== undefined && userId !== subject)\n ) {\n return new Response('Invalid WebSocket principal', { status: 403 });\n }\n principal = { issuer, subject, principalType, tenantId };\n } else if (parsedExpiresAtMs !== undefined) {\n return new Response('WebSocket identity tuple is missing', { status: 403 });\n }\n\n if (parsedExpiresAtMs !== undefined && parsedExpiresAtMs <= Date.now()) {\n return new Response('WebSocket identity expired', { status: 403 });\n }\n\n const { 0: client, 1: server } = new WebSocketPair();\n const accepted = await this.host.accept(\n server,\n path,\n roomId,\n userId,\n parsedExpiresAtMs,\n principal,\n );\n if (!accepted) return new Response('WebSocket connection rejected', { status: 403 });\n return new Response(null, { status: 101, webSocket: client });\n }\n\n override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {\n await this.ready;\n await this.host.onMessage(ws, message);\n }\n\n override async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {\n await this.ready;\n await this.host.onClose(ws, code, reason);\n }\n\n override async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n await this.ready;\n await this.host.onError(ws, error);\n }\n\n /** DO RPC — server-initiated broadcast forwarded from a Worker (see `broadcastToRoom`). */\n async broadcast(cmd: BroadcastCommand): Promise<void> {\n await this.ready;\n await this.host.broadcast(cmd);\n }\n\n /**\n * DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /\n * liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns\n * the commit stamp (what `Vela-Commit-Cursor` carries); the subscription\n * refreshes fan out asynchronously.\n */\n async invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined> {\n await this.ready;\n return this.liveEngine?.applyInvalidation(cmd);\n }\n\n // -- Durable Object PITR (point-in-time recovery) RPC ---------------------\n //\n // GUARD / reachability: these are admin-privileged operations (a restore can\n // roll the DO's SQLite state back up to 30 days and, with `restart`, abort\n // the DO to apply it now). They are safe to expose here because a Durable\n // Object's RPC methods are NOT network-reachable: a `DurableObjectStub` is\n // obtainable ONLY from a Worker that binds this DO namespace, and RPC calls\n // travel Cloudflare's internal capability channel — never the public\n // internet. A WebSocket/HTTP client reaches only `fetch()` above, never these\n // methods. The security boundary is therefore the WORKER-SIDE studio admin\n // gate that fronts the `CloudflareDoTimeTravelPort` (master admin token + the\n // 428 confirm challenge) — the identical trust model as `broadcast()` /\n // `invalidate()` on this same DO. See `do-pitr.ts` for the storage wrappers.\n\n /** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */\n async pitrCurrentBookmark(): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage);\n }\n\n /** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */\n async pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage, time);\n }\n\n /**\n * DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is\n * requested, `ctx.abort()` is called AFTER the undo bookmark is computed so\n * the recovery applies on the immediately-following session; otherwise the\n * restore applies on the next natural restart (`restarted: false`).\n */\n async pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult> {\n await this.ready;\n const result = await armDoPitr(this.ctx.storage, opts);\n if (opts.restart === true) this.ctx.abort('vela PITR restore');\n return result;\n }\n };\n}\n","import { DurableObject } from 'cloudflare:workers';\nimport { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from './nonce-validation';\nconst EXPIRED_DELETE_BATCH = 1_024;\n\nconst CREATE_TABLE =\n 'CREATE TABLE IF NOT EXISTS __vela_nonce_claims (' +\n 'nonce TEXT PRIMARY KEY NOT NULL, ' +\n 'expires_at INTEGER NOT NULL CHECK (expires_at > 0)' +\n ') WITHOUT ROWID';\nconst CREATE_EXPIRY_INDEX =\n 'CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)';\nconst DELETE_EXPIRED =\n 'DELETE FROM __vela_nonce_claims WHERE nonce IN (' +\n 'SELECT nonce FROM __vela_nonce_claims ' +\n 'WHERE expires_at < ? ORDER BY expires_at LIMIT ?' +\n ')';\nconst INSERT_CLAIM =\n 'INSERT INTO __vela_nonce_claims (nonce, expires_at) VALUES (?, ?) ' +\n 'ON CONFLICT(nonce) DO NOTHING RETURNING nonce, expires_at';\n\ninterface NonceSqlCursor {\n toArray(): Record<string, unknown>[];\n}\n\ninterface NonceSqlStorage {\n exec(query: string, ...bindings: unknown[]): NonceSqlCursor;\n}\n\n/**\n * SQLite Durable Object that atomically consumes nonces.\n *\n * Export this class from the Worker entry and register it through a Wrangler\n * `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`\n * is the single-use decision; all SQL runs synchronously before the RPC method\n * yields, and the nonce primary key is the final concurrency boundary.\n */\nexport class VelaNonceDurableObject extends DurableObject<Record<string, unknown>> {\n private sql?: NonceSqlStorage;\n\n constructor(ctx: DurableObjectState, env: Record<string, unknown>) {\n super(ctx, env);\n try {\n const sql = ctx.storage?.sql;\n if (!sql || typeof sql.exec !== 'function') return;\n sql.exec(CREATE_TABLE);\n sql.exec(CREATE_EXPIRY_INDEX);\n this.sql = sql;\n } catch {\n // A non-SQLite/misconfigured class stays fail-closed: every claim denies.\n this.sql = undefined;\n }\n }\n\n async claim(nonce: string, expEpochSeconds: number): Promise<boolean> {\n const sql = this.sql;\n if (!sql) return false;\n\n const now = Math.floor(Date.now() / 1_000);\n if (!isCanonicalBoundedText(nonce, MAX_NONCE_BYTES) || !isValidExpiry(expEpochSeconds, now)) {\n return false;\n }\n\n try {\n // Keep cleanup bounded so one claim cannot monopolize the DO. Entries at\n // exactly `now` remain: Vela's invocation verifier accepts `now === exp`.\n sql.exec(DELETE_EXPIRED, now, EXPIRED_DELETE_BATCH);\n\n const cursor = sql.exec(INSERT_CLAIM, nonce, expEpochSeconds);\n if (!cursor || typeof cursor.toArray !== 'function') return false;\n const rows: unknown = cursor.toArray();\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n\n const row: unknown = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n if (\n !Object.hasOwn(row, 'nonce') ||\n !Object.hasOwn(row, 'expires_at') ||\n !('nonce' in row) ||\n !('expires_at' in row)\n ) {\n return false;\n }\n return row.nonce === nonce && row.expires_at === expEpochSeconds;\n } catch {\n return false;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,iBAAb,MAAoD;CAerB;CAd7B,6BAAsB,IAAI,QAAmC;CAI7D,6BAAsB,IAAI,QAAgB;CAC1C;CAEA,sBAAsB,SAAkE;EACtF,KAAK,qBAAqB;CAC5B;CAEA;CACA;CAEA,YAAY,KAAmC;EAAlB,KAAA,MAAA;CAAmB;CAEhD,sBAAsB,YAAoE;EACxF,KAAK,qBAAqB;CAC5B;;CAGA,sBAAsB,UAAsD;EAC1E,KAAK,oBAAoB;CAC3B;;;;;;CAOA,MAAM,UAAa,IAAY,OAAqC;EAClE,KAAK,WAAW,IAAI,EAAE;EACtB,IAAI;GACF,OAAO,MAAM,MAAM;EACrB,UAAU;GACR,KAAK,WAAW,OAAO,EAAE;EAC3B;CACF;CAGA,SAAS,SAAyB,CAAC;CACnC,SAAS,SAAyB,CAAC;CAEnC,KAAK,QAAkB,MAAoC;EACzD,OAAO,OAAO,KAAK,IAAI;CACzB;CAEA,MAAM,QAAkB,MAAoC;EAC1D,OAAO,OAAO,MAAM,IAAI;CAC1B;CAEA,eAAe,MAAwB;EACrC,OAAO,KAAK,eAAe,IAAI,CAAC,CAAC,KAAK,OAAO,KAAK,aAAa,EAAE,CAAC,CAAC,MAAM;CAC3E;CAEA,aAAa,KAA6C;EACxD,MAAM,aAAa,IAAI,IAAI,IAAI,aAAa,CAAC,CAAC;EAC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B,IAAI,CAAC,OAAO,OAAO,IAAI,SAAS,YAAY;GAC5C,IAAI,KAAK,YAAY;GACrB,IAAI,KAAK,mBAAmB;GAC5B,KAAK,MAAM;EACb,QAAQ;GAEN,KAAK,MAAM,KAAA;EACb;CACF;CAEA,MAAM,MAAM,OAAe,iBAA2C;EACpE,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,KAAK,OAAO;EAEjB,MAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAK;EACzC,IAAI,CAAC,uBAAuB,OAAA,GAAsB,KAAK,CAAC,cAAc,iBAAiB,GAAG,GACxF,OAAO;EAGT,IAAI;GAGF,IAAI,KAAK,gBAAgB,KAAK,oBAAoB;GAElD,MAAM,SAAS,IAAI,KAAK,cAAc,OAAO,eAAe;GAC5D,IAAI,CAAC,UAAU,OAAO,OAAO,YAAY,YAAY,OAAO;GAC5D,MAAM,OAAgB,OAAO,QAAQ;GACrC,IAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,GAAG,OAAO;GAEtD,MAAM,MAAe,KAAK;GAC1B,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM,OAAO;GACpD,IACE,CAAC,OAAO,OAAO,KAAK,OAAO,KAC3B,CAAC,OAAO,OAAO,KAAK,YAAY,KAChC,EAAE,WAAW,QACb,EAAE,gBAAgB,MAElB,OAAO;GAET,OAAO,IAAI,UAAU,SAAS,IAAI,eAAe;EACnD,QAAQ;GACN,OAAO;EACT;CACF;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import "./vela-env-DFvyoNT3.js";
|
|
2
|
+
import { a as DoPitrId, c as DoPitrUnavailableError, d as isDoPitrUnavailable, f as readDoPitrBookmark, i as DoPitrBookmarkRead, l as VelaDoPitrRpc, n as DoPitrArmOptions, o as DoPitrNamespace, p as CloudflareRoot, r as DoPitrArmResult, s as DoPitrStorage, t as VelaNonceDurableObject, u as armDoPitr } from "./nonce.durable-object-Df4CZi-0.js";
|
|
3
|
+
import { AsyncCacheStore, CacheEntry, CacheEntryReader, CacheEntryWriter, CacheInvalidationStore, DynamicModule, InjectionToken, NonceStore, RuntimeAdapter, ThrottlerStore, Type, VelaApplication, VelaEnv, VelaMiddlewareHandler, VelaSecurityOptions } from "@velajs/vela";
|
|
4
|
+
import { BroadcastCommand, ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, UpgradeAuthenticator, WebSocketGateway, WebSocketGatewayOptions, WebSocketSendGate, WebSocketServer, WebSocketUpgradeAuthenticationContext, WebSocketUpgradeIdentity, WsClient, WsDispatcher, WsException, WsMessage, WsResponse, WsServer } from "@velajs/vela/websocket";
|
|
5
5
|
import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveEngine, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
|
|
6
|
+
import { DownloadResult, PresignMethod, PresignedUrlResult, StorageBody, StorageDriver, UploadOptions, UploadResult } from "@velajs/vela/storage";
|
|
6
7
|
import { Context, ExecutionContext } from "hono";
|
|
8
|
+
import "@velajs/vela/internal";
|
|
7
9
|
import { FeatureFlagDriver, FlagContext } from "@velajs/feature-flags";
|
|
8
10
|
//#region src/websocket/room-id.d.ts
|
|
9
11
|
/** Stable, collision-free Durable Object name for one gateway's room. */
|
|
@@ -14,8 +16,63 @@ interface WsGatewayRoute {
|
|
|
14
16
|
path: string;
|
|
15
17
|
binding: string;
|
|
16
18
|
options: WebSocketGatewayOptions;
|
|
19
|
+
/** Container module that declares the gateway; its authenticator resolves from here. */
|
|
20
|
+
moduleId?: string;
|
|
17
21
|
}
|
|
18
22
|
//#endregion
|
|
23
|
+
//#region src/scheduled-event.d.ts
|
|
24
|
+
/**
|
|
25
|
+
* The event a Worker's `scheduled()` export receives. The native
|
|
26
|
+
* `ScheduledController` satisfies it; direct calls (tests, scripts) may omit
|
|
27
|
+
* `scheduledTime`, which then defaults to the current time, and `noRetry`.
|
|
28
|
+
*/
|
|
29
|
+
interface ScheduledEvent {
|
|
30
|
+
readonly cron: string;
|
|
31
|
+
readonly scheduledTime?: number;
|
|
32
|
+
noRetry?(): void;
|
|
33
|
+
}
|
|
34
|
+
/** The Cloudflare trigger behind the current scheduled invocation. */
|
|
35
|
+
interface CloudflareScheduledEvent {
|
|
36
|
+
/** The trigger's exact cron string; it equals the invocation's `expression`. */
|
|
37
|
+
readonly cron: string;
|
|
38
|
+
/** The platform's scheduled time in Unix milliseconds. */
|
|
39
|
+
readonly scheduledTime: number;
|
|
40
|
+
/**
|
|
41
|
+
* Ask Cloudflare not to retry this trigger if the invocation fails. Already
|
|
42
|
+
* bound to the native controller, so it can be passed around or destructured.
|
|
43
|
+
* A no-op for direct calls that supplied no controller.
|
|
44
|
+
*/
|
|
45
|
+
readonly noRetry: () => void;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Request-scoped Cloudflare view of the scheduled trigger, seeded into each
|
|
49
|
+
* `@Cron` job's invocation scope by the Cloudflare adapter. Inject it where a
|
|
50
|
+
* job needs platform controls such as `noRetry()`; the job's argument stays
|
|
51
|
+
* the portable `ScheduleInvocation`. It resolves only inside a scheduled
|
|
52
|
+
* invocation; resolving it anywhere else throws. A cron job fired on demand
|
|
53
|
+
* (Studio's run-now) receives a synthetic event: `cron` is the job's
|
|
54
|
+
* expression and `noRetry()` does nothing.
|
|
55
|
+
*
|
|
56
|
+
* The token provides itself as request-scoped in every container, so a class
|
|
57
|
+
* that injects it is request-scoped wherever the graph boots (a Worker, a
|
|
58
|
+
* Durable Object, the CLI or a testing module) and is built only for an
|
|
59
|
+
* invocation, never at bootstrap.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* @Injectable({ scope: Scope.REQUEST })
|
|
64
|
+
* class Reports {
|
|
65
|
+
* constructor(@Inject(CLOUDFLARE_SCHEDULED_EVENT) private readonly trigger: CloudflareScheduledEvent) {}
|
|
66
|
+
*
|
|
67
|
+
* @Cron('0 3 * * *', { dialect: 'cloudflare' })
|
|
68
|
+
* async nightly(tick: CronInvocation) {
|
|
69
|
+
* if (!(await this.upstreamAvailable(tick.signal))) this.trigger.noRetry();
|
|
70
|
+
* }
|
|
71
|
+
* }
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export declare const CLOUDFLARE_SCHEDULED_EVENT: InjectionToken<CloudflareScheduledEvent>;
|
|
75
|
+
//#endregion
|
|
19
76
|
//#region src/cloudflare-application.d.ts
|
|
20
77
|
/**
|
|
21
78
|
* Options accepted by {@link CloudflareApplication.mountOpenApi}.
|
|
@@ -28,15 +85,16 @@ type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
|
|
|
28
85
|
/**
|
|
29
86
|
* Wraps VelaApplication with Cloudflare-specific handlers:
|
|
30
87
|
* - `fetch` — HTTP request handler (from Hono)
|
|
31
|
-
* - `scheduled` — Cron trigger handler (
|
|
32
|
-
*
|
|
33
|
-
* - `queue` — Queue consumer handler (
|
|
88
|
+
* - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose
|
|
89
|
+
* expression is the trigger's exact string)
|
|
90
|
+
* - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,
|
|
91
|
+
* then `QueueModule`'s native consumer)
|
|
34
92
|
* - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on
|
|
35
93
|
* the underlying Hono app
|
|
36
94
|
*
|
|
37
95
|
* @example
|
|
38
96
|
* ```ts
|
|
39
|
-
* const app = await createCloudflareApp(AppModule, { env
|
|
97
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
40
98
|
* export default {
|
|
41
99
|
* fetch: app.fetch,
|
|
42
100
|
* scheduled: app.scheduled.bind(app),
|
|
@@ -47,18 +105,18 @@ type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
|
|
|
47
105
|
* @example
|
|
48
106
|
* ```ts
|
|
49
107
|
* // Serve OpenAPI docs alongside your routes
|
|
50
|
-
* const app = await createCloudflareApp(AppModule, { env
|
|
108
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
51
109
|
* const document = createOpenApiDocument(AppModule);
|
|
52
110
|
* app.mountOpenApi({ document, ui: 'scalar' });
|
|
53
111
|
* // GET /openapi.json -> JSON document
|
|
54
112
|
* // GET /scalar -> Scalar UI (loads from CDN)
|
|
55
113
|
* ```
|
|
56
114
|
*/
|
|
57
|
-
export declare class CloudflareApplication
|
|
115
|
+
export declare class CloudflareApplication {
|
|
58
116
|
#private;
|
|
59
|
-
readonly env:
|
|
60
|
-
constructor(app: VelaApplication, env:
|
|
61
|
-
readonly fetch: (request: Request, env:
|
|
117
|
+
readonly env: VelaEnv;
|
|
118
|
+
constructor(app: VelaApplication, env: VelaEnv);
|
|
119
|
+
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext) => Promise<Response>;
|
|
62
120
|
getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
|
|
63
121
|
/**
|
|
64
122
|
* Resolve a provider from the application's DI container (delegates to
|
|
@@ -68,7 +126,7 @@ export declare class CloudflareApplication<T extends object = object> {
|
|
|
68
126
|
*
|
|
69
127
|
* @example
|
|
70
128
|
* ```ts
|
|
71
|
-
* const app = await createCloudflareApp(AppModule, { env
|
|
129
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
72
130
|
* const auth = app.get(BetterAuthService);
|
|
73
131
|
* ```
|
|
74
132
|
*/
|
|
@@ -85,7 +143,7 @@ export declare class CloudflareApplication<T extends object = object> {
|
|
|
85
143
|
* ```ts
|
|
86
144
|
* import { createOpenApiDocument } from '@velajs/vela';
|
|
87
145
|
*
|
|
88
|
-
* const app = await createCloudflareApp(AppModule, { env
|
|
146
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
89
147
|
* const document = createOpenApiDocument(AppModule, {
|
|
90
148
|
* info: { title: 'My API', version: '1.0.0' },
|
|
91
149
|
* });
|
|
@@ -104,75 +162,104 @@ export declare class CloudflareApplication<T extends object = object> {
|
|
|
104
162
|
/** @internal — upgrade routes discovered from the application's gateways. */
|
|
105
163
|
getWsGatewayRoutes(): WsGatewayRoute[];
|
|
106
164
|
/**
|
|
107
|
-
* Handle Cloudflare
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
165
|
+
* Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose
|
|
166
|
+
* expression is exactly `event.cron` (the trigger string is compared as
|
|
167
|
+
* delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch
|
|
168
|
+
* primitive every runtime shares. Each job receives only its
|
|
169
|
+
* `ScheduleInvocation`, runs in a fresh invocation scope seeded with
|
|
170
|
+
* {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`
|
|
171
|
+
* dispatch. The trigger settles after every matching job and its managed
|
|
172
|
+
* work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.
|
|
111
173
|
*/
|
|
112
|
-
scheduled(event: {
|
|
113
|
-
cron: string;
|
|
114
|
-
scheduledTime?: number;
|
|
115
|
-
}, env: T, ctx: {
|
|
174
|
+
scheduled(event: ScheduledEvent, env: VelaEnv, _ctx?: {
|
|
116
175
|
waitUntil: (promise: Promise<unknown>) => void;
|
|
117
176
|
}): Promise<void>;
|
|
118
177
|
/**
|
|
119
|
-
* Run one
|
|
120
|
-
*
|
|
178
|
+
* Run one queue consumer inside a fresh request scope, through the shared
|
|
179
|
+
* guard → interceptor pipeline (components declared with
|
|
121
180
|
* `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or
|
|
122
181
|
* method). HTTP-global components deliberately do NOT apply — an HTTP auth
|
|
123
|
-
* guard has no business rejecting a queue batch. Unclaimed errors
|
|
124
|
-
*
|
|
182
|
+
* guard has no business rejecting a queue batch. Unclaimed errors are
|
|
183
|
+
* reported once (`QueueModule`'s consumer reports its own) and rethrow so
|
|
184
|
+
* the platform's retry semantics stay intact.
|
|
125
185
|
*/
|
|
126
186
|
private dispatchEntrypoint;
|
|
127
187
|
/**
|
|
128
|
-
* Handle Cloudflare Queue consumer events.
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
188
|
+
* Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read
|
|
189
|
+
* from `app.entrypoints` claim a batch by its physical queue name and
|
|
190
|
+
* receive it whole. A batch no handler claims goes to `QueueModule`'s native
|
|
191
|
+
* consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which
|
|
192
|
+
* routes each job by its logical queue. Each dispatch runs inside a fresh
|
|
193
|
+
* request-scoped child (request-scoped providers rebuild per batch — no
|
|
194
|
+
* boot-time captives). A batch nothing claims rejects: resolving would let
|
|
195
|
+
* Cloudflare acknowledge every message implicitly.
|
|
132
196
|
*/
|
|
133
197
|
queue(batch: {
|
|
134
198
|
queue: string;
|
|
135
199
|
messages: readonly unknown[];
|
|
136
|
-
}, env:
|
|
200
|
+
}, env: VelaEnv, ctx: {
|
|
137
201
|
waitUntil: (promise: Promise<unknown>) => void;
|
|
138
202
|
}): Promise<void>;
|
|
203
|
+
/**
|
|
204
|
+
* A raw `@QueueConsumer` owns its physical queue's batches and must not carry
|
|
205
|
+
* jobs of a queue registered with `QueueModule`: those reach their
|
|
206
|
+
* `@Processor` only if the raw handler dispatches them itself, while
|
|
207
|
+
* `cloudflareQueues()` delivers registered queues. Warn once per physical and
|
|
208
|
+
* logical queue (unless diagnostics are silent); the raw consumer still
|
|
209
|
+
* receives and settles the batch.
|
|
210
|
+
*/
|
|
211
|
+
private warnRawJobs;
|
|
212
|
+
/**
|
|
213
|
+
* Abort the signals of scheduled jobs still running, wait for them and their
|
|
214
|
+
* managed work to settle, then close the application.
|
|
215
|
+
*/
|
|
139
216
|
close(signal?: string): Promise<void>;
|
|
140
217
|
}
|
|
141
218
|
//#endregion
|
|
142
219
|
//#region src/cloudflare-factory.d.ts
|
|
143
|
-
interface CloudflareWorkerOptions
|
|
144
|
-
/** Global typed DI token for the platform's native environment. */
|
|
145
|
-
envToken: InjectionToken<T>;
|
|
220
|
+
interface CloudflareWorkerOptions {
|
|
146
221
|
globalPrefix?: string;
|
|
147
222
|
security?: VelaSecurityOptions;
|
|
148
|
-
/** Build request middleware from the same
|
|
149
|
-
middleware?: (env:
|
|
223
|
+
/** Build request middleware from the same native environment DI receives as ENV. */
|
|
224
|
+
middleware?: (env: VelaEnv) => VelaMiddlewareHandler[];
|
|
225
|
+
/** Further runtime adapters, composed after the Cloudflare adapter for each application. */
|
|
226
|
+
adapters?: RuntimeAdapter[];
|
|
150
227
|
}
|
|
151
|
-
interface CreateCloudflareAppOptions
|
|
228
|
+
interface CreateCloudflareAppOptions extends CloudflareWorkerOptions {
|
|
152
229
|
/** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */
|
|
153
|
-
env:
|
|
230
|
+
env: VelaEnv;
|
|
154
231
|
}
|
|
155
|
-
/** Bind an application to one environment before provider factories and lifecycle hooks. */
|
|
156
|
-
export declare function cloudflareAdapter<T extends object>(options: CreateCloudflareAppOptions<T>): RuntimeAdapter;
|
|
157
|
-
/** Build an application for one native Workers environment. Call inside a platform event. */
|
|
158
|
-
export declare function createCloudflareApp<T extends object>(rootModule: CloudflareRoot<NoInfer<T>>, options: CreateCloudflareAppOptions<T>): Promise<CloudflareApplication<T>>;
|
|
159
232
|
/**
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
233
|
+
* Bind an application to one environment: seeded as the global ENV before
|
|
234
|
+
* provider factories and lifecycle hooks, and asserted on every request. The
|
|
235
|
+
* adapter also supplies the `InternalDispatcher` transport, so signed queue and
|
|
236
|
+
* schedule dispatch re-enter this application's routes, and reports schedule
|
|
237
|
+
* declarations a cron trigger cannot honor through the diagnostics policy.
|
|
163
238
|
*/
|
|
164
|
-
export declare function
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
239
|
+
export declare function cloudflareAdapter(options: {
|
|
240
|
+
env: VelaEnv;
|
|
241
|
+
}): RuntimeAdapter;
|
|
242
|
+
/**
|
|
243
|
+
* Build an application for one native Workers environment. Call inside a platform event.
|
|
244
|
+
* The root is static: a module class or a `DynamicModule` declared at module scope.
|
|
245
|
+
* Read bindings in providers (`@InjectEnv()`) and module factories
|
|
246
|
+
* (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
|
|
247
|
+
*/
|
|
248
|
+
export declare function createCloudflareApp(rootModule: CloudflareRoot, options: CreateCloudflareAppOptions): Promise<CloudflareApplication>;
|
|
249
|
+
/**
|
|
250
|
+
* Worker entrypoint with one bootstrap per environment identity. Concurrent cold
|
|
251
|
+
* events share construction; failed construction is evicted so the next event
|
|
252
|
+
* can retry. Weak keys stop this cache from retaining a replaced environment.
|
|
253
|
+
*/
|
|
254
|
+
export declare function createCloudflareWorker(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): {
|
|
255
|
+
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
|
|
256
|
+
scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
|
|
170
257
|
waitUntil: (promise: Promise<unknown>) => void;
|
|
171
258
|
}): Promise<void>;
|
|
172
259
|
queue(batch: {
|
|
173
260
|
queue: string;
|
|
174
261
|
messages: readonly unknown[];
|
|
175
|
-
}, env:
|
|
262
|
+
}, env: VelaEnv, ctx: {
|
|
176
263
|
waitUntil: (promise: Promise<unknown>) => void;
|
|
177
264
|
}): Promise<void>;
|
|
178
265
|
};
|
|
@@ -403,60 +490,6 @@ export declare class KvFlagDriver implements FeatureFlagDriver {
|
|
|
403
490
|
/** Convenience factory for {@link KvFlagDriver}. */
|
|
404
491
|
export declare function kvFlagDriver(kv: KVNamespace, options?: KvFlagDriverOptions): KvFlagDriver;
|
|
405
492
|
//#endregion
|
|
406
|
-
//#region src/decorators/env.d.ts
|
|
407
|
-
/**
|
|
408
|
-
* Parameter decorator to inject Cloudflare environment bindings.
|
|
409
|
-
*
|
|
410
|
-
* Without arguments, returns the entire `env` object.
|
|
411
|
-
* With a binding name, returns that specific binding.
|
|
412
|
-
*
|
|
413
|
-
* @example
|
|
414
|
-
* ```ts
|
|
415
|
-
* @Get()
|
|
416
|
-
* handle(@Env() env: WorkerEnv) { ... }
|
|
417
|
-
*
|
|
418
|
-
* @Get()
|
|
419
|
-
* handle(@Env('MY_KV') kv: KVNamespace) { ... }
|
|
420
|
-
* ```
|
|
421
|
-
*/
|
|
422
|
-
export declare const Env: (data?: string | undefined, ...pipes: import("@velajs/vela").PipeType[]) => ParameterDecorator;
|
|
423
|
-
//#endregion
|
|
424
|
-
//#region src/decorators/scheduled.d.ts
|
|
425
|
-
interface ScheduledMetadata {
|
|
426
|
-
cron: string;
|
|
427
|
-
methodName: string;
|
|
428
|
-
}
|
|
429
|
-
/** Compatible with the existing programmatic scheduled() entrypoint. */
|
|
430
|
-
interface ScheduledEvent {
|
|
431
|
-
readonly cron: string;
|
|
432
|
-
readonly scheduledTime?: number;
|
|
433
|
-
}
|
|
434
|
-
/** Native controller passed unchanged to a Worker handler. Call noRetry on its receiver. */
|
|
435
|
-
interface ScheduledController extends ScheduledEvent {
|
|
436
|
-
readonly scheduledTime: number;
|
|
437
|
-
noRetry(): void;
|
|
438
|
-
}
|
|
439
|
-
interface ScheduledContext {
|
|
440
|
-
waitUntil(promise: Promise<unknown>): void;
|
|
441
|
-
}
|
|
442
|
-
type ScheduledHandler<Env extends object = object> = (controller: ScheduledController, env: Env, context: ScheduledContext) => void | Promise<void>;
|
|
443
|
-
export declare function parseScheduledMetadata(value: unknown): ScheduledMetadata;
|
|
444
|
-
/**
|
|
445
|
-
* Marks a method as a scheduled (cron) handler.
|
|
446
|
-
*
|
|
447
|
-
* @example
|
|
448
|
-
* ```ts
|
|
449
|
-
* @Injectable()
|
|
450
|
-
* class WorkerService {
|
|
451
|
-
* @Scheduled('0 * * * *')
|
|
452
|
-
* async hourlyCron() {
|
|
453
|
-
* console.log('Running hourly');
|
|
454
|
-
* }
|
|
455
|
-
* }
|
|
456
|
-
* ```
|
|
457
|
-
*/
|
|
458
|
-
export declare function Scheduled(cron: string): MethodDecorator;
|
|
459
|
-
//#endregion
|
|
460
493
|
//#region src/decorators/queue-consumer.d.ts
|
|
461
494
|
interface QueueConsumerMetadata {
|
|
462
495
|
queueName: string;
|
|
@@ -645,5 +678,5 @@ interface DurableObjectNonceStoreOptions {
|
|
|
645
678
|
*/
|
|
646
679
|
export declare function durableObjectNonceStore(options: DurableObjectNonceStoreOptions): NonceStore;
|
|
647
680
|
//#endregion
|
|
648
|
-
export { type BroadcastNamespace, type CfLiveDriver, type CloudflareRateLimitBinding, type CloudflareRateLimitStoreOptions, type CloudflareRoot, type CloudflareWorkerOptions, ConnectedSocket, type CreateCloudflareAppOptions, type DiskConfig, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type FlagshipBinding, type FlagshipFlagDriverOptions, type KvFlagDriverOptions, type LiveNamespace, MessageBody, type MountOpenApiOptions, type OnGatewayConnection, type OnGatewayDisconnect, type OnGatewayInit, type PresignedUrlConfig, type QueueConsumerMetadata, type
|
|
681
|
+
export { type BroadcastNamespace, type CfLiveDriver, type CloudflareRateLimitBinding, type CloudflareRateLimitStoreOptions, type CloudflareRoot, type CloudflareScheduledEvent, type CloudflareWorkerOptions, ConnectedSocket, type CreateCloudflareAppOptions, type DiskConfig, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type FlagshipBinding, type FlagshipFlagDriverOptions, type KvFlagDriverOptions, type LiveNamespace, MessageBody, type MountOpenApiOptions, type OnGatewayConnection, type OnGatewayDisconnect, type OnGatewayInit, type PresignedUrlConfig, type QueueConsumerMetadata, type ScheduledEvent, type StorageModuleOptions, SubscribeMessage, type UpgradeAuthenticator, type VelaDoPitrRpc, WebSocketGateway, WebSocketServer, type WebSocketUpgradeAuthenticationContext, type WebSocketUpgradeIdentity, type WsClient, WsException, type WsGatewayRoute, type WsMessage, type WsResponse, type WsServer, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark };
|
|
649
682
|
//# sourceMappingURL=index.d.ts.map
|