Request Details
we need a way to disconnect clients from the server side. ideally both through, ctx.disconnect_identity(identity: Identity) and ctx.disconnect_connection_id(connection_id: ConnectionId).
this is required to be able to build ban systems as custom clients can just not react to any "server says disconnect" setups.
a timeout system also requires this but can be worked around with the "server says disconnect" setups but it isn't nice and can be ignored on the client side as mentioned.
the disconnect_connection_id alternative is needed when multiple clients can connect to the same identity at the same time and we don't want to disconnect all connections or something like that. (it's mostly to have the option)
doing a direct ctx.disconnect_sender() is not as useful as it doesn't work with scheduled reducers/procedures.
Requested by @xDovos via the SpacetimeDB site.
Activity
View on GitHub#5266Disclaimer: AI Usage
- This proposal was drafted with AI from a design conversation, and I reviewed and edited it.
Proposal
Modules get a way to disconnect clients from the server side, for bans, timeouts and "one connection per identity".
A new lifecycle reducer
#[reducer(disconnect_client)]receives every disconnect request, together with a payload type that the module defines.Defining it gives
ReducerContextandTxContextadisconnectmethod.A disconnect either waits for the transaction to commit, or happens even if the transaction fails. (why see below)
Rust comes first. TypeScript and C# follow in separate PRs once the Rust part is merged. C++ is out of scope for me, as I'm not familiar with it.
Why a lifecycle reducer
A reducer that disconnects a client often fails on purpose, e.g. when a client forges a call to an admin reducer that its UI never offers.
Without the lifecycle reducer, the failing reducer would have to write the ban itself, and its rollback would discard that write. Every reducer that may disconnect and ban clients would have to succeed just to keep the ban.
With it, the ban is written in
disconnect_client, in a transaction of its own, so the calling reducer is free to fail.
API (Rust)
The API documents itself in the code: the signature of
disconnectand when it acts are in the doc comments, where the IDE shows them.Types
In the
spacetimedbcrate, next toReducerContext:/// The connections that `disconnect` closes. #[derive(SpacetimeType)] pub enum By { /// Every connection of this identity. /// Inside `client_connected`, the connection being set up is left out. Identity(Identity), /// This one connection. ConnectionId(ConnectionId), } impl From<Identity> for By { /* By::Identity */ } impl From<ConnectionId> for By { /* By::ConnectionId */ } /// Whether `disconnect` waits for the calling transaction to commit. /// /// | Calling transaction | `Yes` | `No` | /// |---------------------|------------------------------|--------------------------------| /// | commits | disconnects after the commit | disconnects after the commit | /// | fails | doesn't disconnect | disconnects after the rollback | #[derive(SpacetimeType)] pub enum Transactional { Yes, No, } /// What the `disconnect_client` reducer receives for one call of `disconnect`. #[derive(SpacetimeType)] pub struct Disconnected { /// The identity whose connections are closed. /// `None` when `disconnect` named a `ConnectionId` that has no open connection when it runs. pub identity: Option<Identity>, /// The closed connections; empty when there are none. pub connection_ids: Vec<ConnectionId>, } /// Why SpacetimeDB refused to run a `disconnect`. Nothing changed. #[derive(SpacetimeType)] pub enum DisconnectError { /// Called inside `disconnect_client` or `client_disconnected`. OngoingDisconnect, /// Called inside `client_connected` with the `ConnectionId` of the connection being set up. /// To refuse that connection, return an error from `client_connected`. OwnConnection, }DisconnectErrorimplementsDisplaywith a message that says what to write instead, and converts intoString, so?works in a reducer that returnsResult<(), String>.The payload is no field of
Disconnected, but a parameter of its own (see below):#[derive(SpacetimeType)]doesn't support generic types in modules.The
disconnect_clientreducerA new section in the docs of
#[reducer], next toclient_connectedandclient_disconnected:/// ### The `disconnect_client` reducer /// /// This reducer is marked with `#[spacetimedb::reducer(disconnect_client)]`. /// It adds a `disconnect` method to [`ReducerContext`] and [`TxContext`], /// and runs once for each call of that method. /// A module without it has no `disconnect` method. /// /// Its second parameter is a [`Disconnected`]. /// An optional third parameter takes a payload that each call of `disconnect` passes on. /// Its type `P` is any type that implements `SpacetimeType`: /// a built-in one such as `String` or `u32`, /// or a struct or enum of the module with `#[derive(SpacetimeType)]`. /// The parameters decide the signature of `disconnect`: /// /// | `disconnect_client` takes | `disconnect` is | /// |-----------------------------------------------|--------------------------------------------------------------------------------------------------------------------| /// | `ctx, disconnected: Disconnected` | `fn disconnect(&self, by: impl Into<By>, transactional: Transactional) -> Result<(), DisconnectError>` | /// | `ctx, disconnected: Disconnected, payload: P` | `fn disconnect(&self, by: impl Into<By>, transactional: Transactional, payload: P) -> Result<(), DisconnectError>` | /// /// The payload stays in the module: the disconnected clients never see it. /// [`Transactional`] says whether the disconnect waits for the calling transaction to commit. /// /// `ctx.sender()` is whoever called `disconnect`. /// The disconnected clients are in [`Disconnected::connection_ids`]. /// /// This reducer runs in a transaction of its own, /// so it can record a ban even when the reducer that called `disconnect` fails. /// If an error occurs in this reducer, its changes are discarded, /// and the clients are still disconnected. /// /// A disconnect ends only the connections that are open now. /// To keep a client out, write to a table here, and return an error from `client_connected` when it connects again.The intro of the lifecycle section changes too: it says lifecycle reducers take no parameter except
ReducerContext, anddisconnect_clienttakesDisconnectedand an optional payload.Generated
disconnectThe
disconnect_clientreducer's macro emitsdisconnectas a generated trait implemented forReducerContextandTxContext, the same way a table emits its accessors.The generated method carries a doc comment with its signature for this module, and links to
By,Transactional,DisconnectErrorand thedisconnect_clientsection.ProcedureContextgets nodisconnect. A procedure disconnects insidewith_tx/try_with_tx.Anonymous views get no
disconnect. Whether views get one is open, see below.A module defines at most one
disconnect_clientreducer, like the other lifecycle reducers. Clients can't call it.
Example
#[derive(SpacetimeType)] pub struct Ban { pub reason: String, } #[reducer(disconnect_client)] fn on_disconnect_client(ctx: &ReducerContext, disconnected: Disconnected, ban: Ban) -> Result<(), String> { // e.g. write a ban log; `client_connected` reads it and refuses banned identities. Ok(()) } #[reducer] fn admin_only(ctx: &ReducerContext) -> Result<(), String> { if !is_admin(ctx) { // The target is anything that converts into `By`: // - every connection of the caller's identity: `ctx.sender()`, or written out `By::Identity(ctx.sender())`, // - only the calling connection: `connection_id`, or written out `By::ConnectionId(connection_id)`, // taken from `ctx.connection_id()`, which is an `Option`: `None` in `init` and scheduled reducers. ctx.disconnect(ctx.sender(), Transactional::No, Ban { reason: "forged admin call".into() })?; return Err("not an admin".into()); } Ok(()) }Behavior
When it happens
Transactionalabove says whether a disconnect happens when the transaction called it returns an error.The request records the target, the
Transactionalvalue and the payload in the calling transaction. It changes no table.disconnect_clientruns once perdisconnectcall.In
disconnect_client,ctx.sender()is whoever calleddisconnect: an admin, or the database for a scheduled reducer.connection_idsholds every connection of the identity forBy::Identity, and the one connection forBy::ConnectionId. ForBy::Identityit is empty when the identity has no open connection;disconnect_clientruns anyway, e.g. to ban an identity that isn't connected.For
By::ConnectionId, the identity comes from that connection'sst_clientrow. When the connection never existed, or left before the request runs, there is no row:identityisNone,connection_idsis empty, anddisconnect_clientruns anyway, so its payload isn't lost.Connections include HTTP
/call, SQL and MCP callers, which have anst_clientrow while their request runs, so modules can react to malicious HTTP requests too. Their row is deleted like any other, but their running request isn't cut off: it finishes, and its own teardown then finds the row gone.
Inside
client_connectedBy::Identity(ctx.sender())covers every connection of the identity except the one being set up. This gives "one connection per identity": the new device stays, the old ones go.To refuse the new connection itself,
client_connectedreturns an error of its own, as today. A call ofdisconnectwith the new connection's ownConnectionIdfails withDisconnectError::OwnConnection, whose message says exactly that.To also close the identity's other connections, if there are some, the
By::Identitycall needsTransactional::No: the refusal makesclient_connectedfail, which drops aYesrequest.
#[reducer(client_connected)] fn connected(ctx: &ReducerContext) -> Result<(), String> { if is_banned(ctx) { // Closes the identity's other connections. // `No`, because the error returned below makes this reducer fail. ctx.disconnect(ctx.sender(), Transactional::No, Ban { reason: "banned".into() })?; // Refuses this connection. // Calling `disconnect` with this connection's own `ConnectionId` fails too, // but its `DisconnectError::OwnConnection` says to return an error of your own instead. return Err("banned".into()); } Ok(()) }Refused calls
disconnectreturns an error, and changes nothing, when it is called:inside
disconnect_clientorclient_disconnected, so no request starts another,inside
client_connected, with theConnectionIdof the connection being set up; the error says to return an error fromclient_connectedinstead.
Procedures
Inside
with_tx/try_with_tx,TxContextbehaves likeReducerContext: when the body returns an error,Yesdoesn't disconnect, andNodoes.Transactions of one disconnect
Success case, one transaction:
disconnect_clientruns.client_disconnectedruns for each connection, if the module defines it.SpacetimeDB deletes each connection's
st_clientrow.
If anything in that transaction fails, the whole transaction is discarded, and the host continues with separate transactions, as it already does today for
client_disconnectedlifecycle reducers:disconnect_clientalone. Its failure is discarded, and nothing stops.For each connection, the normal disconnect teardown, including today's fallback transaction that deletes the
st_clientrow whenclient_disconnectedfails.
The connections are closed in every case, also when
disconnect_clientfails.The sockets close after this work, as they do when a migration disconnects all clients today. The connection's own teardown then finds its
st_clientrow gone and does nothing, soclient_disconnectedruns exactly once per connection.When a reducer disconnects its own caller, the caller receives the reducer's result before the close frame.
What the client sees
A WebSocket close frame with a new close code next to
SESSION_BUSY_CLOSE_CODE(4000), and a fixed reason. The payload never reaches the client.A new
ClientDisconnectCausevariant for metrics.
Bans
A disconnect only ends the connections that are open now.
To keep a client out,
disconnect_clientwrites to a module table, andclient_connectedchecks it and returns an error.Host Side (for orientation)
New host call in
spacetime_10.7(wasm), with its wrapper inbindings-sys. V8 (sys@2.3) follows with the TypeScript PR.New
Lifecyclevariant in the module def (crates/lib/src/db/raw_def).The host buffers requests in the instance environment and acts on them when the calling transaction ends, after its commit or rollback. Today no hook runs after a commit, and scheduling and the IDC outbox act right away instead.
Requests live in host memory until they run. A crash between the caller's commit and the request loses it: the connections are gone after a restart anyway, but
disconnect_clientdoesn't run for it.connection_idscomes fromst_client. Closing sockets needs more: today nothing maps(Identity, ConnectionId)to a live connection that the module host can reach. The subscription manager covers only subscribed clients, and thesession_idindex lives in client-api. This needs a registry of all WebSocket connections per database.The existing
kickaborts the connection task without a close frame. This feature sends one.
Questions for the Maintainers
Views: should
ViewContextgetdisconnect? Views are scoped to an identity or connection, so a view could end a connection that subscribes while it isn't allowed to, e.g. a player who may subscribe to some data only after the client told the server that it is in a certain state.Several nodes: the design assumes that the sockets and the module host of a database run in one process, as in SpacetimeDB Standalone. Do deployments with several nodes need more?
Not Included
TypeScript and C# (separate PRs), C++ (none).
Storing bans or refusing reconnects: modules do this in their own tables and
client_connected.Savepoints inside a transaction.
Disconnects from anonymous views.
I have the same requirement for a multiplayer game: when a player logs in on a new device with the same Identity, the server should disconnect the previous connection while keeping the new one active.
Tracking the latest ConnectionId and rejecting reducers from older connections only prevents gameplay actions that perform that check. It does not close the old WebSocket or stop its subscription updates. Asking the old client to disconnect is also insufficient because it can ignore the notification.
The session_id-based reconnect mechanism addresses replacement within the same logical session, but different devices can use different session IDs, so it does not enforce one active connection per account.
A module-accessible API to disconnect a specific ConnectionId would let us implement this policy in the server-side client_connected/login logic. Disconnecting by Identity would also be useful for bans, but targeted disconnection is particularly important here so the newly accepted connection is preserved.
