Skip to content

feat(ws): add server-side room actions - #780

Open
0froq wants to merge 1 commit into
voidzero-dev:mainfrom
0froq:feat/room-server-actions
Open

0froq wants to merge 1 commit into
voidzero-dev:mainfrom
0froq:feat/room-server-actions

Conversation

@0froq

@0froq 0froq commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator

Fixes #689

Description

Let rooms declare named actions that other server code can call through getRoom() from void/ws/server.

An auth hook can pass a session ID to an action that closes matching connections inside the room. The filtering stays in the Durable Object rather than crossing the boundary as a callback. Action arguments and return values retain their declared types.

getRoom() uses the same room addressing as client connections, including route params and custom keys. Actions run over Durable Object RPC, not through an HTTP endpoint or client message. Internal helpers use JavaScript private methods so they are not exposed through RPC.

The server-only entry point stays separate from void/ws. Existing rooms without actions and defineWebSocket routes retain their behavior. The guide includes a session-revocation example using server-authenticated session IDs.

Current boundaries:

  • Authorization belongs in the calling server code. Action context has no request or user.
  • Arguments must be structured-cloneable.
  • Broadcast messages are schema-validated at runtime but are not statically typed inside actions yet.
  • Room hooks should use ctx.room directly instead of awaiting an RPC action on their own room.
  • then is reserved by the actions proxy to prevent accidental Promise assimilation.

Test

  • 309 focused unit and integration tests pass, including existing WebSocket and routing regressions.
  • Miniflare tests exercise the generated Worker, action dispatch, connection filtering, storage, broadcasts, cron and queue callers, and client/HTTP isolation.
  • Regression tests verify that internal helpers cannot be called over RPC and that awaiting the actions proxy does not dispatch an action. Both fail against the pre-fix implementation.
  • A temporary project checks getRoom() against actual generated route declarations, including invalid calls. The test uses the package's built declarations.
  • Package typecheck, lint and formatting checks pass.

The full suite has not passed locally. Earlier runs encountered missing Playwright browsers, an older Node version and missing generated configs; those failures were not compared against the base commit. Live Cloudflare deployment and the development server have not been verified.

@0froq
0froq requested a review from a team as a code owner November 11, 2026 04:24
@0froq

0froq commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

👁️‍🗨️ Review this pull request with grouped, summarized diffs at:
👉 https://pulls.review/gh/voidzero-dev/void/780?from=0froq

raw result

💭 analyzed by openai-compatible/opencode-go/deepseek-v4.1-flash
🕰️ 2026-11-16 05:54 UTC
🔗 head f1d0d81
🤖 automated by pulls.review

