@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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,117 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.31.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 5f19b37: The Cloudflare adapter wires the core `WebSocketModule` and `LiveModule` itself, so an application imports the same modules on every runtime and one static `AppModule` boots in a Worker, in each `VelaWebSocketDurableObject` and on a node host. `cloudflareAdapter` registers the platform as the global `WS_TRANSPORT` and `LIVE_PLATFORM` tokens before modules load; it never replaces a module's providers.
|
|
8
|
+
|
|
9
|
+
- In the Worker, `WebSocketModule` serves an upgrade route for each gateway that names a `binding`. The route authenticates the upgrade before the Durable Object id is derived, reconciles it with the request's trusted identity, and forwards it to the gateway + room Durable Object as before. A gateway's `@WebSocketServer()` has no sockets in the Worker, so pushes from there throw with guidance to push with `Gateways` from `@velajs/vela/websocket`.
|
|
10
|
+
- Inside the Durable Object, the server gateways inject broadcasts to that object's hibernatable sockets. `LiveModule` delivers locally, and its cursor log is a `DoCursorLog` in the object's SQLite storage when the class is SQLite-backed (`new_sqlite_classes`), in memory otherwise (`new_classes`).
|
|
11
|
+
- `LiveModule` in the Worker defaults to `durableObjectLive()`: an invalidation goes to the room Durable Object of the application's single binding-backed gateway, and the namespace is read from `ENV` when an invalidation first needs it. The gateways come from their decorators, so an invalidation sent from `onModuleInit` or `onApplicationBootstrap` reaches the room as well. The first invalidation fails with an ambiguity error only when several binding-backed gateways could hold the subscriptions. `durableObjectLive({ binding, gatewayPath, defaultRoom })` chooses; every option is optional. A Worker configured with `localLive()` still warns once.
|
|
12
|
+
- `createCloudflareWorker(AppModule, { configure(app, env) {} })` finishes each application's HTTP surface, such as extra Hono routes, once per environment. It runs after the application is built and before any event, including concurrent cold events, reaches it. A throw fails that construction, and the next event retries. It must be synchronous and do no I/O; a `configure` that returns a promise fails construction.
|
|
13
|
+
- A minimal `createCloudflareWorker()` Worker no longer bundles the core WebSocket upgrade routes, the gateway dispatcher or the live protocol. It still carries the adapter's own wiring: the Worker transport that forwards upgrades to a room's Durable Object, the default `durableObjectLive()` driver and the check for gateways without `WebSocketModule`. The adapter reads the Cloudflare-attested `cf-connecting-ip` header directly, which also keeps Hono's WebSocket upgrade helper out. With the rest of this release, including the single HTTP error renderer, gateway scoping and framework CORS, a minimal `createCloudflareWorker()` Worker measures 155,636 bytes raw and 52,363 bytes gzipped, against 159,520 and 53,539 for 1.30.0.
|
|
14
|
+
|
|
15
|
+
**Behavior change:** `CloudflareWebSocketModule` is removed. Import `WebSocketModule.forRoot()` from `@velajs/vela/websocket` in the Worker and the Durable Object alike. Without it, the Worker mounts no upgrade route, so a binding-backed gateway's upgrades answer 404 instead of reaching its Durable Object; the adapter reports each such gateway through the diagnostics policy, a warning by default. The `WsGatewayRoute` type and `CloudflareApplication.scanInstances()` and `getWsGatewayRoutes()` are removed with it: the upgrade routes come from `WebSocketModule`.
|
|
16
|
+
|
|
17
|
+
**Behavior change:** `durableObjectLive()` takes the binding name, not the namespace object: replace `durableObjectLive({ namespace: env.ROOMS, gatewayPath })` with `durableObjectLive({ binding: 'ROOMS', gatewayPath })`, or drop the `driver` option to use the default. `LiveModule` no longer needs `forRootAsync({ inject: [ENV] })` for the driver. A Worker that imports `LiveModule` but declares no binding-backed gateway no longer falls back to `localLive()`: each invalidation rejects with "no @WebSocketGateway names a binding". A write through `@Crud({ live })`, or one that calls `LiveInvalidation.invalidate()` itself, commits and then returns that error; a `@LiveInvalidates` handler answers with its result, without commit headers, and reports the error through the application's error reporter (`edge: 'live'`). Declare the gateway, or configure `LiveModule.forRoot({ driver: () => localLive() })` explicitly. `durableObjectCursorLog()` is removed; drop the `log` option, since the adapter supplies the SQLite log inside the Durable Object. `new DoCursorLog(sql, maxRows?)` takes the SQLite handle.
|
|
18
|
+
|
|
19
|
+
**Behavior change:** the `middleware: (env) => handlers` option of `createCloudflareWorker` and `createCloudflareApp` is removed. Apply request middleware from a module with `configure(consumer)`; a consumer middleware class resolves through dependency injection, so it can inject `ENV` with `@InjectEnv()`. Use `configure(app, env)` for routes added to the Hono app. The `CloudflareAppOptions` type holds the options both entries share.
|
|
20
|
+
- 1011653: Bindings are referenced by name and resolved from each application's `ENV` when used. `@velajs/vela/module-kit` adds the seam: `BindingRef` (`{ binding: 'CACHE' }`), `BindingKind` (what a binding is and the configuration key that declares it), `resolveBinding(env, ref, kind)`, `defineBinding(kind)` for lower-camel binding factories, the `EnvFactory<T>` type for option values an application builds from its own `ENV`, and `readEnv(container)` for module providers. A missing binding fails with `ENV.CACHE is not set: declare the KV namespace binding 'CACHE' under kv_namespaces …`; a binding of another kind fails naming the same key.
|
|
21
|
+
|
|
22
|
+
`@velajs/cloudflare` exports the Workers binding factories built on it: `kv`, `r2`, `d1`, `queue`, `durableObject` and `rateLimit`. `kv({ binding: 'CACHE' })` reads no environment when declared; calling it with an application's `ENV` returns the typed native binding. The Cloudflare Queues driver and the Worker's gateway room objects (WebSocket upgrade forwarding, `Gateways` pushes, `durableObjectLive()` invalidations and `LiveInspector` reads) resolve their bindings through the same seam.
|
|
23
|
+
|
|
24
|
+
**Behavior change:** a send to a registered queue whose producer binding is missing or is not a producer rejects with `Queue 'email' cannot send: ENV.EMAIL_QUEUE is not set: …` (or `… is not a binding of type queue producer …`) instead of the previous wording. A WebSocket upgrade, `Gateways` push, `durableObjectLive()` invalidation or `LiveInspector` read whose gateway's Durable Object binding is missing or is not a namespace fails with `ENV.ROOMS is not set: declare the Durable Object namespace binding 'ROOMS' under durable_objects.bindings …` (or `… is not a binding of type Durable Object namespace …`); an upgrade reports that error through the application's error handler and answers with the redacted 500 body. Upgrades previously answered a plain-text 500 (`Durable Object binding 'ROOMS' is not configured`).
|
|
25
|
+
- 2c92243: `createCloudflareWorker()` attaches a descriptor under the symbol key `CLOUDFLARE_WORKER` (`Symbol.for('vela.cloudflare.worker')`) to the Worker it returns: `{ rootModule, options, createOptions(env), createApplication(env) }`. It is enumerable, so an entry that adds handlers with `{ ...worker, email }` keeps it; the platform reads only string-keyed handlers. `createOptions(env)` includes `env`, and `createApplication(env)` builds the application without the Worker handlers or the `configure(app, env)` hook, which receives the Workers application. Tools build the same application as the Worker from it without a platform event; `@velajs/cli` uses it to load a project without `vela.config`. The Worker is typed as the exported `CloudflareWorker` interface, and `CloudflareWorkerDescriptor` describes the descriptor.
|
|
26
|
+
|
|
27
|
+
The new `@velajs/cloudflare/testing` subpath runs inside the Workers Vitest pool. `createTestingWorker(AppModule, { env?, overrides?, ...workerOptions })` builds the module as `createCloudflareWorker(AppModule, workerOptions)` does, its adapters and then its `configure(app, env)` hook, through `@velajs/testing` (now an optional peer dependency), with `overrides` receiving the testing builder (`overrideProvider`, `overrideModule().useModule()`, `useMocker`). `worker.module` is the compiled `TestingModule`; its `fetch()` and `http` client send the Worker's environment as `c.env`. The returned worker's `fetch()`, `queue(queue, messages)` and `scheduled(cron)` drive the Worker handlers with `cloudflare:test`'s `createMessageBatch`, `getQueueResult` and `createScheduledController`: `queue()` reports the acknowledgements and whether the handler rejected, and `scheduled()` rejects a cron no `@Cron` job declares. `queueJob(queue, job, data)` builds the envelope `QueueClient.add()` sends, and `close()` cancels unread response bodies before waiting for background work. The subpath is not part of any Worker bundle.
|
|
28
|
+
- dfe925c: CORS is configured as in Nest. `app.enableCors(options?)` on `VelaApplication` and the `cors` create option (`VelaFactory.create(AppModule, { cors: true | CorsOptions })`) serve Hono's `cors` middleware ahead of body limits, routing and guards, so preflights are answered before any guard runs and refusals stay readable cross-origin. `enableCors` takes effect on the next request with no rebuild; a later call replaces the options. A credentialed `'*'` origin and a `maxAge` that is not a non-negative integer are rejected. `CorsOptions` is exported from `@velajs/vela`. On Workers, `createCloudflareWorker(AppModule, { cors })` and `createCloudflareApp(AppModule, { env, cors })` take the same option, and `CloudflareApplication.enableCors()` works inside `configure(app, env)`. Every application now carries Hono's `cors` middleware, and one pass-through middleware when CORS is off.
|
|
29
|
+
|
|
30
|
+
**Behavior change:** `CorsModule` and `CORS_OPTIONS` are removed from `@velajs/vela/security`, and `CorsOptions` moves from `@velajs/vela/security` to `@velajs/vela`. Replace `imports: [CorsModule.forRoot(options)]` with `app.enableCors(options)` or the `cors` create option; the options keep their shape (`origin`, `allowMethods`, `allowHeaders`, `exposeHeaders`, `credentials`, `maxAge`). Options `CorsModule` passed through unchecked now throw when CORS is enabled: `credentials: true` with a `'*'` origin (browsers refuse it) and a `maxAge` that is not a non-negative integer. CORS now runs ahead of the body and query limits and every global middleware instead of among the global middleware, so their refusals carry the CORS headers. Without `allowMethods`, a preflight now allows Nest's defaults (GET, HEAD, PUT, PATCH, POST, DELETE); `CorsModule` sent no `Access-Control-Allow-Methods` then, so browsers refused cross-origin PUT, PATCH and DELETE. `SecurityModule`'s exact-origin `cors` option is unchanged, but it can no longer be combined with framework CORS: while it is on (it is unless `cors: false`), the `cors` create option fails bootstrap and `app.enableCors()` throws, because that middleware would answer every preflight before `SecurityModule`'s method and header checks.
|
|
31
|
+
- fd11d20: Push to a gateway's rooms from anywhere with `Gateways`, injectable from `@velajs/vela/websocket` wherever `WebSocketModule` is imported: `gateways.of<ChatEvents>(ChatGateway).to(room).emit('message', data)`. The explicit event map (event name → payload) types each push; `to(room)` and `in(room)` chain rooms. The target comes from the gateway's `@WebSocketGateway` metadata (`path`, `binding`, `roomParam`), and each push is bounded by that gateway's `maxFrameBytes` before anything is resolved or sent. `emit()` without a room and `except()` throw with guidance, and a class without `@WebSocketGateway` is rejected. The handle types are `GatewayServer<Events>` and `GatewayBroadcastOperator<Events>`.
|
|
32
|
+
|
|
33
|
+
- A push reaches only that gateway's sockets on every runtime, so two gateways may use the same room id (such as an organization id) without one gateway's pushes reaching the other's sockets. `BroadcastCommand` gains an optional `gatewayPath`, which `Gateways` sets on every push and synchronized commands validate; `WsClient` gains an optional `path`, the gateway route the socket connected through (`NodeWsClient` and the Cloudflare client set it). The in-memory and Durable Object room registries deliver a command that names a gateway path only to sockets whose `path` matches, so a socket without one receives no gateway push or broadcast.
|
|
34
|
+
- A gateway's `@WebSocketServer()` is that gateway's own server, scoped the same way: on node, Bun and Deno its broadcasts, including a global `emit()`, carry the gateway path and reach only the sockets connected through that gateway, where they previously reached every gateway's sockets in the named rooms. This holds for `@Inject(WS_SERVER)` in a gateway's constructor and for a constructor inherited from a base class (each gateway gets its own server), and `afterInit(server)` receives the server that injected handle pushes through: pushes through either reach the same sockets, but they are not the same object. Each broadcast is bounded by the gateway's own `maxFrameBytes`. `WebSocketModule` connects each gateway's server while the application starts, before any lifecycle hook runs, from the `WS_SERVER` the gateway's module sees when it sees exactly one, including one provided by an async `useFactory`. When it sees none, or only the servers of several `WebSocketModule` instances it imports, a `WebSocketModule` instance's own server serves the gateway; a module that sees another module's `WS_SERVER` beside those fails bootstrap with an error naming each module that provides one. A test double provided as `WS_SERVER` in the gateway's module, or through `overrideProvider(WS_SERVER)` in a testing module, receives the gateway's pushes as long as `WebSocketModule.forRoot()` stays imported: a `WS_SERVER` without `WebSocketModule` connects nothing. `WS_SERVER` injected outside a gateway still addresses every gateway's sockets. `WsServer` gains an optional `forGateway(gatewayPath, maxFrameBytes)`, which `WsServerImpl` implements (and its constructor takes an optional `gatewayPath`); a transport server without it is shared by every gateway as before. On Cloudflare each Durable Object holds one gateway's room, so behavior there is unchanged.
|
|
35
|
+
- Presence rosters belong to one gateway room: heartbeats in a room of one gateway no longer appear in, or refresh, the `$presence.roster` of another gateway's room with the same id. `LiveQueryContext` gains `path`, the route path of the gateway the connection subscribed through, and a `@LiveQuery` tags function receives it as `(args, context)`. A `coalesceBy` partition is keyed by that path too, next to the query and its canonical args, so a resolver that answers per gateway never shares one run between subscribers of two gateways. `PresenceService.beat(gatewayPath, room, clientId, meta?)`, `PresenceService.roster(gatewayPath, room)` and `presenceTag(gatewayPath, room)` take the gateway path first; `inspectRooms()` still reports each room once, with the members of every gateway that uses its id. A roster's tag, `presenceTag(gatewayPath, room)`, is `$presence:` and the SHA-256 hex digest of the JSON `[gatewayPath, room]`, so every valid room id (up to 512 bytes) fits the 256-byte bound of an invalidation tag on any gateway path; room ids longer than 246 bytes previously failed the roster subscription. A heartbeat or departure whose roster invalidation the live driver fails to dispatch is reported through the application's error reporter instead of becoming an unhandled rejection.
|
|
36
|
+
- A custom `RoomRegistry` passed to `WebSocketModule.forRoot({ registry })` must skip sockets whose `path` differs from `cmd.gatewayPath` in `deliverLocal`, as the built-in registries do; one that ignores the field delivers every gateway push and broadcast to all gateways' sockets in the named rooms. With `redis()`, upgrade every instance together: instances on an earlier release ignore `gatewayPath` and deliver to every gateway's sockets in the room.
|
|
37
|
+
- Without a platform transport that delivers pushes, a push goes through the module's sync driver: in-process hosts (node, Bun, Deno) deliver it to the gateway's sockets in this process, and `redis()` fans it out to the gateway's sockets on every instance.
|
|
38
|
+
- A platform transport delivers pushes elsewhere with the new optional `WebSocketTransport.deliver(delivery)`, which receives one `GatewayDelivery` (`{ gatewayPath, binding?, room, command }`) per gateway room; a gateway without `roomParam` has one room, its path. A push delivered to several gateway rooms settles every delivery first; when some fail it rejects with an `AggregateError` whose message names the failed rooms (`2 of 3 ChatGateway room pushes failed: "b", "c"`; past ten rooms, the first ten and how many more) and whose `errors` hold one error per failed room with the transport's error as its `cause`, while a push delivered to one room rejects with the transport's own error. A transport that delivers pushes but builds no server gives gateways a `@WebSocketServer()` that keeps no sockets and refuses each push with guidance to `Gateways`. A transport that forwards upgrades (`forwardUpgrade`) but implements neither `deliver` nor `createServer` keeps a gateway with a `binding` out of this process's reach under the `local()` sync driver: a push to it, through `Gateways` or through its `@WebSocketServer()`, rejects with guidance instead of resolving without reaching anyone. A cross-instance sync driver such as `redis()` may reach the isolate that holds its sockets, so both push paths then hand it the command.
|
|
39
|
+
- On Cloudflare, a push from the Worker is a `broadcast` RPC to the gateway + room Durable Object, whose namespace is read by the gateway's `binding` from `ENV` when the push needs it. Inside a Durable Object, a push to its own room goes to its sockets, and a push to another room goes to that room's object instead of reaching no one. Pushing to a gateway without a `binding` fails with guidance.
|
|
40
|
+
- The `Gateways` service and the refusing server live in the core WebSocket entry, which a minimal `createCloudflareWorker()` Worker does not load, and upgrades, pushes and live invalidations share one gateway-room resolver.
|
|
41
|
+
|
|
42
|
+
**Behavior change:** a gateway's `@WebSocketServer()` no longer reaches other gateways' sockets, and it is no longer the `WS_SERVER` instance itself; a gateway that must address every gateway's sockets injects `WS_SERVER` into another provider. `WebSocketModule` connects a gateway's server: in an application or testing module without it, a `WS_SERVER` provided next to the gateway, or overridden with `overrideProvider(WS_SERVER)`, no longer reaches the gateway, whose pushes throw with guidance. Import `WebSocketModule.forRoot()`; a test double then serves the gateway when it is provided as `WS_SERVER` in the gateway's module or overridden in the testing module next to that import. A custom transport's `WsClient` must set `path` to its gateway's route: a socket without one receives no `Gateways` push and no broadcast from a gateway's `@WebSocketServer()`. `LiveQueryContext.path` is required, so code that builds a context, such as a resolver unit test, sets it; `PreparedLiveQuery.tags(context)` takes the subscribing connection's context. `PresenceService` methods and `presenceTag` take the gateway path first, and a presence tag is `$presence:` and a SHA-256 hex digest instead of the room id. `broadcastToRoom(namespace, gatewayPath, room, event, data, options?)` and its `BroadcastNamespace` type are removed from `@velajs/cloudflare`. Inject `Gateways` and call `gateways.of(Gateway).to(room).emit(event, data)`; the gateway's metadata supplies the namespace, path and frame limit.
|
|
43
|
+
- fd11d20: Add `@LiveInvalidates(tags, { room? })` to `@velajs/vela/live`. It runs as an interceptor on a handler: after the handler succeeds it invalidates the tags, static or derived from the result and the execution context (`(result, context) => tags`, where `[]` skips the invalidation), and stamps `Vela-Commit-Cursor` / `Vela-Commit-Epoch` on the handler's HTTP response through `switchToHttp().getResponse()`, or on a `Response` the handler returns. A mutation no longer needs `@Res()` and `stampCommitHeaders` to expose its commit. A handler that throws invalidates nothing. The interceptor resolves `LiveInvalidation` from the module that declares the controller before the handler runs, so a module that cannot reach `LiveModule` fails without committing the write. The tags callback's result type must match the handler's. An invalidation that fails after the handler has committed its write (a tags or room callback that throws, a live driver that cannot reach the room) does not fail the request: it is reported through the application's error reporter (`edge: 'live'`, `source` the handler's `Class.method`, note `invalidation failed after the handler succeeded`), and the request answers with the handler's result without commit headers, so the client drops its optimistic layer and subscribers catch up at the next invalidation of those tags. A failed response would invite a retry that repeats the committed write, which cannot repair the invalidation; keep write handlers idempotent, or accept an idempotency key, for clients that retry a request whose response they never received.
|
|
44
|
+
|
|
45
|
+
Add `LiveInspector`, provided and exported by `LiveModule`: `inspect(rooms)` returns the subscription and presence rows of the named rooms (there is no global room list), read where their subscriptions live. A runtime adapter reads a room through the new optional `LivePlatform.inspect(room)`; without it, the application's engine answers. On Cloudflare the Worker calls the room Durable Object's `inspectLive` RPC through the gateway binding its live driver delivers to. When several named rooms live in one object, each subscription is reported once and each room's members once. The `LiveInspection` type is unchanged. Studio's `livePanel({ rooms })` reads through it.
|
|
46
|
+
|
|
47
|
+
On Cloudflare, a gateway without `roomParam` keeps every socket in one room Durable Object, named by its path. Worker invalidations for such a gateway now go to that object whatever room they name, as upgrades and `Gateways` pushes do, instead of an object named by the room (`'default'` when none is named) that holds no sockets; `LiveInspector` reads follow the same rule. `liveInvalidateToRoom(namespace, gatewayPath, room, tags)` applies the same rule: for a gateway path without parameters it reaches the object named by the path. The Worker's live driver now validates the commit stamp a Durable Object returns before it reaches response headers.
|
|
48
|
+
- d51dbb3: `ThrottlerModule` takes Nest v5 named throttlers: `ThrottlerModule.forRoot({ throttlers: [{ name, ttl, limit }, ...], storage? })`. The global guard counts every request once per throttler, each in its own bucket (the key carries the throttler name), and answers 429 at the first one exceeded; later throttlers are not counted for that request. A throttler without `name` is `'default'`. Headers follow Nest: `X-RateLimit-Limit`, `-Remaining`, `-Reset` and `Retry-After` for `'default'`, suffixed `-<name>` for the others. The guard publishes its decisions under the `RATE_LIMIT` request-context key from `@velajs/vela/throttler`, one `RateLimitInfo` (`{ limit, remaining?, reset }`) per throttler name. `storage` also takes a function of the application's `ENV`, called once per application. Throttlers are validated when the application boots: at least one, unique names made of letters, digits, `_` or `-` (a Nest-style name such as `'per.minute'` fails), positive integer `ttl` (milliseconds) and `limit`. A store can check them too: `ThrottlerStore` gains an optional `validate(throttlers)`, called with the declared throttlers at bootstrap, so a store that cannot serve one fails the application instead of every request. The tracker is unchanged: the verified identity when one is published, else `getTracker` or the client IP.
|
|
49
|
+
|
|
50
|
+
`@velajs/cloudflare` adds `rateLimitStore({ binding })`, the `ThrottlerModule` storage over Workers Rate Limiting bindings resolved by name from each application's `ENV`: one binding for every throttler, or `{ binding: { burst: 'BURST_LIMITER', sustained: 'API_LIMITER' } }` per named throttler. Each binding's configured limit and period must equal its throttler's `limit` and `ttl` (10 or 60 seconds). The store declares `fixedLimits`, so a `@Throttle()` override that changes a throttler it serves fails the application at bootstrap instead of being silently ignored by the platform. One binding serves only throttlers that share a `limit` and `ttl`. The store checks the declared throttlers at bootstrap, before any binding is charged: a throttler whose `ttl` is not 10 or 60 seconds, throttlers with different values on one binding (the error names the per-throttler form), a throttler the per-name map leaves out, and a map entry naming no declared throttler each fail the application. Workers Rate Limiting counters are kept per Cloudflare location and are eventually consistent, so its limits are approximate, and `X-RateLimit-Reset` and `Retry-After` report the configured period rather than a measured reset.
|
|
51
|
+
|
|
52
|
+
**Behavior change:** `ThrottlerModule.forRoot({ limit, ttl })` is replaced by `forRoot({ throttlers: [{ limit, ttl }] })`. `@Throttle({ limit, ttl })` becomes `@Throttle({ default: { limit, ttl } })` (both fields optional, each a positive integer, checked when the decorator is applied), and `@SkipThrottle()` skips only the `'default'` throttler; use `@SkipThrottle({ name: true })` for a named one. As in Nest v5, `limit` and `ttl` override separately: a route's `@Throttle({ default: { limit } })` keeps its controller's `ttl`. A `@Throttle()` on a route or controller naming an undeclared throttler fails bootstrap. `ThrottlerStore.increment(key, ttl)` is now `increment(key, ttl, limit, throttlerName)`, `ThrottlerStorageRecord.enforcedLimit` is replaced by the store's `fixedLimits` flag, and `generateKey(tracker, { className, handlerName })` is now `generateKey(context, tracker, throttlerName)`. `THROTTLE_METADATA` and `SKIP_THROTTLE_METADATA` hold the whole decorator records.
|
|
53
|
+
|
|
54
|
+
**Behavior change:** `ThrottlerGuard` no longer sets the untyped `rateLimit` Hono variable. Its decisions are under the `RATE_LIMIT` request-context key, a record keyed by throttler name (`Readonly<Record<string, RateLimitInfo>>`): replace `c.get('rateLimit')` with `requestContext.get(RATE_LIMIT)?.default`. The default counter key gains the throttler name, `throttler:<Class>:<handler>:<name>:<tracker>` instead of `throttler:<Class>:<handler>:<tracker>`, so counts in a shared store restart after upgrading.
|
|
55
|
+
|
|
56
|
+
**Behavior change:** `cloudflareRateLimitStore(binding, { limit, periodSeconds })` and its `CloudflareRateLimitBinding` and `CloudflareRateLimitStoreOptions` types are removed. Use `storage: rateLimitStore({ binding: 'API_LIMITER' })` with a throttler whose `ttl` and `limit` match the binding.
|
|
57
|
+
- 4a06057: `CacheModule` from `@velajs/vela/cache` is the one cache module, asynchronous end to end and built on `defineModule` (`forRoot` and `forRootAsync`). `namespace` and the trusted `scope` resolver stay mandatory. `store` is optional: without it each application gets its own `MemoryCacheStore` of `max` entries (default 1000). `store` and `invalidation` also take a function of the application's `ENV`, called once per application, so a static registration serves every environment. `@CacheResponse({ ttl, tags, key })` caches GET routes and the injected `CacheService` serves `scope(trustedScope)` reads and post-commit invalidation over the same store. `CacheStore` is one interface whose methods may return values or promises, so memory, tiered and KV stores all fit it.
|
|
58
|
+
|
|
59
|
+
`@velajs/cloudflare` adds `kvCache({ binding })` and `kvCacheInvalidation({ binding })`: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }), invalidation: kvCacheInvalidation({ binding: 'CACHE_GENERATIONS' }) })` reads each namespace from the application's `ENV` when an operation needs it, and names `kv_namespaces` when it is missing. `ErrorReportContext.edge` gains `'cache'`. `KVCacheStore` and `KVCacheInvalidationStore` accept a namespace or a function returning one.
|
|
60
|
+
|
|
61
|
+
**Behavior change:** the synchronous cache is removed: the former `CacheModule` (`ttl`, `max`, `isGlobal` registering its interceptor, `varyBy`, synchronous `store`), its `CacheService` (`get`/`set`/`del`/`clear`), `CacheInterceptor`, `@Cacheable()`, `@CacheKey()`, `@CacheTTL()`, `CACHE_MANAGER` and the `CACHEABLE_METADATA`, `CACHE_KEY_METADATA` and `CACHE_TTL_METADATA` keys. Replace `@Cacheable()` + `@CacheKey(key)` + `@CacheTTL(seconds)` with `@CacheResponse({ key, ttl })`, and manual `CacheService` calls with `cache.scope(scope).get/set/invalidateKey`. Credentialed routes that relied on `varyBy` select a private scope from trusted identity in `scope(context)` instead.
|
|
62
|
+
|
|
63
|
+
**Behavior change:** the asynchronous response cache takes the single names: `ResponseCacheModule` is `CacheModule`, `ResponseCacheService` is `CacheService`, `ResponseCacheInterceptor` is `CacheInterceptor`, `RESPONSE_CACHE_OPTIONS` is `CACHE_MODULE_OPTIONS`, and the types `ResponseCacheOptions`, `ResponseCacheScope`, `ResponseCacheEntryOptions` and `ScopedResponseCache` are `CacheModuleOptions`, `CacheScope`, `CacheEntryOptions` and `ScopedCache`. `AsyncCacheStore` and `AnyCacheStore` are replaced by `CacheStore`. Stored entries keep their keys, so existing KV caches stay valid. Configuring two `CacheModule`s in one application fails bootstrap, as two response-cache modules did.
|
|
64
|
+
|
|
65
|
+
**Behavior change:** a store, generation or scope failure the cache absorbs as a miss or a false outcome is now reported to the application's error reporter (edge `'cache'`, the operation as `source`): it is logged by default, or passed to the `ExceptionHandler`'s `report`. `onError` still receives it afterwards. A missing or misnamed KV binding is therefore visible on its first use instead of disabling the cache silently; match it in the handler's `dontReport` to mute it.
|
|
66
|
+
- 1bfc1c1: `StorageModule` from `@velajs/storage` is the one storage module. Its `driver` may be a function of the application's `ENV`, called on the first storage operation of each application, so one static `StorageModule.forRoot` serves every environment without reading a binding at boot. On Cloudflare Workers, `r2Storage({ binding: 'UPLOADS' })` from the new `@velajs/cloudflare/storage` subpath is its native R2 driver: the bucket is resolved by name from `ENV` and validated, and a missing binding fails the operation naming `r2_buckets`. `@velajs/storage` is an optional peer of `@velajs/cloudflare`, needed only by that subpath.
|
|
67
|
+
|
|
68
|
+
**Behavior change:** the Cloudflare `StorageModule` is removed, with `StorageService`, `StorageManagerService`, `StorageController`, `R2StorageDriver`, `STORAGE_OPTIONS` and the `StorageModuleOptions`, `DiskConfig` and `PresignedUrlConfig` types from `@velajs/cloudflare`. Register a `StorageModule.forRoot({ name, driver: r2Storage({ binding }) })` from `@velajs/storage` per former disk and inject its `StorageService` (`@InjectStorage(name)` for a named bucket). A disk's `root` becomes the bucket's `prefix`, which is static: the `{date}`, `{year}`, `{month}`, `{day}` and `{uuid}` tokens have no replacement, so build such keys in the application. Its HMAC presign-proxy route (`GET /storage/:disk`) is gone and URLs it issued stop working: serve downloads through `publicBaseUrl`, the authorized `http: { download: 'proxy' }` controller, or provider-signed URLs from the S3 or R2 HTTP/hybrid drivers.
|
|
69
|
+
|
|
70
|
+
**Behavior change:** the `@velajs/vela/storage` subpath is removed with the second `StorageDriver` contract, `expandPathTemplate` and `joinStoragePath` it held for that module, and `STORAGE_SIGNED_URL_PURPOSE` leaves `@velajs/vela/security`. Use `@velajs/storage`'s driver contract and key helpers (`joinKey`, `normalizePrefix`, `sanitizeKey`); `signUrl` and `verifySignedUrl` stay on `@velajs/vela/security` with an application-chosen `purpose`.
|
|
71
|
+
- f267c2f: Routes compose like Nest's `setGlobalPrefix(prefix, { exclude })` and URI versioning:
|
|
72
|
+
|
|
73
|
+
- `VelaFactory.create(AppModule, { globalPrefix: '/api', globalPrefixOptions: { exclude: ['health', { path: 'webhooks/:id', method: 'POST' }] } })` serves matching controller routes without the prefix. Targets use the middleware route grammar and match the controller path plus the route path. A relative middleware target resolves under the prefix, so startup fails when one also matches an excluded route that no absolute or controller target of the same middleware covers or excludes. `RouteManager.setGlobalPrefix(prefix, { exclude })` takes the same options, and `createCloudflareWorker`/`createCloudflareApp` pass them through.
|
|
74
|
+
- `VERSION_NEUTRAL` serves a controller or route without a version segment; combine it with numbers (`@Version([2, VERSION_NEUTRAL])`) to serve both.
|
|
75
|
+
- `versioning: { prefix }` sets the text before the version number (default `'v'`; `false` serves `/1/...`).
|
|
76
|
+
- `app.getRoutePathOptions()` returns this composition; pass it to `createOpenApiDocument(AppModule, app.getRoutePathOptions())` so documents match the served paths. The CLI's OpenAPI and client commands and Studio's OpenAPI view use it, and route contributors receive it as `routePathOptions`.
|
|
77
|
+
|
|
78
|
+
**Behavior change:** With a global prefix, startup fails for any relative `forRoutes()` target that reaches prefixed routes while its written path also matches a route registered outside the prefix, not only a route `exclude` serves unprefixed. An adapter's absolute route counts too: under `globalPrefix: '/api'`, `forRoutes(':resource')` also matches the `RpcModule` endpoint `POST /rpc`, so startup fails. Previously the build failed only when such a target reached no prefixed route at all. Cover the outside route in the same `forRoutes()` with an absolute target (`{ path: '/rpc', absolute: true }`) or its controller, or leave it out with an absolute `exclude()`. An absolute target or exclude accounts only for the outside routes it matches itself: with both `RpcModule` and an excluded `health` route, `forRoutes(':resource', { path: '/rpc', absolute: true })` still fails startup for `GET /health` until that route is covered or excluded too.
|
|
79
|
+
|
|
80
|
+
### Patch Changes
|
|
81
|
+
|
|
82
|
+
- Updated dependencies [0b8c649]
|
|
83
|
+
- Updated dependencies [1011653]
|
|
84
|
+
- Updated dependencies [088f4d4]
|
|
85
|
+
- Updated dependencies [f267c2f]
|
|
86
|
+
- Updated dependencies [dfe925c]
|
|
87
|
+
- Updated dependencies [b227d22]
|
|
88
|
+
- Updated dependencies [fd11d20]
|
|
89
|
+
- Updated dependencies [748e4f8]
|
|
90
|
+
- Updated dependencies [096e259]
|
|
91
|
+
- Updated dependencies [3fc6f2b]
|
|
92
|
+
- Updated dependencies [fd11d20]
|
|
93
|
+
- Updated dependencies [3418c55]
|
|
94
|
+
- Updated dependencies [fd11d20]
|
|
95
|
+
- Updated dependencies [d51dbb3]
|
|
96
|
+
- Updated dependencies [f267c2f]
|
|
97
|
+
- Updated dependencies [4a06057]
|
|
98
|
+
- Updated dependencies [f267c2f]
|
|
99
|
+
- Updated dependencies [1bfc1c1]
|
|
100
|
+
- Updated dependencies [f267c2f]
|
|
101
|
+
- Updated dependencies [f267c2f]
|
|
102
|
+
- Updated dependencies [1ef55ac]
|
|
103
|
+
- Updated dependencies [b227d22]
|
|
104
|
+
- Updated dependencies [05bbfdf]
|
|
105
|
+
- Updated dependencies [3fc6f2b]
|
|
106
|
+
- Updated dependencies [2c92243]
|
|
107
|
+
- Updated dependencies [f267c2f]
|
|
108
|
+
- Updated dependencies [b227d22]
|
|
109
|
+
- Updated dependencies [2c92243]
|
|
110
|
+
- @velajs/vela@1.31.0
|
|
111
|
+
- @velajs/feature-flags@1.31.0
|
|
112
|
+
- @velajs/storage@1.31.0
|
|
113
|
+
- @velajs/testing@1.31.0
|
|
114
|
+
|
|
3
115
|
## 1.30.0
|
|
4
116
|
|
|
5
117
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -40,8 +40,17 @@ class AppModule {}
|
|
|
40
40
|
export default createCloudflareWorker(AppModule);
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
-
The worker exposes `fetch`, `queue`, and `scheduled
|
|
44
|
-
|
|
43
|
+
The worker exposes `fetch`, `queue`, and `scheduled`, and carries a
|
|
44
|
+
descriptor under the symbol key `CLOUDFLARE_WORKER`
|
|
45
|
+
(`Symbol.for('vela.cloudflare.worker')`), which the platform ignores and which
|
|
46
|
+
an entry adding handlers keeps (`export default { ...worker, email }`): the
|
|
47
|
+
root module, the options, and
|
|
48
|
+
`createOptions(env)`/`createApplication(env)`, which build the application
|
|
49
|
+
exactly as the Worker does, short of the `configure(app, env)` hook, which
|
|
50
|
+
receives the Workers application. `@velajs/cli` loads the Worker entry and builds its
|
|
51
|
+
application from it, so a project needs no `vela.config`, and
|
|
52
|
+
`@velajs/cloudflare/testing` builds test applications from the same options.
|
|
53
|
+
Its first event builds an application with that event's environment. Concurrent events for the same
|
|
45
54
|
environment object share construction. Different environment objects receive
|
|
46
55
|
separate applications, including separate providers, lifecycle state, and live
|
|
47
56
|
drivers. A failed construction is evicted and the next event retries.
|
|
@@ -80,29 +89,75 @@ factories that inject `ENV` rather than capturing them in module options.
|
|
|
80
89
|
Providers with request scope still rebuild per HTTP request or queue/cron dispatch.
|
|
81
90
|
Do not retain request objects or authentication state in singleton providers.
|
|
82
91
|
|
|
83
|
-
|
|
92
|
+
Request middleware belongs in modules: a consumer middleware class resolves
|
|
93
|
+
through dependency injection, so it can inject `ENV` like any provider.
|
|
84
94
|
|
|
85
95
|
```ts
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
96
|
+
import {
|
|
97
|
+
InjectEnv,
|
|
98
|
+
Injectable,
|
|
99
|
+
Module,
|
|
100
|
+
type MiddlewareConsumer,
|
|
101
|
+
type NestMiddleware,
|
|
102
|
+
type NestModule,
|
|
103
|
+
type VelaContext,
|
|
104
|
+
type VelaEnv,
|
|
105
|
+
} from '@velajs/vela';
|
|
106
|
+
|
|
107
|
+
@Injectable()
|
|
108
|
+
class ServiceHeader implements NestMiddleware {
|
|
109
|
+
constructor(@InjectEnv() private readonly env: VelaEnv) {}
|
|
110
|
+
async use(context: VelaContext, next: () => Promise<void>) {
|
|
111
|
+
context.header('x-service', this.env.SERVICE_NAME);
|
|
91
112
|
await next();
|
|
92
|
-
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
@Module({ providers: [ServiceHeader] })
|
|
117
|
+
export class AppModule implements NestModule {
|
|
118
|
+
configure(consumer: MiddlewareConsumer) {
|
|
119
|
+
consumer.apply(ServiceHeader).forRoutes('*');
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`createCloudflareWorker(AppModule, { configure })` finishes each application's
|
|
125
|
+
HTTP surface, for example with extra Hono routes, once per environment. It runs
|
|
126
|
+
after the application is built and before any event reaches it, including
|
|
127
|
+
concurrent cold events; a throw fails that construction and the next event
|
|
128
|
+
retries. It must be synchronous and do no I/O (a returned promise fails the
|
|
129
|
+
construction):
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
export default createCloudflareWorker(AppModule, {
|
|
133
|
+
configure(app, env) {
|
|
134
|
+
app.getHonoApp().get('/version', (c) => c.text(env.SERVICE_VERSION));
|
|
135
|
+
},
|
|
93
136
|
});
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Enable CORS as in Nest, with the `cors` option or `app.enableCors()` inside
|
|
140
|
+
`configure`; Hono's `cors` middleware then answers preflights ahead of every
|
|
141
|
+
route and guard:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
export default createCloudflareWorker(AppModule, { cors: { origin: ['https://app.example.com'] } });
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
For explicit construction inside a platform event:
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
const app = await createCloudflareApp(AppModule, { env, globalPrefix: '/api' });
|
|
94
151
|
const bindings = app.get(ENV); // VelaEnv
|
|
95
152
|
return app.fetch(request, env, executionContext);
|
|
96
153
|
```
|
|
97
154
|
|
|
98
155
|
`env` is registered as `ENV` before provider factories and lifecycle hooks.
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
the underlying Hono app. Internal `ctx.run` reentry retains the application's
|
|
105
|
-
environment.
|
|
156
|
+
Referencing a binding is safe during construction; platform I/O must still
|
|
157
|
+
happen inside a Workers event or Durable Object context. An explicitly built
|
|
158
|
+
application rejects requests or events carrying another environment object,
|
|
159
|
+
including calls through the underlying Hono app. Internal `ctx.run` reentry
|
|
160
|
+
retains the application's environment.
|
|
106
161
|
|
|
107
162
|
`cloudflareAdapter({ env })` provides the same bootstrap and request contract
|
|
108
163
|
when composing `VelaFactory.create` directly. `createCloudflareWorker` and
|
|
@@ -291,35 +346,19 @@ native bindings and live invalidation capabilities as HTTP. See
|
|
|
291
346
|
|
|
292
347
|
## WebSockets, live queries, and Durable Objects
|
|
293
348
|
|
|
349
|
+
Import the core modules; the Cloudflare adapter wires them to Durable Objects.
|
|
294
350
|
Use the native Durable Object entrypoint only in your Worker entry file:
|
|
295
351
|
|
|
296
352
|
```ts
|
|
297
|
-
import {
|
|
353
|
+
import { Module } from '@velajs/vela';
|
|
298
354
|
import { LiveModule } from '@velajs/vela/live';
|
|
299
|
-
import {
|
|
300
|
-
|
|
301
|
-
createCloudflareWorker,
|
|
302
|
-
durableObjectCursorLog,
|
|
303
|
-
durableObjectLive,
|
|
304
|
-
} from '@velajs/cloudflare';
|
|
355
|
+
import { WebSocketModule } from '@velajs/vela/websocket';
|
|
356
|
+
import { createCloudflareWorker } from '@velajs/cloudflare';
|
|
305
357
|
import { VelaWebSocketDurableObject } from '@velajs/cloudflare/durable-objects';
|
|
306
358
|
|
|
307
359
|
@Module({
|
|
308
|
-
imports: [
|
|
309
|
-
|
|
310
|
-
LiveModule.forRootAsync({
|
|
311
|
-
// ROOMS is typed DurableObjectNamespace<Room> by `wrangler types`.
|
|
312
|
-
inject: [ENV],
|
|
313
|
-
useFactory: (env) => ({
|
|
314
|
-
driver: () => durableObjectLive({
|
|
315
|
-
namespace: env.ROOMS,
|
|
316
|
-
gatewayPath: '/rooms/:room/ws',
|
|
317
|
-
}),
|
|
318
|
-
log: () => durableObjectCursorLog(),
|
|
319
|
-
}),
|
|
320
|
-
}),
|
|
321
|
-
],
|
|
322
|
-
// Add your @WebSocketGateway and @LiveResolver classes here.
|
|
360
|
+
imports: [WebSocketModule.forRoot(), LiveModule.forRoot()],
|
|
361
|
+
// Your @WebSocketGateway({ binding: 'ROOMS', ... }) and @LiveResolver classes.
|
|
323
362
|
providers: [],
|
|
324
363
|
})
|
|
325
364
|
class RoomModule {}
|
|
@@ -328,6 +367,32 @@ export class Room extends VelaWebSocketDurableObject(RoomModule) {}
|
|
|
328
367
|
export default createCloudflareWorker(RoomModule);
|
|
329
368
|
```
|
|
330
369
|
|
|
370
|
+
`cloudflareAdapter` registers the platform as the global `WS_TRANSPORT` and
|
|
371
|
+
`LIVE_PLATFORM` tokens before modules load; it never replaces module providers.
|
|
372
|
+
In the Worker, `WebSocketModule` serves an upgrade route for each gateway that
|
|
373
|
+
names a `binding` and forwards the authenticated upgrade to that room's Durable
|
|
374
|
+
Object. The Worker keeps no sockets, so a gateway's `@WebSocketServer()`
|
|
375
|
+
refuses pushes there; `Gateways` from `@velajs/vela/websocket`
|
|
376
|
+
(`gateways.of(ChatGateway).to(room).emit(event, data)`) calls the `broadcast`
|
|
377
|
+
RPC of the gateway + room Durable Object, read by the gateway's `binding` from
|
|
378
|
+
`ENV`. Inside a Durable Object, a `Gateways` push to its own room reaches its
|
|
379
|
+
sockets and a push to another room goes to that room's object. `LiveModule`
|
|
380
|
+
sends invalidations to the room Durable
|
|
381
|
+
Object of the single binding-backed gateway, reading the namespace from `ENV`
|
|
382
|
+
when first needed; with several, the first invalidation reports the ambiguity,
|
|
383
|
+
and `driver: () => durableObjectLive({ gatewayPath })` (or `{ binding }`)
|
|
384
|
+
chooses. A gateway without `roomParam` has one room Durable Object, named by
|
|
385
|
+
its path, so its invalidations and inspections go there whatever room they
|
|
386
|
+
name. Inside the Durable Object, the gateway server broadcasts to its
|
|
387
|
+
hibernatable sockets, invalidations apply locally, and the cursor log is a
|
|
388
|
+
`DoCursorLog` in the object's SQLite storage (in memory when the class is not
|
|
389
|
+
SQLite-backed). `LiveInspector` reads a named room through the same gateway
|
|
390
|
+
binding with the object's `inspectLive` RPC, which
|
|
391
|
+
Studio's `livePanel({ rooms })` uses. The same `RoomModule` serves the Worker, every Durable Object
|
|
392
|
+
and a node host. Without `WebSocketModule`, the Worker mounts no upgrade route,
|
|
393
|
+
and the adapter reports each binding-backed gateway through the diagnostics
|
|
394
|
+
policy.
|
|
395
|
+
|
|
331
396
|
Declare gateways with `@WebSocketGateway({ path, roomParam, binding, ... })` and
|
|
332
397
|
configure origins and upgrade authentication for your application.
|
|
333
398
|
`authenticator` names an `UpgradeAuthenticator` class that the Worker resolves
|
|
@@ -341,57 +406,179 @@ routing consumes the core trusted request identity, checks conflicts with the
|
|
|
341
406
|
upgrade credential, and forwards issuer, subject, tenant, and expiry to the DO.
|
|
342
407
|
Client-supplied internal identity headers are stripped before authorization.
|
|
343
408
|
|
|
344
|
-
Declare live query
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
409
|
+
Declare each live query once with `defineLiveQuery({ name, args, result })` from
|
|
410
|
+
`@velajs/vela/live`. Both schemas accept a parser object such as a Zod schema.
|
|
411
|
+
Use `@LiveQuery(definition, { tags: ['todos'] })` on the resolver and share the
|
|
412
|
+
definition with its client. Restored hibernation arguments
|
|
348
413
|
and final query results use the same validation boundary.
|
|
349
414
|
|
|
350
415
|
Each application constructs its own driver and cursor log. Workers send
|
|
351
|
-
invalidations through the
|
|
416
|
+
invalidations through the gateway's DO namespace; the DO uses its own live engine
|
|
352
417
|
and SQLite cursor log. Configure the class in Wrangler `new_sqlite_classes` to
|
|
353
418
|
retain cursor/epoch state across hibernation. Hibernated subscriptions are
|
|
354
419
|
restored on wake; the shared live protocol handles resume or snapshot fallback.
|
|
355
420
|
|
|
356
421
|
The DO class preserves its RPC types, so `DurableObjectNamespace<Room>` exposes
|
|
357
|
-
`invalidate`, `broadcast`, and PITR methods without assertions.
|
|
358
|
-
`liveInvalidateToRoom
|
|
422
|
+
`invalidate`, `broadcast`, `inspectLive`, and PITR methods without assertions.
|
|
423
|
+
`liveInvalidateToRoom` and the PITR helpers remain available from the root
|
|
359
424
|
package. `VelaNonceDurableObject` is exported from `/durable-objects`; its
|
|
360
425
|
`durableObjectNonceStore` factory remains on the root entrypoint.
|
|
361
426
|
|
|
362
427
|
The root package contains no runtime `cloudflare:workers` import and can be
|
|
363
428
|
loaded by Node tooling. Native classes belong to `/durable-objects`.
|
|
364
429
|
|
|
430
|
+
## Bindings by name
|
|
431
|
+
|
|
432
|
+
Module options name a binding instead of holding it. `kv`, `r2`, `d1`,
|
|
433
|
+
`queue`, `durableObject` and `rateLimit` each take `{ binding }`, the name
|
|
434
|
+
declared in the Wrangler configuration, and read nothing when declared: calling
|
|
435
|
+
the reference with an application's `ENV` returns the typed native binding, or
|
|
436
|
+
fails naming the binding and the Wrangler key that declares it
|
|
437
|
+
(`ENV.UPLOADS is not set: declare the R2 bucket binding 'UPLOADS' under r2_buckets …`).
|
|
438
|
+
The drivers and stores below are built on them, so one static module graph
|
|
439
|
+
serves every environment.
|
|
440
|
+
|
|
441
|
+
## Rate limiting
|
|
442
|
+
|
|
443
|
+
`ThrottlerModule` from `@velajs/vela/throttler` counts through Workers Rate
|
|
444
|
+
Limiting bindings named in `rateLimitStore`:
|
|
445
|
+
|
|
446
|
+
```ts
|
|
447
|
+
import { ThrottlerModule } from '@velajs/vela/throttler';
|
|
448
|
+
import { rateLimitStore } from '@velajs/cloudflare';
|
|
449
|
+
|
|
450
|
+
ThrottlerModule.forRoot({
|
|
451
|
+
throttlers: [
|
|
452
|
+
{ name: 'burst', ttl: 10_000, limit: 20 },
|
|
453
|
+
{ name: 'sustained', ttl: 60_000, limit: 100 },
|
|
454
|
+
],
|
|
455
|
+
storage: rateLimitStore({ binding: { burst: 'BURST_LIMITER', sustained: 'API_LIMITER' } }),
|
|
456
|
+
});
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
`rateLimitStore({ binding: 'API_LIMITER' })` serves every throttler from one
|
|
460
|
+
binding. Each binding's `simple.limit` and `simple.period` in the Wrangler
|
|
461
|
+
`ratelimits` block must equal its throttler's `limit` and `ttl` (10 or 60
|
|
462
|
+
seconds): the platform enforces them, so a `@Throttle()` override that changes
|
|
463
|
+
them fails at bootstrap, and one binding serves only throttlers that share a
|
|
464
|
+
`limit` and `ttl`. The store checks the declared throttlers at bootstrap: another
|
|
465
|
+
period, different values on one binding, or a throttler the per-name map leaves
|
|
466
|
+
out fails the application before any binding is charged. The platform exposes no
|
|
467
|
+
counters, so responses carry no `X-RateLimit-Remaining`, and no reset time, so
|
|
468
|
+
`X-RateLimit-Reset` and `Retry-After` report the configured period.
|
|
469
|
+
|
|
470
|
+
Workers Rate Limiting counts per Cloudflare location, and its counters are
|
|
471
|
+
eventually consistent: limits are approximate, not a global or exact quota. A
|
|
472
|
+
client spread across locations can exceed them. For strict limits such as login
|
|
473
|
+
attempts per account, implement a `ThrottlerStore` that counts in a Durable
|
|
474
|
+
Object.
|
|
475
|
+
|
|
365
476
|
## R2 storage and caches
|
|
366
477
|
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
1.x Worker HMAC proxy API; its signed routes differ from provider-signed URLs.
|
|
478
|
+
`StorageModule` from [`@velajs/storage`](../storage/README.md#storage-on-cloudflare-workers)
|
|
479
|
+
is the one file-storage module. Its native R2 driver comes from the
|
|
480
|
+
`@velajs/cloudflare/storage` subpath:
|
|
371
481
|
|
|
372
|
-
|
|
482
|
+
```ts
|
|
483
|
+
import { StorageModule } from '@velajs/storage';
|
|
484
|
+
import { r2Storage } from '@velajs/cloudflare/storage';
|
|
485
|
+
|
|
486
|
+
StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) });
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
The bucket is read from each application's `ENV` on its first storage
|
|
490
|
+
operation. The native binding cannot presign; use `publicBaseUrl`, the storage
|
|
491
|
+
HTTP controller with `http: { download: 'proxy' }`, or the R2 HTTP/hybrid
|
|
492
|
+
drivers for provider-signed URLs.
|
|
493
|
+
|
|
494
|
+
`CacheModule` from `@velajs/vela/cache` takes its KV stores by binding name:
|
|
373
495
|
|
|
374
496
|
```ts
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
}),
|
|
497
|
+
import { CacheModule } from '@velajs/vela/cache';
|
|
498
|
+
import { kvCache, kvCacheInvalidation } from '@velajs/cloudflare';
|
|
499
|
+
|
|
500
|
+
CacheModule.forRoot({
|
|
501
|
+
namespace: 'catalog-v1',
|
|
502
|
+
scope: trustedCacheScope,
|
|
503
|
+
store: kvCache({ binding: 'CACHE' }),
|
|
504
|
+
invalidation: kvCacheInvalidation({ binding: 'CACHE_GENERATIONS' }),
|
|
383
505
|
});
|
|
384
506
|
```
|
|
385
507
|
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
the
|
|
508
|
+
Each operation reads the namespace from the application's `ENV`. A binding that
|
|
509
|
+
is not declared fails the operation with an error naming it and
|
|
510
|
+
`kv_namespaces`; the cache treats that as a miss and sends the error to the
|
|
511
|
+
application's error reporter (edge `'cache'`).
|
|
512
|
+
|
|
513
|
+
`KVCacheStore` and `KVCacheInvalidationStore` take a namespace or a function
|
|
514
|
+
returning one, for composition such as
|
|
515
|
+
`store: (env) => new TieredCacheStore([new MemoryCacheStore(), new KVCacheStore(env.CACHE)])`.
|
|
516
|
+
Construct `KvFlagDriver` with a native namespace: `new KvFlagDriver(env.CACHE)`.
|
|
517
|
+
Cache reads and object-valued flag reads return `unknown`; validate them with an
|
|
518
|
+
application parser (`cache.scope(scope).getParsed(key, parser)`).
|
|
519
|
+
|
|
520
|
+
## Testing Worker handlers
|
|
521
|
+
|
|
522
|
+
`@velajs/cloudflare/testing` runs inside the Workers Vitest pool
|
|
523
|
+
(`@cloudflare/vitest-plugin`) and needs `@velajs/testing`.
|
|
524
|
+
`createTestingWorker(AppModule, { env?, overrides?, ...workerOptions })` builds
|
|
525
|
+
the module as `createCloudflareWorker(AppModule, workerOptions)` does (its
|
|
526
|
+
adapters, then its `configure(app, env)` hook), through
|
|
527
|
+
`Test.createTestingModule()`, and drives the Worker's handlers:
|
|
528
|
+
|
|
529
|
+
```ts
|
|
530
|
+
import { env } from 'cloudflare:workers';
|
|
531
|
+
import { createTestingWorker, queueJob } from '@velajs/cloudflare/testing';
|
|
532
|
+
import { expect, it } from 'vitest';
|
|
533
|
+
|
|
534
|
+
it('processes a created todo', async () => {
|
|
535
|
+
const worker = await createTestingWorker(AppModule, {
|
|
536
|
+
env,
|
|
537
|
+
overrides: (module) =>
|
|
538
|
+
module
|
|
539
|
+
.overrideModule(NotificationsModule)
|
|
540
|
+
.useModule(SilentNotifications)
|
|
541
|
+
.useMocker((token) => (token === Notifier ? fakeNotifier : undefined)),
|
|
542
|
+
});
|
|
543
|
+
try {
|
|
544
|
+
const created = await worker.fetch('/todos', {
|
|
545
|
+
method: 'POST',
|
|
546
|
+
headers: { 'content-type': 'application/json' },
|
|
547
|
+
body: JSON.stringify({ title: 'Write tests' }),
|
|
548
|
+
});
|
|
549
|
+
expect(created.ok).toBe(true);
|
|
550
|
+
|
|
551
|
+
const result = await worker.queue('todo-events', [
|
|
552
|
+
queueJob('todo-events', todoCreated, { id: '1', title: 'Write tests' }),
|
|
553
|
+
]);
|
|
554
|
+
expect(result.outcome).toBe('ok');
|
|
555
|
+
expect(result.explicitAcks).toHaveLength(1);
|
|
556
|
+
|
|
557
|
+
await worker.scheduled('0 3 * * *');
|
|
558
|
+
} finally {
|
|
559
|
+
await worker.close();
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
```
|
|
389
563
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
564
|
+
- `env` defaults to the pool's `env` from `cloudflare:workers`; every event
|
|
565
|
+
carries it, so the Cloudflare adapter accepts the requests.
|
|
566
|
+
- `overrides` receives the `@velajs/testing` builder: `overrideProvider()`,
|
|
567
|
+
`overrideGuard()` and the other enhancer overrides, `overrideModule().useModule()`
|
|
568
|
+
and `useMocker()`. `worker.module` is the compiled `TestingModule`; its
|
|
569
|
+
`fetch()` and `http` client send the same `env` as `c.env`.
|
|
570
|
+
- `fetch(input, init?)` resolves a path against `http://localhost`.
|
|
571
|
+
- `queue(physicalQueue, messages)` delivers one batch built with `cloudflare:test`'s
|
|
572
|
+
`createMessageBatch()` and returns its `getQueueResult()` plus `outcome`
|
|
573
|
+
(`'exception'`, with `error`, when the handler rejected: Cloudflare would retry
|
|
574
|
+
the unacknowledged messages). `queueJob(queue, jobOrName, data, { id?, attempts? })`
|
|
575
|
+
builds the envelope `QueueClient.add()` sends.
|
|
576
|
+
- `scheduled(cron, { scheduledTime? })` fires a cron trigger with
|
|
577
|
+
`createScheduledController()`, and rejects when no `@Cron` job declares `cron`.
|
|
578
|
+
- `close()` cancels response bodies a test never read, waits for background
|
|
579
|
+
work (`waitUntil`) and closes the application.
|
|
580
|
+
|
|
581
|
+
The subpath is not part of any Worker bundle: import it from tests only.
|
|
395
582
|
|
|
396
583
|
## Development
|
|
397
584
|
|
|
@@ -407,13 +594,12 @@ The Workers suite uses real KV, D1, R2, WebSockets, SQLite Durable Objects, and
|
|
|
407
594
|
cold event dispatch. See the [security guide](https://github.com/velajs/vela/blob/main/docs/cloudflare-security.md) for trusted identity,
|
|
408
595
|
URL signing, and WebSocket boundaries.
|
|
409
596
|
|
|
410
|
-
###
|
|
597
|
+
### KV caches
|
|
411
598
|
|
|
412
|
-
`
|
|
413
|
-
`TieredCacheStore`. The adapter retains absolute logical expiry in
|
|
414
|
-
KV's minimum physical retention does not extend the requested TTL.
|
|
415
|
-
|
|
416
|
-
|
|
599
|
+
`kvCache` works directly as `CacheModule`'s store or, through `KVCacheStore`, as
|
|
600
|
+
a tier beneath `TieredCacheStore`. The adapter retains absolute logical expiry in
|
|
601
|
+
KV metadata; KV's minimum physical retention does not extend the requested TTL.
|
|
602
|
+
For tags and scoped invalidation, configure `kvCacheInvalidation` with a separate
|
|
603
|
+
dedicated KV namespace without TTLs or lifecycle cleanup. It is eventually
|
|
417
604
|
consistent, including concurrent writes and cached negative reads, and does not
|
|
418
|
-
promise globally strong invalidation.
|
|
419
|
-
factory. See the [caching guide](../../docs/caching.md).
|
|
605
|
+
promise globally strong invalidation. See the [caching guide](../../docs/caching.md).
|