Federation
Serve this schema as an Apollo subgraph: an entity resolved by reference, gated like every other operation, behind a router and not on the internet.
A subgraph is a schema a router composes with others. The router asks it
two things a client never does: what does your schema look like (_service)
and give me these objects by their keys (_entities). Turn it on with one
config flag, write one new kind of operation, and the schema answers both.
#[operations]impl PostsResolver { #[entity] #[authorize(Read, PostEntity)] async fn find_post_by_id(&self, id: Uuid) -> Result<Option<Post>> { match self.svc.access(Action::Read, id).await.opaque()? { Access::Found(post) => Ok(Some(Post::from(&post))), Access::Denied | Access::Missing => Ok(None), } }}Denied and Missing answer the same thing on purpose: a field the router
addresses by key must not say which keys exist.
That is the whole surface. The @key the router matches on is inferred from
the resolver’s own arguments — id here — so an entity declares its key
once, where it is resolved, and #[expose] never carries a federation key of
its own.
An entity is an operation, and it owes what one owes
Section titled “An entity is an operation, and it owes what one owes”_entities is a field on the Query root that the router calls with
references — {__typename, <key fields>} — for objects the client never
named. Nothing in the document a client reads mentions your entity resolver, so
it is the one role where a forgotten gate is invisible.
It is therefore a #[query] in every respect that matters:
| Layer | On an #[entity] |
|---|---|
| Guard chain | runs — resolver-scope and method-scope, each declaring GuardFor<GraphqlView> |
| Access posture | mandatory — #[authorize(Action, Entity)] or #[public], no posture ⇒ compile error |
| Argument rules and pipes | run — the key arguments’ rules, then a Piped<P> on any of them |
| Wire rows | judged — the entity’s row is judged for the caller’s ability like any other row |
Four things it refuses that a #[query] does not, each a named compile error:
bind = Serviceis refused — it answersNOT_FOUNDfor an absent row andFORBIDDENfor a withheld one, which by key is an existence oracle; load the row in the body and answerNonefor both;#[entity(key = "…")]is refused — the@keyis read off the method’s own arguments, so declaring it would be declaring it twice;- a
#[graphql(…)]of the method’s own is refused — async-graphql reads the first one on a method, and the decorator has to emit#[graphql(entity)]there, so yours would silently take its place and the method would quietly stop being an entity resolver; - and it must take at least one argument, since the arguments are the key.
The method itself may be a plain fn or an async fn: the resolver
async-graphql awaits is the one the decorator emits, which is always async.
Two more are decided at boot, because only the built schema holds the
fact. An #[entity] whose resolved type carries no @key — a list, a
scalar, a union, anything async-graphql does not key — fails the boot naming
the method and the type. So do two resolvers whose key shapes overlap
(below).
#[entity] is a role, not a modifier: it cannot be combined with #[mutation]
or #[subscription], because _entities lives on the Query root and no
other root has it. Writing both is a compile error naming both. The reverse
holds too: async-graphql’s own #[graphql(entity)] beside #[query],
#[mutation], #[subscription] or #[field_resolver] is a compile error, since
it would key a type with none of what an #[entity] owes.
Turning it on
Section titled “Turning it on”GraphqlModule::for_root(GraphqlConfig { federation: true, ..GraphqlConfig::default()})or <PREFIX>_GRAPHQL__FEDERATION=true — the same dual path every module config
has. Default off.
The flag does not switch the federation surface on — a key does.
async-graphql serves _service and _entities the moment a type in the schema
is keyed, whatever the flag says. So the two are declared together or not at
all: a keyed schema with federation: false fails the boot, naming the
resolver whose types key it — an #[entity], or an object an operation returns
that carries async-graphql’s own #[graphql(entity)]. Without that check the
flag would be a comment, and an app that added one entity would publish its own
SDL while its config said it was not a subgraph.
What the flag itself decides:
- The committed SDL becomes the subgraph form.
@keyappears on every federated type, and_service/_entitiesare stripped from the export — which is what the Apollo spec asks of a subgraph schema. If your app commitsschema.graphql, expect it to move in both directions in that first diff. - The directives are declared even with no entity yet, so
_serviceanswers for a subgraph that has not written its first key. (_entitiesdoes not exist until one does — there would be nothing for it to return.) - A guard identifying the router is owed.
_serviceanswers the whole SDL and no posture stands behind it, so a subgraph whose/graphqlrequest runs no guard ofGuardPhase::AuthenticationorAuthorization— inGlobalGuardsor anEndpointGuards<GraphqlView, …>— fails the boot, naming the guard to add and the one opening below.
A subgraph only its router reaches, on a private network, opens its SDL in one line:
GraphqlModule::for_root(GraphqlConfig { federation: true, federation_sdl: Surface::Open, ..GraphqlConfig::default()})or <PREFIX>_GRAPHQL__FEDERATION_SDL=true, said at warn at each boot outside a
development or test profile. Surface::ByProfile opens it under one of those alone,
for a router run beside the subgraph in development. Where a guard identifies the
caller, it decides whatever this says.
One key shape, one entity resolver: two claims on the same shape fail the
boot, naming both. An entity is addressed by @key rather than by name, so
the duplicate leaves no clashing operation in the SDL — only a doubled @key,
and a router reaching whichever body linked first, access posture included. The
check applies inside a resolver too — two #[entity] methods in one impl
claiming one shape is the same duplicate, written the way it is easiest to
write.
A type may carry several @keys — as long as the shapes are disjoint.
Keying Post by id in one resolver and by slug in another is legal and both
stay reachable: no representation can satisfy both matchers, so which resolver
answers is decided by the reference, not by link order. Shapes that overlap —
id here and id tenant there, or the same fields in a different order —
fail the boot naming both claimants and both shapes.
Wherever they are declared, including on one resolver. A reference carrying
id and tenant satisfies the id matcher too, so one of the two bodies is
unreachable and the posture that answers is the other one’s — and nothing orders
them by anything you wrote. Across resolvers _entities takes whichever linked
first. Within one resolver async-graphql sorts its matchers by argument
count, not key arity, so a short key with a non-key argument beside it outranks
a longer key without one; at equal counts the sort is stable and declaration
order decides. This is narrower than Apollo, which allows a type several
overlapping @keys. The narrowing is deliberate: what the router picks decides
which #[authorize] runs, and neither this framework nor async-graphql orders
those two by anything declared.
A nested selection is one field: @key(fields: "id organization { id }") selects
id and organization, so it is disjoint from @key(fields: "slug") and
overlaps @key(fields: "id").
What guards the two fields a router calls
Section titled “What guards the two fields a router calls”_entities and _service are resolved by async-graphql’s own Query root,
above the merged root this framework composes — so the chain #[operations]
emits inside a resolver body is not where they are gated. Guards run in front of
both, once per field, through a schema extension GraphqlModule installs on a
subgraph and wherever the app lists a pool: on _entities the app-wide pool, and on
_service that pool and each guard of its EndpointGuards that identifies or authorizes
a caller. Each field is a graphql.field unit of role federation, inside the app’s
exception filters and interceptors. /graphql admits an anonymous request, so this is where one
is refused: a GlobalGuards<(AuthnGuard,)> answers _service and _entities as it
answers a gated #[query], UNAUTHENTICATED in the same native GraphQL error frame,
and a router presents the token a caller would. An AuthzGuard with no AuthnGuard
beside it refuses them too, a visitor’s ability having no posture to answer to there.
Five consequences worth reading twice:
- The pool is the whole chain on
_entities, because a federation field belongs to no resolver. The router calls it on the schema, so there is no#[use_guards]scope to compose and no posture to read. An#[entity]’s own#[use_guards]and#[authorize]/#[public]still run in its body, per reference, and a pooledAuthnGuardreaches none of them for an anonymous caller, its#[public]included. EndpointGuardsalone leave_entitiesto each#[entity]. Its posture is mandatory, so what one opens is a line you read;_servicehas none, and refuses.- A guard of your own decides in its
check. One admitting the anonymous/graphqlrequest readsPosture::Gated, the posture of both fields, to refuse them. - A guard
EndpointGuardslists that reads the request decides incheck_http.GuardPhase::AuthenticationorAuthorizationputs itscheckon_service, a unit holding no HTTP request, so one reading the request there answersINTERNALto every caller, a router with a valid key included, and itserrorline says this edit. A guard identifying no one, a rate limit, decided at the request and is not asked again. - A pooled guard runs once per
_entitiesoperation, not once per representation. The gate runs it at the field; the#[entity]bodies reached through it compose everything except the pool, precisely so the multiplier on a pooled check is not a number the caller picks.
A router’s API key is that shape: the decision reads the request, and the units it carries are admitted in one visible line.
use nest_rs::core::{Layer, UnitContext, async_trait, injectable};use nest_rs::guards::{Denial, Guard, GuardFor, GuardPhase};use nest_rs::http::HttpView;
#[injectable]#[derive(Layer)]pub struct RequireApiKey;
#[async_trait]impl Guard for RequireApiKey { fn phase(&self) -> GuardPhase { GuardPhase::Authentication }
async fn check_http(&self, cx: &mut UnitContext<'_>) -> Result<(), Denial> { match HttpView::of(cx)?.request().header("x-api-key") { Some(key) if known(key) => Ok(()), _ => Err(Denial::unauthorized("an unknown API key")), } }
async fn check(&self, _cx: &mut UnitContext<'_>) -> Result<(), Denial> { Ok(()) }}
impl GuardFor<HttpView> for RequireApiKey {}What is not here
Section titled “What is not here”Composition. Merging subgraphs into a supergraph is the router’s job, done
by Apollo’s own tooling (rover). NestRS ships the subgraph half — the schema,
the entity resolvers, and the guarantee that both are gated (above) — and takes
no dependency to do the router’s work.
Going further
Section titled “Going further”- Queries and mutations — the operation shape an
#[entity]follows in every respect but how it is reached. - Authorization — what the mandatory posture gates and reads.
- Configuration — the rest of the
<PREFIX>_GRAPHQL__*surface, including the introspection switch this one is not covered by.