{
  "headSha": "f1d0d8117b3098cb6dc1f69f42dc1df45fd1ed75",
  "result": {
    "overallSummary": "Adds server-callable named actions to rooms: `defineRoom({ actions })` keeps each action's declared parameter and return types, and a new server-only entry point `void/ws/server` exposes `getRoom()` to call those actions over Durable Object RPC from routes, auth hooks, queues and crons. Codegen publishes the room's `actions` on `WebSocketRouteMap` and the generated route table registers route metadata so `getRoom()` addresses exactly the same instance a client's `connect()` reaches; the WebSocket DO now extends Cloudflare's `DurableObject` with all internal helpers as `#` skills so only the action RPC method is exposed.",
    "groups": [
      {
        "key": "room-actions-runtime",
        "label": "Room actions runtime",
        "summary": "The feature itself: `RoomActions`/`RoomActionContext` types plus a `defineRoom()` overload that preserves action signatures, a new `getRoom()` handle that resolves the binding and instance id exactly like `forwardWebSocketRequest()`, and RPC dispatch inside the Durable Object. The DO class now extends `DurableObject` from `cloudflare:workers` so RPC exists, with every other helper converted to `#`-private methods to keep them off that surface.",
        "category": "core",
        "filePaths": [
          "packages/void/src/runtime/ws/index.ts",
          "packages/void/src/runtime/ws/room.ts",
          "packages/void/src/runtime/ws/server.ts"
        ],
        "critical": true,
        "fileNotes": [
          {
            "path": "packages/void/src/runtime/ws/room.ts",
            "text": "`getRoom()` executes in the caller's Worker and only forwards `{ name, args, id, params }` to the stub; param validation and mode checks happen before any DO is contacted, so errors are thrown locally rather than as RPC failures."
          },
          {
            "path": "packages/void/src/runtime/ws/server.ts",
            "text": "Route metadata is stored on a `globalThis` symbol because dev can evaluate the module twice; `canonicalWebSocketPattern()` translates the public `[param]` / `[...param]` spelling to the router's compiled `:param` form for the lookup key."
          }
        ],
        "lineNotes": [
          {
            "path": "packages/void/src/runtime/ws/room.ts",
            "side": "additions",
            "line": 106,
            "text": "Returning `undefined` for `then` (and symbols) prevents `await room.actions` / `Promise.resolve(room.actions)` from dispatching an action named \"then\" with resolver callbacks that are not structured-cloneable."
          },
          {
            "path": "packages/void/src/runtime/ws/server.ts",
            "side": "additions",
            "line": 366,
            "text": "`Object.hasOwn` keeps inherited names like `constructor` and `toString` from resolving to a function and being invoked with the action context."
          }
        ]
      },
      {
        "key": "route-codegen",
        "label": "Route codegen & registration",
        "summary": "Generated declarations gain `actions` on `WebSocketRouteMap` for room routes only, and the compiled route table carries `mode` and registers the route array via `__registerWebSocketRoutes` after `key` is attached, which is what makes `getRoom()` and `connect()` share addressing.",
        "category": "core",
        "filePaths": [
          "packages/void/src/codegen/route-types.ts",
          "packages/void/src/router/compile.ts"
        ]
      },
      {
        "key": "package-entry",
        "label": "Package entry point",
        "summary": "Publishes `void/ws/server` as its own entry pointing at `dist/runtime/ws/room.*` and adds that module to the build inputs, keeping the server-only surface out of `void/ws`.",
        "category": "build",
        "filePaths": [
          "packages/void/package.json",
          "packages/void/vite.config.ts"
        ]
      },
      {
        "key": "docs",
        "label": "Docs",
        "summary": "Documents the session-revocation example and the action contract (types kept, cloneable args, no `ctx.request`/`ctx.user`, don't call your own room), lists the new entry point in the API table, and records the codegen/RPC module boundaries in the contributor notes.",
        "category": "docs",
        "filePaths": [
          "docs/guide/websockets.md",
          "docs/reference/api.md",
          "packages/void/AGENTS.md"
        ]
      },
      {
        "key": "tests",
        "label": "Tests",
        "summary": "Unit coverage for dispatch, addressing and error paths; type-level assertions for the action/proxy types; Miniflare integration tests through the generated Worker (closing, broadcast, storage, cron/queue callers, RPC isolation); and generated-dts typechecks that are proven live by asserting they fail when the `actions` declaration is stripped.",
        "category": "tests",
        "filePaths": [
          "packages/void/test/integration/room-action-types-typecheck.test.ts",
          "packages/void/test/integration/websocket-room-actions.test.ts",
          "packages/void/test/unit/compile.test.ts",
          "packages/void/test/unit/resource-name-runtime.test.ts",
          "packages/void/test/unit/route-types.test.ts",
          "packages/void/test/unit/ws-room-actions.test.ts",
          "packages/void/test/unit/ws-room.typecheck.ts",
          "packages/void/test/unit/ws-server-close.test.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/void/test/integration/room-action-types-typecheck.test.ts",
            "text": "Uses the package's built `dist` declarations, so it will fail if `dist` is stale rather than only when codegen drifts."
          },
          {
            "path": "packages/void/test/unit/ws-server-close.test.ts",
            "text": "`cloudflare:workers` is mocked here because the DO class now extends Cloudflare's `DurableObject`; the `define()` helper replaces the previous `it.each` over the two define functions.",
            "critical": false
          },
          {
            "path": "packages/void/test/integration/websocket-room-actions.test.ts",
            "text": "The `/helpers` case asserts internal helpers answer \"does not implement the method\", which is what proves the `#`-private conversion actually keeps them off the RPC surface."
          }
        ]
      }
    ],
    "schemaVersion": 1,
    "source": "llm",
    "generatedAt": "2026-11-16T05:54:43.713Z",
    "model": "openai-compatible/opencode-go/deepseek-v4.1-flash",
    "locale": "en"
  }
}

@yangshun

Copy link
Copy Markdown
Collaborator
  • PR Better organize runtime modules #841 reorganized the runtime files into feature directories.
  • Please resolve the merge conflicts against the latest main and update imports and build/export paths that still use the old layout.
  • This PR adds runtime/ws-room.ts; please place it under runtime/ws/.

@cpojer
cpojer self-requested a review November 16, 2026 05:03
@0froq
0froq force-pushed the feat/room-server-actions branch from cf28f78 to 8bb44e1 Compare November 16, 2026 05:51
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.
@0froq
0froq force-pushed the feat/room-server-actions branch from 8bb44e1 to f1d0d81 Compare November 16, 2026 05:52

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WebSockets: a server-side handle to a room, to broadcast to or close its connections from other server code

2 participants