Skip to content

Commit 8bb44e1

Browse files
committed
feat: add server-side room actions
Rooms declare `actions` in `defineRoom()` and other server code calls them through `getRoom()` from `void/ws/server`. Actions run inside the room's Durable Object over RPC, so filtering stays local instead of crossing the boundary as a callback, and internal helpers stay `#` methods off that surface.
1 parent 220aa27 commit 8bb44e1

18 files changed

Lines changed: 1359 additions & 34 deletions

‎docs/guide/websockets.md‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ export default defineRoom({
9191
- `ctx.connection.close(code?, reason?)`
9292
- `ctx.connection.setState(data)`
9393

94+
Add `actions` when other server code should reach the room. See [Server-side actions](#server-side-actions).
95+
9496
## `defineWebSocket()`
9597

9698
Use `defineWebSocket()` when each connection is handled independently instead of as a shared room.
@@ -156,7 +158,76 @@ When Void auth is enabled, every WebSocket hook receives the current user as `ct
156158

157159
Connections from another origin are anonymous unless that origin is in your auth `trustedOrigins`. If you read your own cookies from `ctx.request` in `onBeforeConnect`, check its `Origin` header yourself.
158160

159-
`ctx.user` is resolved when the socket connects and stays the same for that connection, even if the user later signs out or the session is revoked. For actions that must respect a ban or role change, re-check your own records in `onMessage` and close the connection with `ctx.connection.close()` in rooms or `ctx.socket.close()` in `defineWebSocket()`.
161+
`ctx.user` is resolved when the socket connects and stays the same for that connection, even if the user later signs out or the session is revoked. For actions that must respect a ban or role change, re-check your own records in `onMessage` and close the connection with `ctx.connection.close()` in rooms or `ctx.socket.close()` in `defineWebSocket()`. To close idle sockets as soon as a session is revoked, declare a [room action](#server-side-actions) and call it from the code that revokes the session.
162+
163+
## Server-side actions
164+
165+
A room can declare named actions that other server code calls with typed arguments. An action runs inside the room's Durable Object, so it can close connections or broadcast without waiting for a client frame.
166+
167+
```ts
168+
// routes/relay/[accountId].ws.ts
169+
import * as v from 'valibot';
170+
import { getSession } from 'void/auth';
171+
import { defineRoom } from 'void/ws';
172+
173+
const ClientMessage = v.object({ type: v.literal('relay.ping') });
174+
const ServerMessage = v.object({ type: v.literal('relay.message'), text: v.string() });
175+
176+
export default defineRoom({
177+
messages: { client: ClientMessage, server: ServerMessage },
178+
onConnect(ctx) {
179+
// The id comes from the authenticated session, never from client input.
180+
const session = getSession()?.session;
181+
if (session) {
182+
ctx.connection.setState({ sessionId: session.id });
183+
}
184+
},
185+
actions: {
186+
async revokeSession(ctx, sessionId: string, code: number) {
187+
let closed = 0;
188+
for (const connection of ctx.room.getConnections()) {
189+
const state = connection.state as { sessionId?: string } | undefined;
190+
if (state?.sessionId !== sessionId) continue;
191+
connection.close(code, 'session revoked');
192+
closed += 1;
193+
}
194+
return { closed };
195+
},
196+
async announce(ctx, text: string) {
197+
await ctx.room.broadcast({ type: 'relay.message', text });
198+
},
199+
},
200+
});
201+
```
202+
203+
Call an action from a route handler, an auth hook, a queue consumer or a cron job with `getRoom()` from `void/ws/server`:
204+
205+
```ts
206+
import { getRoom } from 'void/ws/server';
207+
208+
// Better Auth's databaseHooks.session.delete.after, or any other server code
209+
const room = getRoom('/relay/[accountId]', { params: { accountId } });
210+
const { closed } = await room.actions.revokeSession(session.id, 4001);
211+
```
212+
213+
`getRoom()` addresses the same instance `connect()` reaches. Pass the route pattern and the same params, and a custom `key` is applied too.
214+
215+
Match connections on server-verified state. A session id read from the URL, a query string or a client message can be any value a client sends, so the revocation would close the wrong sockets. Derive the id from `getSession()` or your own records, store it in `onConnect`, and pass that same id from the code that revokes it.
216+
217+
- Annotate each action parameter. Arguments and results are typed from the definition, and an unannotated parameter is `never`.
218+
- Actions receive `ctx.id`, `ctx.params`, `ctx.env`, `ctx.storage` and `ctx.room`. There is no `ctx.request` or `ctx.user`: other server code is the caller, so authorize the decision where you make it.
219+
- `ctx.room.broadcast()` and connection `send()` accept any event inside an action. The server message schema still validates it at runtime.
220+
- Arguments cross a Durable Object boundary, so pass structured-clone data, not callbacks or class instances.
221+
- An unknown action name or a handler error rejects the call. An unknown route, a `defineWebSocket()` route or a missing param throws before any Durable Object is contacted.
222+
- Do not call an action from the same room's own hooks. Use `ctx.room` there; a call from inside the room waits on the room itself.
223+
224+
Actions are not an endpoint. They run over Durable Object RPC from your Worker, so a browser request or a WebSocket message cannot call one.
225+
226+
`getRoom()` reads the current runtime env, so it works in any handler Void runs. Outside one, pass the bindings object you already hold:
227+
228+
```ts
229+
getRoom('/relay/[accountId]', { params: { accountId }, env: bindings });
230+
```
160231

161232
## Hooks
162233

‎docs/reference/api.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ Import Void's app-facing APIs from these paths:
4242
| `void/auth` | `defineAuth`, `getUser`, `getSession`, `requireAuth`, `AuthUser`, `AuthSession`, `AuthState` |
4343
| `void/client` | `fetch`, `fetchStream`, `FetchError`, `auth`, `createAuthClient`, `AuthUser`, `AuthSession`, `AuthState` |
4444
| `void/client/{framework}` | Same as `void/client`, with framework-specific Better Auth clients for `react`, `vue`, `svelte`, and `solid` |
45-
| `void/ws` | `defineRoom`, `defineWebSocket`, `connect`, WebSocket context and connection types |
45+
| `void/ws` | `defineRoom`, `defineWebSocket`, `connect`, WebSocket context, connection and action types |
46+
| `void/ws/server` | `getRoom`, `RoomHandle`, `RoomOptions`, `RoomPath`. Server-only: call room actions from routes, auth hooks, queues and cron jobs. |
4647
| `void/durable` | `defineDurableState`, `defineDurableObject`, typed state/RPC/context/migration types |
4748
| `void/sse` | `eventStream`, `formatSse`, `formatSseText`, `getLastEventId`, `SseStreamClosedError`, SSE message and stream types |
4849
| `void/sse/client` | `connectEventStream`, browser `EventSource` wrapper types |

‎packages/void/AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ generated entries must preserve the module-boundary rules below.
144144
- **Reserved `__VOID_*` names**: `envSchemaPlugin.config` (every mode, with or without `env.ts`) and `void env check` reject `__VOID_*` names in the root `.env` or declared in `env.ts`. Do not try to strip them from dev `vars` instead: Wrangler reads `.env` itself and writes it over `vars`, so a strip cannot be enforced. Manual trigger auth is a compile-time literal (`__VOID_SERVE` from `CompileOptions.dev`, false in builds and `vite preview`): dev accepts only `x-void-dev-trigger`, builds use the proxy token or build key. Never key it on `import.meta.env.DEV`, which is true in a `NODE_ENV=development` build.
145145
- **Typed Durable State convention**: each default-exported `defineDurableState()` definition in `durable-objects/*.ts` becomes a filename-derived binding and worker class (`shopping-cart.ts` → `SHOPPING_CART` / `ShoppingCartDurableObject`). The generated entry calls the internal `__bind()` hook so named imports can use `State.get(name)` without touching `c.env`, exports `State.class`, and emits a stable `new_sqlite_classes` migration. `syncWranglerDurableObjects()` persists bindings and append-only class migration history in `void.lock.json` through the generated Cloudflare config; never regenerate migration order solely from the current sorted files. The generated class extends `DurableObject` from `cloudflare:workers` so namespace stubs expose real RPC methods; runtime state and helpers use JavaScript private fields and methods. Runtime operations are serialized and persisted after successful typed RPC, `fetch`, or `alarm` handlers; versioned value migrations run on load. This is native-Void + Cloudflare only and is supported by direct Cloudflare deploys. Typed `*.ws.ts` routes likewise use SQLite-backed classes; their root-config sync uses the comment-preserving writer, retains legacy `new_classes` histories, and appends a new migration tag only for new classes.
146146
- **Persistent resource names**: optional static `name` on Durable State and WebSocket definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format.
147+
- **Server room actions**: `defineRoom({ actions })` keeps each action's declared parameters and return type (`RoomActions` accepts any annotated parameter list, so unannotated parameters become `never`). Codegen adds `actions` to `WebSocketRouteMap` for room routes only, and `getRoom()` from `void/ws/server` resolves the same `bindingName` plus `buildWebSocketInstanceId()` key as `forwardWebSocketRequest()`. The generated route table registers route metadata once, after attaching `key`, through `__registerWebSocketRoutes`; the map lives on `globalThis` because dev can evaluate the module twice. Dispatch is Durable Object RPC (`__voidRoomAction`), so the WebSocket DO class extends `DurableObject` from `cloudflare:workers`; its own helpers are `#` methods so they stay off that RPC surface, and actions are never reachable from `fetch`, `webSocketMessage`, or client HTTP.
147148
- **Journal coherence invariant**: `db/migrations/*.sql` and `db/migrations/meta/_journal.json` must stay in sync — every `.sql` file has a matching journal entry (by `tag`) and vice versa. `assertJournalCoherence` in `src/migrations/validate.ts` is the gate, called from `deploy`, `db status`, `db migrate`, and `db reset`. The two CLI commands that mutate migration state — `void gen migration` and `void db rename-migrations` — are responsible for keeping the journal coherent themselves: when the journal has entries, the first delegates to `drizzle-kit generate --custom --name <name>`, which writes the empty `.sql`, appends the journal entry, and writes a snapshot of the current schema (it refuses if the last entry's snapshot is missing and byte-restores the journal if drizzle-kit fails); with no journal entries it writes a plain timestamped `.sql`. The second rewrites `tag` values alongside the file renames and also renames the matching `meta/<prefix>_snapshot.json` (with byte-level rollback on failure). Drift will fail loudly before touching any remote DB. This prevents an orphan scaffolded `.sql` file from half-applying against D1 and blocking later deploys.
148149

149150
- **D1 migration recovery**: Publish the lock and attempt record atomically. Stable attempts register in `_void_migration_fences`; every migration and legacy tracking-table upgrade checks ownership inside its D1 batch. Recovery revokes ownership before reading confirmed migrations, so a resumed executor cannot write after a replacement starts. Duplicate submissions only report progress. Never steal a missing-record lock or interrupt an older/raw-exec attempt without fencing: its owner may still be running. Such interrupted legacy attempts require operator verification that the executor has stopped before manually recovering the database lock.

‎packages/void/package.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,11 @@
154154
"import": "./dist/runtime/ws/index.mjs",
155155
"require": "./dist/runtime/ws/index.mjs"
156156
},
157+
"./ws/server": {
158+
"types": "./dist/runtime/ws/room.d.mts",
159+
"import": "./dist/runtime/ws/room.mjs",
160+
"require": "./dist/runtime/ws/room.mjs"
161+
},
157162
"./db": {
158163
"types": "./dist/runtime/db/index.d.mts",
159164
"import": "./dist/runtime/db/index.mjs",

‎packages/void/src/codegen/route-types.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,14 @@ export function generateRouteTypes(
404404
lines.push(
405405
` server: ${imports.map((source) => `ExtractOutput<${source}["server"]>`).join(' | ')};`,
406406
);
407+
const roomSources = sources.filter((route) => route.mode === 'room');
408+
if (roomSources.length > 0) {
409+
const actions = roomSources.map((route) => {
410+
const importPath = relative(outDir, `${routesDir}/${route.filePath}`);
411+
return `NonNullable<(typeof import(${JSON.stringify(importPath)}))["default"]["actions"]>`;
412+
});
413+
lines.push(` actions: ${actions.join(' | ')};`);
414+
}
407415
lines.push(' };');
408416
legacyRouteAlias(lines, 'WebSocketRouteMap', pattern);
409417
}

‎packages/void/src/router/compile.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ export function compileRouteTable(
228228
options.webSocketRuntimePath
229229
) {
230230
lines.push(
231-
`import { createWebSocketDurableObject as __createWebSocketDurableObject, createWebSocketTombstoneDurableObject as __createWebSocketTombstoneDurableObject, forwardWebSocketRequest as __forwardWebSocketRequest } from ${JSON.stringify(options.webSocketRuntimePath)};`,
231+
`import { createWebSocketDurableObject as __createWebSocketDurableObject, createWebSocketTombstoneDurableObject as __createWebSocketTombstoneDurableObject, forwardWebSocketRequest as __forwardWebSocketRequest, __registerWebSocketRoutes } from ${JSON.stringify(options.webSocketRuntimePath)};`,
232232
);
233233
}
234234
if (options.hasLive && options.liveRuntimePath) {
@@ -414,6 +414,7 @@ export function compileRouteTable(
414414
params: route.params,
415415
className: route.className,
416416
bindingName: route.bindingName,
417+
mode: route.mode,
417418
...(route.name !== undefined && { name: route.name }),
418419
},
419420
)}, ${auth ? '__voidAuthOptions' : 'undefined'}, ${auth ? '__resolveVoidAuthState' : 'undefined'});`,
@@ -427,6 +428,7 @@ export function compileRouteTable(
427428
params: route.params,
428429
className: route.className,
429430
bindingName: route.bindingName,
431+
mode: route.mode,
430432
...(route.name !== undefined && { name: route.name }),
431433
})),
432434
)};`,
@@ -436,6 +438,10 @@ export function compileRouteTable(
436438
for (let i = 0; i < webSockets.length; i++) {
437439
lines.push(`__voidWebSocketRoutes[${i}].key = websocket${i}.key;`);
438440
}
441+
if (webSockets.length > 0 && options.webSocketRuntimePath) {
442+
// Register after `key` is attached so getRoom() shares the client's addressing.
443+
lines.push('__registerWebSocketRoutes(__voidWebSocketRoutes);');
444+
}
439445
for (const className of options.webSocketTombstones ?? []) {
440446
lines.push(
441447
`export const ${className} = __createWebSocketTombstoneDurableObject(${JSON.stringify(className)});`,

0 commit comments

Comments
 (0)