Subscriptions
A long-lived operation over graphql-ws — declared like a query, gated at subscribe, and filtered per item for the subscriber who is reading.
A subscription is a #[query] that answers more than once. You write an
async method returning a stream, declare the same access posture every
other operation declares, and the framework serves it over graphql-ws on
the path it already serves POST on. What you get at the end: a socket
clients can subscribe to, gated at subscribe and filtered on every item
pushed afterwards.
#[subscription]#[authorize(Read, PostEntity)]async fn post_published(&self) -> impl Stream<Item = Post> { self.bus .stream::<PostPublishedEvent>() .map(|event| Post::from(&event.post))}That method sits in the same #[operations] impl as the queries and
mutations beside it. There is no second decorator, no subscription root
to register, and no separate mount.
Wire it in
Section titled “Wire it in”Nothing beyond what a query needs. GraphqlModule, which a resolver brings,
mounts the graphql-ws socket on the same path as the POST endpoint the moment a
#[subscription] is discovered:
#[module(imports = [PostsGraphqlModule])]pub struct ApiModule;A schema with no subscription anywhere carries no Subscription type at
all — the SDL is unchanged until you declare one.
The posture runs twice
Section titled “The posture runs twice”Every operation declares #[authorize(Action, Subject)],
#[public(Action, Subject)] or a bare #[public], and a subscription with none
does not compile. What differs is when
the declaration is enforced, and this is the part worth reading twice.
The gate runs once, at subscribe. A caller whose ability carries no matching rule is refused before the stream opens, exactly as a query is refused before its body runs.
Each item is judged as the socket polls the stream. The row the stream
builds (Post::from(&event.post)) is judged for the subscriber whose ability
the socket carries — the row rules first, then the field grants. An item the
subscriber may not read is dropped, not delivered with its fields nulled, as a
refused row leaves an item that is a list:
// two subscribers, one stream#[subscription]#[authorize(Read, PostEntity)]async fn post_published(&self) -> impl Stream<Item = Post> { self.bus .stream::<PostPublishedEvent>() .map(|event| Post::from(&event.post))}With a policy that scopes posts to the caller’s org, an author in org A
and a reader in org B can hold the same subscription open: the post
published in org A reaches the first and never reaches the second. The
resolver body writes no filter — the posture attribute is the whole
mechanism, the same one #[authorize] arms on a query.
That policy reads org_id, a column of the row the event carries, whole. An
item is pushed, not read through Repo, so a rule only a read could decide — a
relation, two value types only the database compares — admits no item, and such
a denial refuses every one. And carry the row, never its wire type: a wire row
the publisher built was judged for the publisher, and answers no subscriber
(A row answers the caller who judged it).
Feeding a subscription
Section titled “Feeding a subscription”A stream needs a source, and a domain event is one already: PostsService emits
PostPublishedEvent on publish, and the resolver reads it off the bus it injects.
#[resolver]#[use_guards(AuthzGuard)]pub struct PostsResolver { #[inject] svc: Arc<PostsService>, #[inject] bus: Arc<EventBus>,}There is no hub to write and no listener to import: an item reaches a subscriber once the mutation’s transaction has committed, never for one that rolled back. Forgetting the bus is a boot error naming it, not a silent subscription.
The stream reaches this process, and a reader far behind loses the oldest events:
Event streams has what it promises.
A source of your own — a broker’s consumer, a channel — is any
impl Stream<Item = T>, gated and judged the same way.
Note what the event carries: the published row, not its id and not its wire
type. An item is pushed, not read through Repo, and its judgement decides on the
whole row. A published fact carries the fact.
The socket
Section titled “The socket”Subscriptions run over graphql-ws on
the URL POST is served on, the caller authenticated on the upgrade with the
same Authorization header a query carries. The subscription
socket is its handshake, what it carries from the
upgrade, and the bounds it holds.
Limits
Section titled “Limits”- A subscription selects one root field, by name, once. One operation opens
one stream (GraphQL §5.2.3.1), so a document selecting a second root field, the
same one twice, its field through a fragment, or under
@skipor@includeat the root is refused once validation passed, before anything opens:the subscription selects "b" beside "a" at its root, oneINVALID_ARGUMENTerror, thencomplete. async-graphql would open a stream per field there, stream each copy’s items twice, and open none for a fragment. A directive below the root field is the client’s as anywhere; two streams are two operations on one socket. - The fallible return is spelled
Result<…>. async-graphql reads the last path segment of the return type and takes any other spelling for the stream itself, so aResultunder another name —GqlResult<impl Stream<…>>fromuse async_graphql::Result as GqlResult, or an alias around a named stream — is a compile error naming the rule, at the return type. A query or a mutation answers such aResultby its type; a subscription cannot. The method may befnorasync fn. - An item a refusal makes is dropped, not raised. A stream field’s type is
the item’s, not a
Result, so there is no error channel per item: failing closed means the item does not ship. A refusal the subscriber’s grants make is said atdebug, a row judged for another caller aterror, each onnest_rs::authznaming the subscription byhost,method,kindandfield. - A relational rule decides no item. The subscriber sees nothing, and
nest_rs::authzlogs onewarn(reason = "undecidable_on_push") per entity and action, not one per item. - A stream’s own reads. A visitor’s read nothing; a caller a token backs reads
under the ability its socket carried, or the one the field’s own guards attached
at its opening, and what a scalar built from those rows says is the body’s own
line. Its items are judged and answered under that same ability, so a field
binding
AbilityGuarditself streams as one under a guarded upgrade does. bind = Servicebinds at subscribe, not per item — it names one subject for the subscription, the way it names one for a mutation.- A subscription’s request scope lasts as long as the subscription. A request-scoped provider it resolves is built at its opening and shared by every item its stream yields, until it completes.
- Federation reaches queries, not subscriptions. An
#[entity]is aQuery-root field the router resolves by reference; theSubscriptionroot has no_entities, and declaring one there is a compile error naming both roles. See Federation.
Going further
Section titled “Going further”- Queries and mutations — the operation shape a subscription follows.
- Authorization — what
#[authorize]gates and what a judged row holds. - Events — the bus a subscription reads domain events from.
- WebSockets — the other realtime surface, for message-shaped protocols rather than schema-shaped ones.