Subscriptions
Serve GraphQL subscriptions over graphql-transport-ws beside the HTTP endpoint.
GraphqlConfig::subscriptions(path) mounts a WebSocket gateway at path. The gateway speaks the graphql-transport-ws subprotocol and runs every subscribe message through Engine::subscribe, so it serves async-graphql and juniper alike.
The application imports WsModule once, because the gateway is reachable through it. GraphqlModule does not import it, since a second import would make a second WsModule identity beside the application's.
use ulo::module;
use ulo_graphql_http::{GraphqlConfig, GraphqlModule};
use ulo_ws::WsModule;
#[module(imports = [
WsModule::for_root(),
ApiModule,
GraphqlModule::for_root(GraphqlConfig::at("/graphql").subscriptions("/graphql/ws").playground(false).engine_from(ApiModule)),
])]
pub struct AppModule;The subscription reads from a provider, so anything that can reach the provider feeds every open subscription. Here Ticker wraps a tokio::sync::broadcast channel:
use async_graphql::{Context, Subscription};
use futures_util::{Stream, stream};
use ulo_graphql_async_graphql::dep;
pub struct Subscriptions;
#[Subscription]
impl Subscriptions {
/// Every tick published while the subscription is open.
async fn ticks(&self, ctx: &Context<'_>) -> async_graphql::Result<impl Stream<Item = u64>> {
let receiver = dep::<Ticker>(ctx).await?.sender.subscribe();
Ok(stream::unfold(receiver, |mut receiver| async { receiver.recv().await.ok().map(|tick| (tick, receiver)) }))
}
}Ticker is exported from ApiModule so dep::<Ticker> finds it. The example binary has nothing that publishes; tests/subscriptions.rs calls Ticker::publish.
The protocol
A client opens the socket offering the graphql-transport-ws subprotocol, sends connection_init, and receives connection_ack. Each subscribe message starts one execution under its own id:
{ "type": "subscribe", "id": "t", "payload": { "query": "subscription { ticks }" } }The server answers each event with {"type":"next","id":"t","payload":{"data":{"ticks":1}}}. A complete message from the client cancels that operation. Two operations on one connection each receive every event under their own id.
The gateway closes the connection on a protocol violation:
| Code | Cause |
|---|---|
| 4406 | The handshake echoed no graphql-transport-ws subprotocol. |
| 4400 | A message that does not parse. |
| 4401 | subscribe before connection_ack. |
| 4408 | No connection_init within connection_init_timeout. |
| 4409 | A second subscribe with an id already in use. |
| 4429 | A second connection_init. |
ping is answered with pong. The init timeout is 3 seconds at Bound::Default, Bound::Unbounded waits indefinitely, and Bound::After(Duration::ZERO) is refused when the application wires. A module that mounts GraphqlWs itself binds the timeout with m.try_value(InitTimeout::new(..)): InitTimeout::new returns Err for a zero bound, and try_value reports it when the application wires. The connection_init payload is kept in the connection's session.
Shutdown
When the application drains, each running operation ends with a complete message and the socket closes with code 1001 and the reason the server is shutting down.
Authorisation
Connect guards are the gateway's only authorisation point. They run once per connection, and no WebSocket guard, interceptor or error handler runs per operation, since the gateway has no handler for them to wrap. A guard written expecting to run on every message does not run on graphql-transport-ws. Decide an operation's authorisation at connection_init, from its payload in the session, or inside the resolvers.