jmap-websocket
JMAP over WebSocket (RFC 8887, urn:ietf:params:jmap:websocket) for the
jmap-* crate family: the capability object, the wire messages, and a
server session driver that runs a jmap_server::Dispatcher behind any
WebSocket library.
What it is
A support crate. Always available, with no async runtime:
| Item | RFC 8887 |
|---|---|
CAPABILITY, WebSocketCapability (url, supportsPush) |
§3 |
SUBPROTOCOL ("jmap"), offers_jmap |
§4.2, §6.1 |
WsRequest (@type: "Request", optional id) |
§4.3.2 |
WsResponse (@type: "Response", requestId) |
§4.3.3 |
WsRequestError (problem details, @type: "RequestError", requestId) |
§4.3.4 |
WsStateChange (StateChange plus pushState) |
§4.3.5.1 |
WebSocketPushEnable (dataTypes, pushState), WebSocketPushDisable |
§4.3.5.2, §4.3.5.3 |
ClientMessage, ServerMessage (pick the type by @type) |
§4.3 |
Feature server (module server):
Connection: one connection's driver.run(incoming, outgoing)takes anyStreamofInbound(text, binary, close) andSinkofOutbound(text, close).parse_client_message: one text message to aClientMessageor theWsRequestErrorto answer with (notJSON,notRequest,limit).RequestHandler: what answers a Request;DispatcherHandlerwraps aDispatcherand a caller, with an optionalunknownCapabilitycheck.PushSource: where push notifications come from;PushHubis an in-memory fan-out withpushStatetokens and replay;NoPushsends nothing.filter_state_changeappliesdataTypes.ExtensionHandler: takes the client messages of extension@types (ChatStreamEnable,VTCStreamEnable,SceneStreamEnable, ...) and sends the extension's events through anExtensionSender; register it withConnection::with_extension.ConnectionConfig:maxCallsInRequest,maxSizeRequest,maxConcurrentRequests, binary-message policy, extension queue size.
Feature tungstenite: tungstenite::serve runs a Connection over a
tokio-tungstenite WebSocketStream.
What it's for
Servers built from the kit that want to offer RFC 8887. The *-server
crates stay transport-free (workspace AGENTS.md); a deployment adds this
crate next to its HTTP stack. jmap-testjig serves its /ws endpoint
with it over axum. Clients use jmap-base-client's connect_ws, which
has its own frame types today.
How to use
[]
= { = "0.6", = ["tungstenite"] }
use Arc;
use ;
use Dispatcher;
use State;
# async #
After each write, publish the changed states to the principal's
PushHub (hub.publish(state_change)); every connection of that
principal with push enabled gets them.
Extension message types
The JMAP Chat, VTC and Scene WebSocket drafts update RFC 8887: a
capability in the Session "MAY define additional WebSocket message
types, each identified by its @type value", and the server sends them
only after the client enabled them with that capability's control
message (ChatStreamEnable, VTCStreamEnable, SceneStreamEnable).
Implement ExtensionHandler for those types and register one value per
connection, next to advertising the capability:
use JmapError;
use ;
#
handleruns one message at a time, in order; the driver reads the next client message only after it returns, while Responses, StateChanges and queued events keep going out.- Events go through a bounded queue
(
ConnectionConfig::extension_queue_capacity, default 64):try_senddrops onFull,sendwaits. An event must be a JSON object with an@typethat is not an RFC 8887 one. closeruns once whenrunends, however it ends, after the queue closed and a runninghandlefinished.- A
@typeno handler registered is still answered withnotRequest.
Closing on credential expiry
RFC 8887 §4.2 lets the server close the connection when the handshake's
credentials expire, with a Close frame of status 1008 (Policy
Violation); the JMAP Chat, VTC and Scene WebSocket drafts make 1008 a
SHOULD. Take a CloseHandle before running the connection and close
through it from the task that tracks the expiry:
use ;
# async
run then sends the Close, drops the push subscription, runs every
ExtensionHandler::close, and returns Ok(()).
How it works
- Every message type serializes with its
@typefirst and checks it on deserialize (absent accepted, wrong value rejected); the enums need it. Unknown members are kept (extra, or the inner RFC 8620 object'sextra). runloops over three sources withtokio::select!: incoming messages, finished Requests (aFuturesUnordered, so Requests run concurrently and answer in finishing order, as §4.3.2 allows), and the push subscription. Writes go out one at a time; a slow client back-pressures the loop.- A text message is read in order: size, JSON, object with
@type, then the message's own shape. Every RequestError carries the message's stringidasrequestId, ornull. RequestHandler::prepare_problemruns on every RequestError, so a deployment can localizetitle.PushHubnumbers each published change. A token it issued replays the changes since then (merged into one notification), or the latest state of everything when they were already dropped; a foreign token replays nothing.
Gotchas
- The handshake is not done here: authentication (§4.1), TLS (§5.1) and
the
jmapsubprotocol echo (§4.2) are the deployment's. - A binary message closes the connection with 1003 by default
(
BinaryFrames::Ignoreto drop it instead); RFC 8887 does not answer it with a RequestError. WsRequestErroralways writesrequestId(nullwhen unknown), as the §4.4notJSONexample does;WsResponseomits it when the request had noid.- A request over
maxConcurrentRequestsis answered with alimitRequestError, not queued. To count HTTP requests too, share a semaphore withConnection::with_shared_limit. dataTypes: []matches no type (the RFC's literal reading); usenullfor all.- A
WebSocketPushEnablewith members of the wrong type is answered withnotRequestinstead of being ignored. PushHubdoes no access filtering: keep one per principal. Merging dropsStateChange.extra.- Two §4.4 examples are not valid as printed: the Response omits the
sessionStateRFC 8620 §3.4 requires, and the second StateChange misses a comma. The tests say so. Dispatcher::dispatchneeds a Tokio runtime, sorundoes too.- Extension
@types are answered withnotRequestunless anExtensionHandleris registered for them. The driver does not checkusingfor them: the drafts tie them to the Session capability, so register a handler only where the capability is advertised. - A handler error's
extramembers become problem-details members, except names the driver writes itself (type,status,title,detail,instance,limit,requestId,@type). ExtensionHandler::closedoes not run if therunfuture is dropped (a cancelled task); put cleanup that must happen then inDrop.- Ending
incomingends the connection without a Close frame. To close with a status code (1008 for expired credentials), useConnection::close_handle. The firstclosewins; later ones, and any afterrunreturned, do nothing and returnfalse. Nothing queued is sent ahead of the Close: Responses still running, queued extension events and pending StateChanges are dropped. A reason over 123 bytes (the RFC 6455 control-frame limit) is cut on a character boundary.CloseCode::newrefuses codes an endpoint may not send.
References
- RFC 8887 — A JSON Meta Application Protocol (JMAP) Subprotocol for WebSocket
- RFC 8620 §3.3, §3.4, §3.6.1, §7.1 — JMAP Core requests, responses, request-level errors, StateChange
- RFC 6455 — The WebSocket Protocol
- RFC 9457 — Problem Details for HTTP APIs
- draft-atwood-jmap-chat-wss-00, draft-atwood-jmap-vtc-wss-00, draft-atwood-jmap-scene-wss-00 — the extension message types (jmap-chat-spec)