Repository navigation
v4.0.0
What's Changed
#[entity] — a schema serves as a subgraph, gated like everything else
NESTRS_GRAPHQL__FEDERATION serves the schema as an Apollo subgraph: the
federation directives are declared and the emitted SDL is the subgraph form —
@key present, _service / _entities stripped, as the spec requires. It is
one flag on a call this repo already makes; async-graphql =7.2.1 carries the
whole thing with no cargo feature and no new dependency, and the roadmap's
recorded reason for deferring it ("the dedicated schema tooling it would
reintroduce") was simply false.
The flag does not switch the surface on, and the boot is what makes it mean
anything. async-graphql serves _service and _entities as soon as one
entity resolver has registered its keys, whatever the builder was told — so
#[entity] plus federation = false would publish the schema's own SDL while
the config claimed otherwise, and the flag would be a comment. Declaring an
entity without the flag now fails the boot, naming the resolver.
So does claiming one key shape twice. An entity is addressed by @key
rather than by name, so the duplicate leaves nothing in the SDL but a doubled
@key while the router reaches whichever body linked first — access posture
included. The shape is the identity, not the type: Apollo lets a type carry
several @keys and async-graphql matches a reference against the shape, so two
resolvers keying Widget by id and by slug are both reachable and are not a
duplicate. Two claims on id are. And it is checked within a resolver as
well as across them — two #[entity] methods in one impl are one
registration, which is the arrangement a per-registration diff cannot see and
the way the mistake is easiest to write. The existing duplicate-operation check
was blind to all of it, an entity method contributing no field; it now reads the
key shapes out of the same scratch registry it already builds.
What it actually cost is a new operation role, and that is the whole of it.
_entities is a Query-root field the router calls with references —
{__typename, <key fields>} — for objects the client never named, so it is the
one operation whose posture is invisible from the document a client reads. Ship
it ungated and every @key-ed type is readable from outside every #[authorize]
in the schema, which is the Hard "no" list's first line. #[entity] therefore
takes exactly what a #[query] takes, through the same code path: the guard
chain, a mandatory #[authorize] / #[public], the argument pipes, the
response mask, and the GraphqlGuard bound on every guard bound at its site.
The @key is inferred from the resolver's own arguments, so #[expose] never
declares a federation key and the cross-transport declaration question never
arises.
One thing had to be built rather than switched on, and it is the half a
merged root loses silently: ContainerType::find_entity defaults to None, and
DiscoveredQuery merges its members by hand. A root that forwards only
resolve_field answers Entity not found to every reference, however many
entity resolvers the app wrote — a whole operation role missing with no field
missing. It now forwards both, under the same first-member-that-answers rule.
Seven refusals, each a named compile error with a trybuild snapshot. Three are
about the role: an #[entity] with no posture (whose sentence names why this
role is the worst one to forget), and #[entity] beside #[mutation] or
#[subscription] — a role, not a modifier, because _entities lives on the
Query root and no other root has one. Four are things a #[query] allows and
this cannot:
- A
Resultreturn is required. The guard chain is emitted only where a
denial has somewhere to go, so a bare-return operation silently has none. On a
#[query]that trade is visible in the document; an entity is reached for a
type the client never named, so a resolver-scope#[use_guards]compiled out
there shows up nowhere at all. bind = Serviceis refused. It answersNOT_FOUNDfor an absent row and
FORBIDDENfor a withheld one — right for a mutation subject the caller
named, an existence oracle on a field addressed by key.#[entity(key = "…")]is refused. The key is not the developer's to
declare, and it is the first thing someone arriving from Apollo reaches for.- A
#[graphql(...)]of its own is refused. async-graphql reads the first
one on a method and removes exactly one, so a developer's would silently take
the slot#[graphql(entity)]needs and the method would stop being an entity
resolver — reported, before this, as a leftover attribute against
#[operations]. There is no working spelling to redirect to, so the sentence
names the limit. asyncand at least one argument, reworded from async-graphql's own
refusals, which land on the#[operations]attribute naming a generated type
nobody wrote.
Deliberately absent: composition, and the demo is not a subgraph. Merging
subgraphs is the router's job and rover is a dependency this repo will not
take, so what ships is the subgraph half. And demo/apps/api leaves federation
off — _service cannot be switched off; disable_introspection does not
cover it and its field is unconditionally visible, so a subgraph publishes its
own SDL to whoever can reach it. The demo is a standalone API on a public
address with no router in front of it, so being one would publish its schema and
buy it nothing. demo/apps/api/schema.graphql is unchanged for that reason.
With it, ROADMAP.md's deferred section is empty and gone.
An #[sse] ceiling bounds its stream; its socket is a reported gap
SseSettings::respond composes the deadline into the response body, so it is
evaluated whenever that body is polled: no event is produced past the ceiling
at any rate a peer reads at, measured against a trickling client rather than
assumed. That is the stale-privilege window, and it holds.
What outlives it is the socket. Measured against a client that sent the
request and then read nothing: the server had ~1.6 MB queued for a peer taking
none of it, and hyper's connection task, its buffers and everything the stream
held stayed alive until that peer felt like reading.
Closing that from inside this crate was attempted twice and neither is sound,
which is why the gap is documented and witnessed instead. The only thing still
polled while a write is parked is the socket — and a socket does not know
which response its bytes belong to:
- Arming the connection for the stream's ceiling killed traffic that never asked
for a stream: on HTTP/1.1 keep-alive an ordinary request issued afterwards
died with zero bytes and no status line; on HTTP/2, where a browser
multiplexes an origin's whole traffic onto one connection, siblings died
mid-flight without even aGOAWAY. - Narrowing it to fire only on a parked write was worse, not better. A parked
write is ordinary TCP backpressure, not a peer that stopped reading: a
full-speed client downloading 4 MB over a connection that had once carried a
stream received 1 404 928 bytes under a declaredcontent-length: 4194304
— a protocol lie told to a well-behaved peer — while a stream small enough to
fit the socket buffer never parked at all and so was never bounded.
The information the control needs — which response is stalled — lives in the
body, which is precisely what stops being polled; poem 3.1 and hyper 1 expose no
per-response write deadline and no abort handle usable while parked. So the
ceiling stays what it is, sse::a_peer_that_stops_reading_still_holds_its_socket_past_the_ceiling
asserts the residual so it cannot be quietly reclassified as closed, and the
answer for now is poem's own Server::idle_timeout or the reverse proxy —
controls that do not need to know whose bytes are queued.
A commit that fails the same way every time no longer costs a retry budget
Per-job transactions above turned an unsettleable attempt into a failure, which
was right, and then classified every one of them as retryable, which was
not. A constraint checked at COMMIT — a deferred unique index, the shape whose
whole point is that it fires late — fails identically on every attempt. The job
therefore replayed its body once per unit of retry budget, including every
side effect that is not the database's (an HTTP call, an S3 write, a mail),
and dead-lettered anyway. #[process] already aborts on its three other
deterministic failures — an unsupported wire version, an undeserializable
payload, a missing provider — and did the opposite here.
The classification now comes from the database. CommitError::is_retryable_conflict
already existed and the HTTP interceptor already consulted it; the worker
context could not, because JobSettlement was a payload-free Copy enum and
run_in_job_context's unhonoured: fn() -> T was a bare function pointer with
nothing to capture. It carries an Unhonoured { reason, retryable } now, and a
LazyTransaction records the same verdict on the first failed statement, so
a poisoned transaction answers the question the same way a failed commit does —
the first is the one that aborted the transaction, and everything after it fails
with 25P02, which says nothing about why.
An in-doubt commit aborts, and that is the deliberate half. A connection lost
during COMMIT may have landed. Replaying it turns "may have written once" into
"wrote twice", so the framework re-attempts only what it knows rolled back —
which is exactly what keeps the default's promise standing: a PerAttempt job
needs no idempotency key because a retry has nothing left to repeat, and
transactional = false needs one because the transaction never was. The
documentation said both; only one of them is now true of the code as well.
A schedule reports the classification rather than acting on it, and the
asymmetry is the answer rather than an omission: #[every] / #[cron] /
#[after] have no retry budget and no dead-letter, so the next occurrence is
the same whichever way it went. What it owes is the sentence, and it logs it —
the context's own, not one the scheduler invented.
Breaking for anyone who wrote their own JobContext: JobSettlement::Unhonoured
takes an Unhonoured, and the unhonoured argument of run_in_job_context is
handed one. FinalizeOutcome::Poisoned gained a retryable field.
Registering a global guard could open /mcp instead of closing it
use_guards_global reached /graphql and the WS message loop and not the
MCP operation: the per-operation chain excluded the app-wide pool outright, so a
global guard overriding only check_mcp was never consulted. Its presence still
made the pool non-empty, which disarmed the endpoint's deny-all tail — so the
same host answered a tool call with the guard registered and refused it
without. A guard written to close an endpoint opened it.
The pool now composes into the per-operation chain on both in-band transports,
through the one compose in nest-rs-guards/src/dispatch/chain.rs — same three
buckets, same TypeId dedup, no per-transport switch over where the pool runs.
The rule underneath it: an Exempt endpoint guard is handed a request and runs
check_http; the site is handed the operation and runs check_mcp /
check_graphql. Two questions, so neither answers the other, and an edge that
ran the first never shortens the second.
McpOperationGuard::already_ran is gone, and it is what expressed the false
claim: it reported HTTP-scope execution and was subtracted from an MCP-scope
chain, so its only possible effect was to skip a check_mcp that had never run.
Deleting it took the task-local, the mount-time snapshot and the per-request
Arc clone that carried it into rmcp's dispatch with it. A custom
McpOperationGuard loses a method it could not implement correctly; the
canonical bridge and the pool fallback each lose an override.
Deliberately unchanged: the deny-all tail still keys on an empty pool. What
made it wrong was a pool that could not reach the operation, and it can now.
Refusing to arm the fallback for a pool holding no authentication guard is a
different rule about a different failure, and it would decide from
GuardPhase — a declaration, not a check.
What this closes is the operation, and tools/list is not one. rmcp's own
server methods — initialize, tools/list, prompts/list — carry no operation
for a check_mcp to be handed, so the only thing gating them is the endpoint's
check_http. A pool holding only check_mcp guards still takes /mcp from
deny-all to a handshake that discloses the tool inventory. Gating discovery
means a guard with a check_http, and the framework cannot tell the two apart
in a pool: use_guards_global takes no capability bound, deliberately, because
requiring one would refuse a guard written for a single edge. Reported here
rather than closed by inventing a per-edge global list.
A boundary that swallows a database error can no longer report success
Postgres aborts the whole transaction on the first failed statement and refuses
everything after it (25P02) — and a COMMIT on an aborted transaction
succeeds, having rolled back. So the commonest shape there is — loop, log what
fails, carry on — reported Ok, was told the commit worked, and persisted
nothing, with no framework event anywhere. It was reachable on any mutating
HTTP request, and per-job transactions below would have made every queue and cron
job reachable too.
LazyTransaction now records the first failed statement, and finalize refuses
to report a success it cannot honour: it rolls back, logs at error on
nest_rs::orm, and returns FinalizeOutcome::Poisoned. Every settle site
already had this shape for an escaped handle and a failed commit, so all three —
HTTP's DbContext, the shared with_data_context for WS/MCP, and the worker
context — treat it the same way: an otherwise-successful outcome fails loudly
rather than losing its writes.
Nested transactions are unaffected: begin_nested runs its statements on its own
handle, so a SAVEPOINTed insert that fails still leaves the outer transaction
committable — which is what keeps Creatable::create's scope re-check working.
A job attempt is atomic, so a retry has nothing left to repeat
A #[process] / #[every] / #[cron] / #[after] ran on the connection
pool: every statement committed on its own. A job that wrote a row and then
failed left that row behind, the queue retried the job, and the second attempt
wrote it again. The framework carried the transaction for every
request-carrying edge and left the one execution path whose failures are
expected — that is what a retry budget is — running without it.
WorkerDbContext now installs the same lazy transaction the request edges use,
settled through the same LazyTransaction::finalize: commit on Ok, roll back
on Err, and nothing at all when the job never touched the database. Commit
failure and an escaped transaction handle turn a "successful" attempt into a
failed one rather than reporting writes that were never made — the rule
with_data_context already applied per request, now applied per job.
The classification the roadmap was waiting for turned out not to be needed.
A job has no safe/mutating method to read, but the transaction is lazy: what
opens it is the first data-layer touch, which is a fact about the job rather
than a guess about its intent, so no verb has to be invented for one. A job that
never reaches the database opens nothing at all. A read is a touch, though —
a job that only reads still pays a BEGIN/COMMIT and holds its connection for
the attempt, which is what not having a verb costs and is what
transactional = false is there to decline.
transactional = false is the opt-out, one key, the same word on all four
decorators, parsed and worded once in nest_rs_codegen::job with a trybuild
snapshot on each half of the family. It is for the job whose shape defeats the
default — read, then minutes of work that is not the database's, then write —
where the default would pin a pooled connection across the middle. Such a job
owns its own consistency, and an idempotency key is what makes its retry safe.
The seam changed shape, which is breaking for anyone who wrote their own
JobContext: scope now takes the declared JobTransaction and an inner
yielding whether the job succeeded, and returns a JobSettlement.
run_in_job_context grew the matching succeeded / unhonoured pair — the
same two functions with_data_context takes on the request edges, because the
settling rule is one rule and a job is not an exception to it.
#[sse] is a route of the framework's own, with the ceiling its peers have
A route could already stream: nest-rs-http re-exports poem, so a handler
returned poem::web::sse::SSE and the document typed it text/event-stream off
the return type. What that cost was a use poem::web::sse::{Event, SSE}; in the
developer's own controller — the one import the umbrella exists to remove — and a
hand-written .keep_alive(Duration::from_secs(15)) at every site that remembered
to write one.
#[sse("/path")] is a GET that answers text/event-stream. The handler returns
an SseStream of SseEvents; the decorator owns the response. Both types, and
the futures_util combinators that build a stream, come through nest_rs::http,
so a controller that streams still declares one dependency.
A stream now carries the ceiling WS and graphql-ws already had. A stream
authenticates once, when the request arrives, then emits with those
privileges for as long as it lives — it outlived an expired token, a logout and a
revoked grant, with nothing to stop it. NESTRS_HTTP__SSE_MAX_CONNECTION_SECS
ends it and the client's EventSource reconnects, re-running the guard chain:
same reading, same 4-hour default, same 0 ⇒ unlimited spelling as
NESTRS_WS__MAX_CONNECTION_SECS and NESTRS_GRAPHQL__MAX_CONNECTION_SECS.
NESTRS_HTTP__SSE_KEEP_ALIVE_SECS is the interval the demo used to hand-write.
The namespace is http, not sse, and that is the one deliberate difference
from its two peers. SSE is a response shape of the HTTP transport, not a
module; it owns no #[config], so under one seam per config it gets no
for_root of its own — HttpModule::for_root is already its in-code path.
Three refusals ship with it, each a named compile error rather than a key that is
quietly ignored:
#[authorize]— the posture masks the response against the entity model,
and an event stream is no wire model to reconcile; the mask could only fail
closed at 500 on every request. Gate a stream with a capability-only guard, the
same answer a presigned URL and a computed report already have.#[http_code]/#[redirect]/#[response_header]— one sentence for the
family, so a fourth response decorator inherits the refusal. All three shape a
response that completes; a stream does not.#[api(response_content_type = …)]— the route answers
text/event-stream; declaring another can only make the published document
describe something it never sends.
Deliberately absent: SseStream is a named type, not impl Stream<Item = SseEvent>.
An async fn on &self returning an opaque type captures the &self lifetime
under the 2024 rules, so the stream is not 'static and cannot outlive the call —
which is the one thing a response body must do. The alternative was making every
developer write + use<> and know why.
A guard bound on a route now declares that it checks HTTP
Guard::check_http defaults to Ok(()) exactly like its three siblings, so an
empty impl Guard for X {} bound with #[use_guards(X)] compiled, read as a
protection, and passed every request. GraphQL, WS and MCP closed that this
release with a capability marker each. HTTP was left out on the argument that
check_http is the trait's base entry, so every Guard has it and a bound
there could never fail — an argument about the wrong thing. The bound never
proved a method exists; the default gives every guard all four. It proves the
author declared that this guard checks this edge.
HttpGuard: Guard is the fourth marker. #[controller], #[routes], #[crud]
and the #[gateway] struct assert it for every path in a #[use_guards] /
#[force_guards], through the same nest_rs_codegen::guard_capability_bounds
the other three go through, so the refusal is worded once and cannot drift per
edge. There are three emitters — #[controller], #[routes] and the
#[gateway] struct — and each underlines the decorator the guard was written
under. Two ship a trybuild snapshot; the gateway site is asserted by the
nest-rs-macro-hygiene witness rather than by a snapshot of its own.
A #[gateway]-struct guard attests HttpGuard, not WsGuard — those run on
the upgrade, which is an HTTP GET, while WsGuard belongs to the per-message
scope. That split was documented folklore; it is now checked.
Deliberately absent: check_http did not move onto the marker. Every
execution site holds Arc<dyn Guard>, so an extension trait carrying the method
needs a second erasure and two container registrations for any guard serving HTTP
and another edge — the cost already weighed and refused for the other three. It
would also save nothing: nest-rs-guards depends on nest-rs-http
unconditionally, so every build that links the guard core links the HTTP stack
and a cfg on the trait method saves no bytes.
The binary-size argument that deferred this work belonged elsewhere —
nest-rs-queue carried an unused nest-rs-http dependency, removed here, its
#[input] re-export having come from nest-rs-core for some time.
Migrating: write impl HttpGuard for YourGuard {} beside the check_http it
attests. The compiler names every site, at the #[use_guards] line.
An operationId is sanitised as one string, not one half of one
The version fragment was mapped onto what an identifier can carry and the
controller and handler fragments were not, so a raw-ident handler
(async fn r#type) published probe_r#type — an id no client generator can name
a method after. The map now runs over the composed id, which covers all three
halves at once; a collision it newly creates (r#type beside r_type) is
reported by the existing duplicate-id warn, whose remedy now names the handler
rename too.
#[mcp] answers every server-level identity key by name
description, website_url and icons got a bare "unknown key" while version
and instructions named their owner — the same mistake in three more spellings,
and a bare "unknown key" is silence. All four now come from one table and one
sentence pointing at McpModule::for_root(McpOptions { server }), with a drift
guard that reads McpIdentity's builders and fails if one gains no answer. A key
that is genuinely nobody's still gets the accepted-key list.
One casing rule, and it reads a run of capitals as one word
snake_case inserted _ before every interior capital, so HTTPServer became
h_t_t_p_server and APIKey became a_p_i_key. A run of capitals is now one
word: http_server, api_key, io_handler.
It had gone unnoticed because every consumer fed format_ident! — private Rust
identifiers inside macro expansions, which nobody reads. The operationId above
is the first output a developer reads, and it is where the rule had been
copied rather than shared.
The copy is gone. #[routes] computes the controller's identifier token at
compile time, through the one nest_rs_codegen::snake_case, and
HttpControllerMeta carries it. A runtime crate cannot reach codegen without
dragging syn into every app's dependency graph, so deriving it in the macro is
what keeps the rule single — the alternative is a second implementation, which is
exactly what was there.
One shape no general rule resolves, and it is documented rather than
special-cased: OAuth → o_auth. Nothing distinguishes a single capital
followed by a capitalised word from a genuine one-letter prefix without a
dictionary, and a heuristic for it would fire on names it has no business
touching — the same reasoning that removed the v-plus-digits heuristic from
version detection. Rust's own convention is the answer: acronyms count as one
word (Uuid, not UUID), so the type is spelled Oauth.
Every operationId is unique, which OpenAPI requires and we were not
operationId was the handler's method name alone, so #[crud] — which names
every resource's handlers identically — published one id for many operations.
The reference product's own document carried 12 collisions across 27
operations: list four times, get four times, create / update / delete
three each. OpenAPI 3.1 §4.8.10.1 requires the id to be unique across the
document; a generator either errors or silently renames, so the loser's method
went missing from every generated SDK.
An id is now <controller>_<handler> — the controller struct name with its
trailing Controller stripped, snake_cased, from the same metadata field that
already supplies the operation's default tag. posts_list, users_get. This is
what @nestjs/swagger does, for the same reason.
- A version composes on top:
reports_list_v1, and a version that is not a
bare integer still reads as an identifier (reports_list_v2024_08_11). So a
version = ["1", "2"]controller and the two-controller layout both name their
operations apart. - What survives is reported, not published silently: two controllers whose
names reduce to one token — differing only by theControllersuffix or by
casing — raise awarnonnest_rs::openapinaming both addresses. Never a
boot failure: a duplicate id degrades a generated client, it does not break the
running app. demo/apps/api/openapi.jsonregenerates to 27 operations with 27 distinct ids
and boots with no warning.
TestApp boots the transport the app configured, not a fresh one
TestApp::build constructed a bare HttpTransport::new(). Every field
HttpModule::for_root(cfg) sets was therefore absent under test — the global
prefix, the versioning strategy, the body cap, the request timeout, CORS,
compression, the security headers — so a suite asserted against a transport the
deployment never runs. An app pinning global_prefix: "/api" served /widgets
in its own e2e and /api/widgets in production, and every test passed.
That is the failure e2e exists to catch: the testing section of CLAUDE.md
opens with "wiring bugs don't surface in unit tests", and the wiring was what
the harness dropped.
HttpTransport::from_config(&HttpConfig)is now the one place a config
becomes a transport.HttpModule'sTransportContributioncalls it, and so
does the harness — the logic used to live inline in a closure where nothing
else could reach it.TestAppBuilder::http(transport)still overrides, for a test that needs a
transport the app does not declare. Pinning anHttpConfigon the module is
now the way to assert against non-default settings.harness_parityinnest-rs-testing's suite pins the two fields that change
a request's address, because those are the ones whose absence turns a
green suite into a404in production.
A version is declared the same way wherever a client can select one
Versioning was HTTP's, and every other transport was silent about it — so a
developer who read #[controller(version = "1")] and reached for the same word
on a resolver or a processor got "unknown key" and had to go find out what that
transport does instead. Silence is the failure of unity here, not the absence of
a mechanism: versioning is addressing, and the transports genuinely differ in
whether they have an address a client picks.
So the declaration is unified where it can be, and refused with the
transport's own answer where it cannot:
#[controller]— full, and wider than before (below).#[gateway]—version = "1"mounts the socket at/v1/ws, through the
sameversion_paththe HTTP routes use, so the two cannot word the/v{n}
prefix differently. Two gateways may share apathunder different versions;
the duplicate-mount boot error compares the versioned path.#[resolver],#[mcp],#[processor],#[scheduled],#[listeners]—
a compile error naming what to reach for instead:#[graphql(deprecation = …)]
on the field a GraphQL schema is retiring,#[mcp(path = "/mcp/v1")]for an
MCP endpoint, a versioned queue name or payload evolution for a job, and
nothing at all for a clock or an in-process event. The five sentences are
worded once innest_rs_codegen::Edge, besideDecoratorPairand
PostureRules—rg 'Edge::' crates/*-macros/src/names every site — and
each ships a trybuild snapshot.
#[processor] and #[scheduled] took an argument list and silently ignored
whatever was in it; both now refuse, version by name first.
#[mcp] refuses version in every shape. The word was briefly spelled there
for serverInfo.version, and that was one declaration too many: a feature library
knows neither the binary's version nor, on a shared endpoint, the whole surface,
so the server's version has one owner — the app's single
McpModule::for_root(McpOptions { server, .. }). A host declares only which
endpoint stands apart, #[mcp(name = …, title = …)]. The refusal points at
#[mcp(path = "/mcp/v1")] for an address and at that seam for a version.
This follows reject_http_only_layers — the framework already answers a layer
family an edge does not bridge with a named error rather than ignoring it.
Selection asks the app's real shape, and poem always decides last
Under header / media_type, the selector answers one question per request:
does a version have anything to select here? It reads three exact lists the
transport hands it at boot — the routes that carry a version, the addresses
answered without one, and the paths self-mounted endpoints own — and matches a
request against them with the router's own segment forms (:name, <regex>,
*rest, and a literal and a parameter sharing one segment: /@:handle).
Precedence, which is the whole behaviour:
- A self-mounted path is neutral against everything.
/graphql,/mcp,
/api-json, a WebSocket gateway — each owns its path outright and has no
version to be rewritten to. - A stated version beats an unversioned route at the same address. An
explicit request is the strongest signal a caller sends; yielding to a
neighbour would leave#[controller(version = …)]unreachable there. - A default version yields to it. The caller asked for nothing, so nothing
moves under them. This is what stopsNESTRS_HTTP__DEFAULT_VERSIONfrom
rewriting the whole surface: a versioned#[controller(path = "/")]with a
catch-all route would otherwise swallow every unversioned controller beside it. - A version that serves no route, while another version does, is a
404—
answering with a different version's body is the silent failure the design
exists to prevent. Where no version serves the address at all, the request is
passed through and the router answers.
The matcher answers loosely on purpose, and that is the load-bearing part.
Every outcome ends at poem: a match produces a rewritten path the router must
still recognise, a non-match passes the request on as written. So a false match
costs a 404 the request was heading for anyway, while a false non-match once
served one controller's body to a caller who asked for another's. Loose in the
direction the router can correct, never in the direction it cannot see — which
is what a first attempt at this, matching controller prefixes, got backwards
in both directions at once.
The rewrite endpoint is not installed at all when nothing is versioned. A
strategy set with no versioned controller would otherwise pay an extra routing
layer per request, forever, for an outcome it could never change. The endpoint
also resolves behind an immutable borrow, so a neutral or version-less request
allocates nothing.
Two boot-time consequences:
- A
NESTRS_HTTP__DEFAULT_VERSIONnaming a version nothing declares fails the
boot, in every app. The check used to live innest-rs-openapi, so an app
publishing no document got no answer at all and every caller stating no version
silently fell through.declared_versionsmoved tonest-rs-httpand both
consumers share it. - Two controllers overlapping on one version are told which version. The
failure used to read "give each one a distinct path" — advice against the
two-controller layout the docs prescribe, about a string (/v2/posts) neither
developer wrote.
A second API version stops costing a second controller
#[controller(version = ["1", "2"])] mounts one controller under every version
it lists, and #[version("2")] on a method narrows one route out of the rest —
the shape a real v2 has, where most routes are unchanged and one is new.
HttpControllerMetacarriesversions: &'static [&'static str]and yields one
mount per version; the boot log, the OpenAPI document and the served routes all
iterate the same list.- A
#[version]naming something the controller never declared does not
compile. It would otherwise mount nowhere — the transport loops over the
controller's versions — leaving a handler that builds, registers, documents
itself and answers nothing.versions_declareis aconst fn, so the error
lands at the route. - A declared version is validated as a path segment at compile time, the same set
the wire validator refuses at runtime. - A verb absent from a version answers
405on a path its siblings serve, not
404— the path exists, that method does not.
Response masking is armed by the compiler, so a rename cannot disarm it
#[routes] used to decide whether a route masks its response by matching a
parameter's path segment against Authorize / Bind. That is a question
about how a type is spelled, and use Authorize as Az gave a different answer
than Authorize for the same type. The hole was covered — an unarmed route ran
inside a MaskProbe and a masking extractor that ran there failed the request
closed — but the cover was load-bearing, which is exactly what the roadmap
entry existed to end.
The macro no longer asks the question. It hands each parameter type to
nest_rs_http::ShaperProbe and the compiler answers whether that type is a
RouteResponseShaper, through the two-arm autoref selection shaper_of! spells
once. A rename changes the spelling and not the type, so the alias arms
identically — an_aliased_authorize_masks_a_raw_model_body used to assert a
500 and now asserts a masked 200.
- The trait moved from "capture + run" to "capture into a
ResponseShaping".
RouteResponseShaper::capturereturns the request-independent half as a boxed
object, so the selection can be a plain function pointer rather than a type
parameter threaded through the endpoint. OneBox::pinper armed request
buys the alias-proofing; an unarmed route pays nothing it did not pay before. maskedin the OpenAPI document reads off the same selection, so a
document can no longer describe an aliased route as unmasked.- The probe stays, with a smaller job. A signature scan of any kind cannot
see an extractor reached indirectly — nested in another extractor, or run by
a hand-rolledFromRequest. That is now the only thing the500covers, and
its message says so. - The eager HTTP-D1 diagnostic survives, and got shorter: a local type wearing
the nameAuthorizewithout implementing the trait is still a spanned error
namingRouteResponseShaper, no longer trailed by a transitiveEndpoint
bound failure from the mount site.
A certificate renewal no longer needs a restart
HttpTransport::tls loaded the PEM pair once, at boot, so certbot's
--deploy-hook ended in systemctl restart. Material read from files —
NESTRS_HTTP__TLS_CERT_FILE + _KEY_FILE, or the new TlsConfig::from_files —
is now watched, and a renewed pair is swapped into the running rustls config.
The listener is not rebuilt: the port stays bound and in-flight connections
finish.
NESTRS_HTTP__TLS_RELOAD_SECS is the interval (60 by default, 0 disables).
Polling rather than an OS watch is deliberate — a renewal is a minute-scale
event, and a file watcher's hardest case is precisely the one renewal tools hit,
an atomic replace that swaps the inode out from under the watch.
Two refusals are as load-bearing as the swap: a pair that cannot be read
leaves the current certificate serving (a tool that unlinks before it writes
would otherwise take the listener down between two syscalls), and a pair is
installed only once it reads back identical twice, so a file caught mid-flush
is never the one that gets served.
The second rule is stated as what polling can actually guarantee, because a
first attempt claimed more: a renewal whose two halves land more than one
interval apart looks settled in between. Certbot and cert-manager both swap
atomically and never hit it; a_pair_that_is_still_changing_is_never_installed
pins what does hold, and the docs name the residue rather than implying it away. Inline PEM has no source to watch and is
loaded once, as before. a_renewed_certificate_is_served_without_dropping_the_listener
proves it through a real handshake: two leaves under one CA, and which hostname
verifies is the only thing the swap changes.
A version is declared once; how a caller selects one is deployment config
URI versioning shipped; Accept: application/json; version=2 and
X-API-Version: 2 did not, and the docs told you to write a guard. Now
NESTRS_HTTP__VERSIONING picks between uri (the default), header and
media_type, and no controller changes — #[controller(version = "2")]
remains the one place a version is declared and version_path the one place it
becomes a path.
The two request-time strategies are a rewrite in front of routing, inside the
global prefix, so one route table serves all three. The boot log follows: it
reports the address a client uses and moves the version into its own field,
because /v1/posts is where the route is mounted, not where it is called.
Three behaviours are decisions, not defaults:
- An unknown version is a
404, never a fallback. Quietly servingv1to a
client that asked forv9is how a client talks to the wrong API for a month. - The URI form stops being a second address under the other two strategies —
one way to ask, or every version has two names. - A malformed version token is a
400before it reaches a path. The token is
spliced into a URL, so it is validated first: alphanumerics,.and-, 32
bytes.a_version_that_could_reach_another_path_is_refusedis the witness.
NESTRS_HTTP__DEFAULT_VERSION answers a caller that states none — on the paths
that have versions. The selector learns which mounted prefixes carry one at
configure time, so a default is a default among versions and never a rewrite of
everything the app mounts: an unversioned controller, and every self-mounted
endpoint (/graphql, /mcp, /api-json, /health), is served as written.
a_default_version_does_not_rewrite_paths_that_have_no_version pins it.
The generated document follows, in the same release: OpenAPI 3.1 cannot key
two operations on one path, so a non-URI strategy publishes one document per
version — see The document describes the addresses a client actually calls
below.
An upload never exists whole, at either end
Storage grew the two methods the object-store surface was missing, and the
HTTP side grew the one seam that lets them be reached without buffering:
Storage::list(prefix)streamsObjectEntry { key, byte_size, last_modified }rather than returning aVec, so a large prefix is never
held in memory. It leaks no new third-party type —last_modifiedis a
std::time::SystemTime.Storage::put_stream(key, content_type, stream)drives a real multipart
upload, sequentially, one part in memory at a time. Every failure path —
the source stream's, a part's, the tail's, completion's — aborts the
upload first, because parts left behind are billed and invisible tolist.
A failing abort is reported atwarnonnest_rs::storagerather than
swallowed.nest_rs_http::PartExt::into_byte_stream()is the other half of poem's
Field::bytes(): the part as it arrives. The demo's direct upload now goes
part → storage without aVec<u8>anywhere, and its service names a stream
rather than a transport type, so the same method serves a multipart part, a
proxied download or a test fixture.
Streaming bounds memory, not the request: max_body_bytes remains the
ceiling, and it still covers Multipart like every other extractor.
nestrs g entity and nestrs info
g entity <feature>[/<name>] scaffolds one #[expose] entity into an existing
feature without the CRUD slice around it. Placement follows the feature: its
first entity is the lone entity.rs, and a feature already keeping several in
entities/ gets one more file there.
A feature with a lone entity.rs that now needs a second one is refused with
the four steps to take, not migrated. SeaORM spells relation module paths
inside string literals (belongs_to = "super::org::Entity"), so moving
entity.rs into entities/ either misses those or, reaching into strings,
corrupts prose that merely mentions one — silently, in code the developer wrote.
nestrs info reports the project the current directory sits in — layout, root,
apps, features, the framework version the manifests pin, the env prefix in
force, the toolchain — and says so plainly outside a project rather than
failing. That is the line between it and about: about is seven lines
identical on every machine, info reads the tree it stands in.
A relation is a page, an enum is a declaration, and a second foreign key no longer needs a hand-written resolver
Three gaps in #[expose], closed independently.
#[wire_enum] — the enum half of the umbrella promise. An exposed enum column
made the developer hand-write nine derives and put schemars and async-graphql
in their manifest for nobody's code but the macro's. #[wire_enum] emits the wire
derives with their crate = overrides routed through nest-rs-resource, and
#[wire_enum(graphql)] adds async_graphql::Enum. It deliberately emits none
of the SeaORM half — DeriveActiveEnum, rs_type, the per-variant string_value
— because how a column is stored is the developer's decision, and their own
source legitimately writes it.
The graphql flag is explicit rather than read off the crate feature: a Cargo
feature is additive across a workspace, so one GraphQL app would otherwise put an
Enum derive on every enum in every sibling crate.
nest-rs-macro-hygiene gains its first witness from the #[expose] family: an
entity cannot live in a zero-dep crate, but an enum can, so the derive routing
that was invisible to review is now compiled against nest-rs and nothing else.
Connection<T> — a relation you can page, and a defect that is gone rather than
documented. An auto-emitted HasMany resolver returned a Vec<T> capped at
RELATION_LOAD_CAP (100 per parent) through one WHERE fk IN (…) LIMIT cap × keys
query — a shape in which low-FK parents could consume the whole budget and leave
later parents with [], indistinguishable from "no children" (DATA-R2). The field
is now a Relay Connection with first / after / PageInfo, backed by a new
Repo::relation_pages that ranks with ROW_NUMBER() OVER (PARTITION BY fk ORDER BY pk) — one round trip, a page per parent.
RELATION_LOAD_CAPis deleted, and so is the DATA-R2 comment. Both existed
only to bound the broken shape and make its starvation loud.clamp_page_size
(1..=100) is the only bound now, withDEFAULT_PAGE_SIZE = 20.- The loader key carries the window (
RelationKey { parent, first, after }).
Keyed on the parent alone, two sibling selections asking for different pages of
one relation would be served the same batch entry. - The
afterpredicate is inside the ranked subquery, and a unit test asserts
the SQL text says so. Applied outside, a parent's rank would count rows the
caller already has and page 2 would come back short — a bug that returns exactly
as many plausible rows as a correct query, which is why the assertion is on the
text and not the count. - Complexity is
first * child_complexityinstead of a flat10 *. The
constant was a guess because there was nothing to multiply by; the field now
takes its page size, sofirst: 5costs a twentieth offirst: 100— which is
what a ceiling is for. A 3-deep unannotated chain scores 20³ against the
documentedmax_complexitydefault, and that is the ceiling working on a query
that really can materialise 8000 rows. - Masking is unchanged and still per item, in the loader.
unmaskedturns out to
be irrelevant here rather than needed: a#[ComplexObject]field resolver is not
an#[operations]operation, so the value-level round-trip never sees the
connection.
last / before are deliberately absent: the underlying keyset is forward-only,
and a backward argument would be a lie in the SDL.
via = "…" — naming which foreign key, when the type cannot. The ambiguity was
always on the has_many side: a belongs_to names its column in from = "…",
while the parent had only the child's entity type, and RelatedTo<Parent> was
keyed on that type alone. Two belongs_to at one parent meant two impls of one
trait, which is why the macro used to refuse the shape outright.
RelatedTo<Parent, Via> now carries a per-FK marker the child's #[expose] emits,
and the SoleForeignKey default impl is emitted only when the child targets that
parent exactly once. That absence is the enforcement: the ambiguous case fails to
compile at the relation that is ambiguous, with a note naming
#[expose(via = "…")]. The framework never picks whichever belongs_to came
first. (via on a HasOne is a compile error pointing back at from.)
One half stays the developer's, and it is SeaORM's rule rather than ours: two
relations to one entity need relation_enum / via_rel on the entity itself.
That is entity-site code their own source writes — and sea-orm gates its own
Related<E> impl on the same "targeted exactly once" rule.
The document describes the addresses a client actually calls
Shipping header and media-type versioning left the generated document naming
/v1/posts while clients had to call /posts plus a header — paths that answer
404. A document that lies is worse than one that omits, so it was recorded on
the roadmap the day it appeared and is closed here.
Under a non-URI strategy the path keys become the client-facing ones and each
operation gains its version parameter — the configured header, or Accept for
media-type — required exactly when the deployment names no default. OpenAPI 3.1
keys operations by path, so two versions cannot share one entry; each version
gets its own document at /api-json/v{n}, built through version_path rather
than a second format! so the document's own address and the routes it describes
cannot disagree about the /v{n} spelling. /api-json describes the default
version when one is named, and otherwise aggregates, resolving a contested path
to the highest version — deterministic and stated, where link order would have
been neither.
Under the URI strategy nothing changes: same paths, same operations, no
version parameter, no extra route, and the committed document's line order is
left exactly as discovery hands it over — an aggregate sort that reordered a JSON
object would have rewritten every line of a committed snapshot for no reader's
benefit.
A NESTRS_HTTP__DEFAULT_VERSION naming a version no controller declares now
fails the boot. It used to publish an empty document to every client that
read it.
The second half of the entry is smaller and older: a required Query<T> property
produces a 400 the document did not advertise, while a required header already
did. One rule computed from the parameters actually emitted now covers both, and
the committed snapshot moved with it.
Every #[expose] diagnostic is pinned, and pinning them found three that were wrong
#[expose] raised 27 distinct compile errors, #[wire_enum] four more, and
nothing pinned any of them — eleven other macro crates carry a trybuild
suite, this one did not. It does now: crates/nest-rs-resource/tests/integration/diagnostics/,
31 .rs/.stderr pairs, same arrangement as its siblings.
Writing them down is not the point; reading them back is. Three of the 31
were wrong, and two of those had shipped:
#[expose]on an enum answered with syn'sexpected struct. It now names
its sibling#[wire_enum], mirroring the refusal that already went the other
way. Each half's name is aconstthe other one's message reads, so neither
can name a decorator that has moved.from = "…"naming a column that does not exist claimed the column was
"not exposed" while checking only existence — two different remedies, one
message. The two copies of that check became one function.from = "…"naming a column that exists but is unexposed passed silently,
then failed asno field `org_id` on type `Post`from inside the expansion,
because the field resolver reads the key off the wire object. It is refused at
the field now, naming both remedies.
Two diagnostics are deliberately unpinned and say so in the suite's header: the
graphql-feature refusals cannot exist in a build that can run the suite (the
dev-dep that compiles the GraphQL fixtures turns the feature on), and pinning
them would need a third suite name, which is locked.
#[crud]'s GraphQL list op also stopped spelling its own 20 and reads
nest_rs_seaorm::DEFAULT_PAGE_SIZE. The HTTP half never drifted — it reads
PageParams::limit(), which reads the constant.
The document stops omitting the three shapes it could not describe
Header parameters, multipart request bodies and streamed responses were invisible
to the generated OpenAPI document: /audio/uploads/direct carried no
requestBody at all, the streamed download and the SSE feed carried a bare
"200": {"description": "OK"}, and no operation anywhere declared a header. The
docs page even promised a Header<T> extractor that did not exist.
nest_rs_http::Header<T> now does — the header-map twin of poem's
Query<T>: one struct field per header, #[serde(rename)] for the wire name,
case-insensitive lookup, values parsed into the field's type, Option<_>
optional. It composes like every other extractor (Valid<Header<T>>,
Piped<P, Header<T>>), and the operations that read one describe it.
Its rejections name the header and never quote its value. Headers carry
credentials, so a compound shape is refused by our own arm rather than left to
serde, whose invalid_type message would print the value it could not parse.
The two body shapes follow the same rule — say what the framework emits, never
guess:
#[api(multipart = T)]documentsmultipart/form-datawithT's schema.
A handler takingpoem::web::Multipartand declaring nothing still documents
multipart/form-datawith a free-form object, because silence was the defect.
The two are one enum, not a media-type string beside an optional schema, so
"media type disagrees with schema presence" is unrepresentable.#[api(response_content_type = "…")]declares a non-JSON success body and
gets the stream schema that goes with it. SSE is inferred from-> SSE:
that return type serializes astext/event-streamand nothing else, so reading
it off the signature states a fact rather than repeating a declaration — the
same reading that already infers the response schema from-> Json<T>. An
explicitresponse_content_typestill wins.
A required header also makes the operation advertise its 400, computed from the
parameters actually emitted, so an all-optional header DTO adds nothing.
The demo carries a real use site rather than a stub: GET /audio/events reads
Last-Event-ID, so a reconnecting EventSource is not re-sent progress ticks it
already displayed.
The docs say which pages you need and which ones you may not
A section was one flat list, so Controllers, Extractors, Compression,
Versioning and File uploads read with the same weight and nothing told a
newcomer which four to open. Every section of five or more pages now splits into
Basics — what you need to ship the section's common case — and All
options — configuration and tuning, opt-in capabilities, operational
behaviour, extension seams, reference tables.
The mechanism keeps ordering in one place: a page declares tier: in its
frontmatter, sidebar.order still sorts within a tier, and
docs/src/sidebar.mjs builds the groups. Adding a page needs no config edit and
cannot be silently dropped from the sidebar. Both halves fail closed — a missing
or unknown tier stops the build, and lint:docs reports it — and
STYLE.md §G states the rule so a new page inherits it.
The tier follows why a reader opens a page, not its content mix, which is
what puts http/extractors (a reference page you read to write a handler) in
Basics and websockets/guards in Basics against the size logic — "All options"
must never read as "security is optional".
GraphQL subscriptions, and a posture that keeps applying after it is granted
#[subscription] joins #[query] and #[mutation] in the same #[operations]
impl, under the same mandatory posture, served over graphql-ws on the path that
already serves POST — an upgrade takes the socket, a plain GET still takes
the playground. The discovered schema builds with a real subscription root;
EmptySubscription is gone, and a schema that declares none still carries no
Subscription type.
What is new is not the operation kind but when the declaration is enforced. A
query's posture is spent once. A subscription's is not: the guard decides at
subscribe, and items keep arriving afterwards.
- The mask moved onto the stream. Every item is evaluated against the
ability captured at subscribe — row rules first, then field grants — and an
item outside the grant is dropped, never nulled. Two subscribers on one
stream therefore read two different sequences, which is the whole guarantee;
an_item_outside_the_grant_never_reaches_that_subscriberis the witness. - A socket may not outlive the decision that opened it.
NESTRS_GRAPHQL__MAX_CONNECTION_SECSis the same control, spelling and
four-hour default as a WebSocket gateway's, and it is now asserted rather than
configured: a connection that never ends is closed when the deadline elapses. - Three things the upgrade lends, and one it does not. The principal and its
ability travel with the connection. A database handle travels too, but always
outside the upgrade's transaction — carrying it would pin a pooled
connection for hours and write through something the101already finalized.
TheRequestScopedoes not travel at all: a request-scoped provider built once
at connect and shared for four hours is not request-scoped, soScoped<T>
reports it absent instead of handing back something that looks right. GraphqlOperationGuard::aroundscopes a()future, so one method covers
one operation and one socket. Without it the socket ran with no ambient
ability and every subscribe was refused — the guard chain was correct and the
state it reads was missing.- Two compile errors that name themselves: a
#[subscription]must be
async, and a fallible one spells its returnResult<…>literally
(async-graphql reads the last path segment, so an aliasedResultis taken for
an ordinary value). A third, wider one landed with them: an operation taking a
Piped<P, T>argument must returnResult<…>, because a pipe rejects and the
rejection has to reach the client. TestApp::graphql_socket()drives the graphql-ws protocol in-process, so a
suite asserts what a subscriber receives without binding a socket.
A decorator may not put a line in your manifest, and now something checks
#[crud] emitted ::uuid::Uuid for three HTTP routes and one GraphQL resolver
argument. A controller file names std, nest_rs and crate:: — never uuid
— so a crate that wrote #[crud] and nothing else failed with E0433 blamed on
the attribute, against the hard "no" that a macro expansion never obliges the
developer to declare a crate.
It survived two witnesses. nest-rs-macro-hygiene cannot reach #[crud] (it
needs a real entity and service, documented and still true), and the generator's
e2e — the substitute witness — passes for an unrelated reason: g resource
bootstraps g auth, whose claims type names uuid and drags the dependency in.
Remove the auth adapter and the generated CRUD stops compiling.
- Routed through
::nest_rs_resource::uuid, whose re-export exists for this
and is unconditional —nest-rs-seaorm's ownuuidis optional behind two
features, so routing there would have made resolution depend on which
transport the crate enabled. - The rule became a test.
framework.mdhas always stated it as checkable —
"a*-macroscrate emits only::std/::corepaths or paths routed through
its surface crate's re-exports — never a bare third-party path" — and nobody
had run it.nest-rs-macro-hygiene/tests/integration/emissions.rsreads every
macro source and fails on a path rooted outside the framework. It is an
allowlist, not a banned-crate list: a decorator written next year reaching for
a crate nobody thought to ban fails on the day it is written.
Two transports could contradict themselves at boot; both now refuse
GraphQL — two resolvers claiming one operation name. The merge folds member
fields with IndexMap::extend, so the last registration's metadata reached the
schema, while resolve_field returns from the first member that answers. A
client read one resolver's signature from the SDL and reached another resolver's
body, with the argument it was told to send dropped. Both orders follow
inventory::iter — link order. The security half is why this is an error rather
than a warn: #[authorize] expands inside the operation's body, so the
posture that ran belonged to whichever body won the dispatch, not to the
operation the schema documented. Now an HttpBootCheck naming both resolvers,
the seam MCP already used. A query and a mutation may still share a name — two
root objects, not a collision.
Queue — two #[process] methods claiming one queue. A backend builds one
worker per registry entry, so both polled the same stream: each job went to
whichever popped it, and the retry budget forked with it. nest-rs-queue owns
the check (any backend draining the registry owes the same refusal) and
QueueWorker::configure runs it after module-gating, so a processor another app
owns cannot fail this app's boot.
Every client-facing transport withholds what a client must not read
A handler's error type is the framework's only source for the message a client
reads, and Display is the wrong default: a DbErr carries SQL, column names
and sometimes row values. MCP had the seam first, because its reader is a
language model that may repeat what it is told — but a GraphQL error frame, a WS
error frame and an HTTP error body are read by clients just as untrusted.
nest_rs_graphql::Opaque,nest_rs_ws::Opaqueandnest_rs_http::Opaquejoin
nest_rs_mcp::Opaque:.opaque()?logs the real error aterroron the
transport's own target and substitutes the shared
nest_rs_core::OPAQUE_CLIENT_MESSAGE.- Four traits, one constant — deliberately, and the reason is measured rather
than aesthetic. The trait's output is the transport's error type, which is
what lets.opaque()?infer from the enclosing function's return type; one
trait generic over the output has four applicable impls, so the receiver stops
deciding and every call site needs a turbofish. Sharing stops at the value the
four must agree on. - GraphQL's opaque error carries the same
INTERNALcode an internal denial
does, so a client cannot tell an unexpected failure from a refusal it was owed
no explanation for. HTTP's is aProblemDetails500 for the same reason: the
envelope a client parses must not change because the reason is withheld. - The three non-request edges get no trait and want none — a job, a tick and an
event have no caller to tell anything. - One site on the WS edge bypassed the seam it already had, and it was the
one nothing could see:WsReply::replybuilds the frame from a handler's
return, and when that value would not serialize it handed the socket
serde_json::Error'sDisplay— which names the handler's types and can
carry the value that failed — while emitting no event at all. Its neighbour
pipe_errorhad learned the same lesson a release earlier and says so in its
own doc. It now routes throughOpaquelike everything else: the operator
gets the cause onnest_rs::ws, the client gets the constant. A reply that
cannot be built is the server failing, not the caller.
The testing harness can watch a thread it did not start
LogCapture is thread-local — set_default, which is what keeps parallel tests
from reading each other's events. That is the right default and it is blind in
one place, and the place is not a corner: an event the framework emits from a
task it spawned — a spawn_blocking write, a socket's writer half — never
runs on the test's thread, so the assertions worth writing were exactly the ones
that could not be.
LogCapture::install_global()captures on every thread for the rest of the
process. Sound because nextest gives each test its own process; permanent,
becausetracingallows one global default and offers no way back. It panics
if anything already took the slot — including anAppboot, which installs
the console fallback — so it is the first statement of a test, never a line
near the assertion. Never besideinstall(): a thread-local default shadows
the global one silently, and a negative assertion then passes for the wrong
reason.LogCapture::expect_none(target, message)is the quiet half, worded once. A
negative log assertion is the easiest to write and the easiest to write
uselessly — it passes when the event is absent, and equally when the target is
misspelt or nothing ran — so the panic names both coordinates and dumps what
was captured, which is the half a hand-rolled
assert!(logs.find(..).is_empty())keeps leaving out.
The diagnostics each pair owed
Eight snapshots existed; seven were missing, all for pairs whose wrong shape
reported syn's expected impl instead of naming the sibling.
#[processor],#[scheduled],#[listeners],#[indicators]and#[hooks]
each get their wrong-shape case —schedule,eventsandhealthhad no
diagnostics suite at all.- MCP gets the two GraphQL and WS already had: the no-posture refusal and the
reject_http_only_layersone. Both fixtures decorate the impl half only —
pairing them with#[mcp]cascades a second error about theServerHandler
the refused expansion never wrote, pinning rmcp's internals in a snapshot whose
job is one sentence of ours. - That last snapshot caught a wording bug in the shared helper: the fifth caller
passes"operation", and the template saidon a {site}.
Every decorator is now witnessed, and the two exclusions are separated
#[config], #[queue], #[processor], #[indicators], #[interceptor],
#[redirect] and #[dataloader] gained use sites in nest-rs-macro-hygiene,
which required adding config, health and queue to its single dependency's
feature list — the assertion being that each capability's feature pulls
everything its decorators emit. #[dataloader] reads as needing a data layer
because its intended use runs each batch through Repo; the macro only reads a
key type off the argument and a value type off the return, so it belongs where
the manifest is the assertion. Writing it surfaced a real constraint now
recorded there: Loader::Error is bound Send + Clone + 'static, one error
being handed to every caller waiting on a batch.
#[crud] and #[expose] stay out, but no longer for one reason. An entity
cannot live in a zero-dep crate — DeriveEntityModel roots its expansion at the
call site's sea_orm and offers no crate = override, checked against
sea-orm-macros 2.0 rather than assumed. That excuses #[expose], which sits on
an entity. It does not excuse #[crud], which sits on a controller whose source
writes nothing but std, nest_rs and crate:: — and that conflation is what
let the uuid emission ship.
So #[crud] gets the tree that can actually observe it:
crud_needs_no_dependency_the_controller_does_not_name generates a resource,
drops the auth modules from the module tree, the guards from the controller and
uuid from the manifest, leaving a crate whose only claim on uuid is whatever
the decorator emits. Reintroducing the bug fails it while
a_generated_crud_resource_compiles still passes — which is the measurement of
what the older test was worth here.
A guard bound where it does not run is a compile error
Every Guard::check_* defaults to Ok(()) — right as "this guard does not apply
to that transport", and also the reason this compiled, read as a protection, and
throttled nothing:
#[resolver]
#[use_guards(ThrottlerGuard)] // ThrottlerGuard implements only check_http
pub struct PostsResolver { /* … */ }The per-operation chain called check_graphql, got the default, and passed. The
fix is a bound rather than a boot check: it fails at the #[use_guards] line, and
needs no plumbing into the four places each transport composes its chain.
GraphqlGuard/WsGuard/McpGuardinnest-rs-guards, each a marker a
guard declares beside thecheck_*it attests.#[resolver]/#[operations],
#[messages]and#[mcp]/#[tools]emit one bound per declared guard;
#[diagnostic::on_unimplemented]names the missing method and the two remedies.
Three trybuild snapshots pin the wording.- HTTP has no marker.
check_httpis the trait's base entry — the one method
not behind a feature — soHttpGuardis blanket-implemented and the bound could
never fail. Emitting it would prove something already true, per route, per guard. - A
#[gateway]-struct guard is an HTTP guard, and the bound is where that
stops being folklore: those run on the upgrade, which is aGET. Only a
#[use_guards]beside a#[subscribe_message]owesWsGuard. - It found a live one on the first run.
demo's three GraphQL resolvers bound
#[use_guards(AuthnGuard, AuthzGuard)], andAuthnGuardhas nocheck_graphql
— on a resolver it ran nothing, authentication having always been the bridge's
job in band. Dropped; the dependency lives on the bridge, which is what runs it.
All 88 demo e2e tests pass unchanged, which is the proof it was inert.
WebSocket messages declare a posture, and the mask comes with it
A #[subscribe_message] returning entity rows had to mask them by hand:
// before — the posture is an argument buried in a call nobody can `rg` for
async fn list(&self) -> Result<Value, ServiceError> {
let rows = self.svc.list().await?;
let wire = serde_json::to_value(rows.iter().map(User::from).collect::<Vec<_>>())
.map_err(|e| ServiceError::Masking(e.to_string()))?;
masked_reply::<UserEntity>(Action::Read, wire)
.map_err(|e| ServiceError::Masking(e.to_string()))
}
// after — `#[messages]` emits the gate and the mask
#[subscribe_message("users.list")]
#[authorize(Read, UserEntity)]
async fn list(&self) -> Result<Vec<User>, ServiceError> {
Ok(self.svc.list().await?.iter().map(User::from).collect())
}Two things were wrong with the old shape, and the second is the serious one. The
posture was an Action::Read argument rather than a greppable #[authorize],
against this repo's rule that every authn/authz decision be findable at one of
three sites. And a handler that simply forgot the call shipped unmasked rows and
compiled — on GraphQL and MCP that is a compile error.
- Breaking, and deliberately loud. Every
#[subscribe_message]now declares
#[authorize(Action, Entity)]or#[public]; no posture is a compile error
naming both forms.#[public]used to be rejected on a message (there is no
anonymous fast-path to take on WS) — it is now the declaration that the posture
was decided and the message is deliberately ungated. nest-rs-authzgains awsfeature:ws::authorize(the class gate, whose
decision is the same sharedgateGraphQL and MCP use) and
ws::masked_reply_for(the reply mask). NoWsAbilityBridge— a gateway is
EdgePosture::Guarded, so its upgrade already ran the real HTTP chain; the
ambient ability comes fromWsDataContextas before.- A gate refusal and a guard refusal reach the client through one frame, via a
newdenial_to_ws_errorcarryingreasonandrequiredScopesunder
data.errors— where every other structured rejection on this transport rides. - WS masks like HTTP, not like MCP. GraphQL and MCP reconstruct the return type
after masking, so a stripped required key refuses the operation. A WS envelope
carries JSON and promises no schema, so the key is simply absent from the frame,
exactly as the HTTP response shaper omits it from a body — a field-restricted
caller reads a smaller object, and the reply type needs noDeserializeOwned.
Fail-closed is reserved for a missing ambient ability and a body that cannot be
reconciled with the entity at all. - One compile rule, whose reason is not masking: a masked message returns a
literalResult<T, E>, because the reply shape is decided syntactically and
aResultbehind an alias would be masked as theResultitself — a
success-shaped frame carrying{"Ok": …}. - Ordering per message is chain → gate → pipes → call → mask, so a caller the
gate refuses never pays for validation.
Every decorator pair names its sibling on the wrong shape
The rule shipped with the MCP pair; only GraphQL and MCP obeyed it.
#[controller]/#[routes] and #[gateway]/#[messages] still reported syn's
expected struct — the error the rule exists to forbid, since the shape the
developer reached for does exist and is spelled with the other decorator.
- All six pairs now parse through one
DecoratorPairconst per edge, read by
both halves, so the two sentences cannot drift into naming a decorator that
no longer exists. Eight trybuild snapshots (two per pair) pin the wording. - The impl-half decorators whose struct half is the generic
#[injectable]—
#[processor],#[scheduled],#[listeners],#[indicators],#[hooks]—
get the same treatment throughDecoratorPair::on_provider, naming
#[injectable]and the methods they collect instead ofexpected impl. - The posture grammar is deduplicated the same way: one
PostureRulesin
nest-rs-codegen, adopted by#[tools]and#[messages]. GraphQL keeps its
own parser, which carriesbind = Service/id_argthat no other transport
can express.
One decorator, one item shape
#[resolver] and #[mcp] each answered to two item shapes — the struct and its
impl — and nothing else in the framework did. An attribute macro is a single
path in the macro namespace: the shape is discriminated after syn::parse, so
the name bought one rustdoc page for two argument grammars, one symbol for
go-to-definition, and the same in this expansion of #[mcp] note on every error
whichever half emitted it. rg '#\[mcp\]' could not tell a host from an
operations block either — and this repo's security rules lean on exactly that
kind of grep. Both are now pairs, like every other edge:
| Edge | on the struct | on the impl |
|---|---|---|
| HTTP | #[controller(path)] |
#[routes] |
| WS | #[gateway(path)] |
#[messages] |
| GraphQL | #[resolver] |
#[operations] |
| MCP | #[mcp] |
#[tools] |
#[mcp]
#[use_guards(TenantGuard)]
#[derive(Clone)]
pub struct UsersTool { #[inject] svc: Arc<UsersService> }
#[tools] // was: a second #[mcp]
impl UsersTool { /* #[tool] / #[prompt] methods */ }- Breaking, with no shim. Rename the impl-block attribute and add the
sibling to the import:use nest_rs::graphql::{operations, resolver};,
use nest_rs::mcp::{mcp, tools};.#[crud]is unchanged — it still stands in
for the impl-form decorator and now re-emits under#[operations]. - The wrong shape names its sibling.
#[mcp]on an impl does not report
"expected struct"; it says the methods go under#[tools], and vice versa.
Four trybuild snapshots pin the wording. - The impl half is named for what it collects, the way
#[routes]and
#[messages]are.#[tools]carries#[prompt]methods too: rmcp routes both
through the oneServerHandlerthe expansion writes, so they are one host's
operations. MCP keeps the protocol's name on the struct — the role word moved
to the impl half, where a host's methods are.
The rule is now in the hard "no" list, with a testable form: an entrypoint in a
*-macros crate matches at most one Item:: variant.
MCP operations take the request layers every other edge has
#[mcp] mounted on the HTTP transport from the start, but an operation was the
one handler in the framework that could not declare anything about itself: no
guards, no access posture, no pipes. A tool wanting validation wrote
params.validate().map_err(…)? by hand — the inline edge conversion the layer
rules call drift — and a tool returning entity rows shipped them past a mask
that was never armed. That is closed: an MCP operation now declares the same
things a #[query] does, expanded in the same order.
#[mcp]
#[use_guards(TenantGuard)] // host scope, like a #[controller] / #[resolver]
#[derive(Clone)]
pub struct UsersTool { #[inject] svc: Arc<UsersService> }
#[tools]
impl UsersTool {
/// List the people the caller may see.
#[tool]
#[authorize(Read, UserEntity)] // class gate + response mask
async fn list_people(
&self,
Parameters(page): Parameters<Valid<PageDto>>, // validated before the body
) -> Result<Json<Vec<User>>, McpError> { /* … */ }
}- Posture is mandatory, and that is a breaking change. A
#[tool]/
#[prompt]carrying neither#[authorize(Action, Entity)]nor#[public]is
a compile error, for the reason it already was on a#[query]: an operation
nobody thought about must not ship ungated and unmasked to a language model.
Every existing host needs one line per operation. - Guards bind per host and per operation.
#[use_guards(...)]on the struct
and beside an operation compose into one chain per site, memoized per app in
theSiteChainCellGraphQL already used — extracted rather than copied, since
this is the second in-band transport to need it.Guardgrowscheck_mcp,
whose context carries the app and which operation is running; the caller's
Abilityis ambient, so a capability-only guard reads it the same way it does
on HTTP. - The edge checks the request; the chain checks the operation.
/mcpgates
the HTTP request at itsMcpOperationGuardand the operation in band, and the
two are different questions —check_httpagainst a request,check_mcp
against an operation — so neither shortens the other. (This shipped first as a
reported-and-subtracted set,McpOperationGuard::already_ran; Registering a
global guard could open/mcpinstead of closing it above is what replaced
it, in the same release. That method is not part of 4.0.0.) - Pipes reach the fifth transport.
Parameters<Valid<T>>/
Parameters<Piped<P, T>>exposeTas the operation's JSON Schema — a client
never sees the carrier — and a rejection isinvalid_params(-32602)
carrying the field errors, which is the one MCP error a model can act on. - Response masking is automatic, and fails closed.
#[authorize]masks the
returned value through the caller's field grants,Json<T>unwrapped and
rewrapped so the structured content is what gets masked. MCP has no selection
set to excuse a stripped required field the way GraphQL does, so such a
mask refuses the operation rather than serving the row;unmaskedis the
opt-out for a deliberate projection.#[authorize]on aCallToolResultis a
named compile error pointing at it, rather than a trait bound failing inside
the expansion. bind = Servicehas no MCP form, and says so. A resolver exposes named
scalar arguments a wrapper can turn into an id; an operation takes one
Parameters<T>struct no macro may reach into.- The authored method keeps its signature. The expansion emits a delegating
wrapper carrying#[tool(name = "…")]rather than rewriting the body, so a
unit test still calls the method directly, the wire name stays the authored
one, and a compile error about the body points at the body.
nest-rs-macro-hygiene now consumes the guard chain and the pipe carrier, still
on its single nest-rs dependency — the compile-time proof that none of this
puts a second line in a host's manifest.
A tool host writes one decorated impl
MCP was the only edge in the framework that made a developer write three blocks
and name a foreign trait. #[mcp] now decorates the impl too — the same name
as on the struct, because it is one concern and because a #[tools] sitting a
letter from the #[tool] beneath it would read as a typo.
#[mcp]
#[derive(Clone)]
pub struct UsersTool { #[inject] svc: Arc<UsersService> }
#[mcp]
impl UsersTool {
/// List the people the caller is allowed to see, by name.
#[tool]
async fn list_people(&self) -> Result<String, McpError> {
let rows = CrudService::list(&*self.svc).await.opaque()?;
Ok(rows.iter().map(|r| r.name.as_str()).collect::<Vec<_>>().join("\n"))
}
}Gone from the file: #[tool_router], #[prompt_router], #[tool_handler],
#[prompt_handler], impl ServerHandler, get_info, ServerCapabilities,
ServerInfo, description = "…" — and use nest_rs::mcp::rmcp;, the import
whose only job was someone else's macro hygiene and which the CLI template
shipped with three lines of comment explaining it.
use rmcp;is gone for good, not hidden behind a prelude. The expansion
emits rmcp's macros inside a private child module that carries the import.
Two Rust facts make it sound, both asserted in
nest-rs-mcp/tests/integration/mcp_impl.rs: an inherent impl may live in any
module of the defining crate and still reach the parent's private fields, and
an item's own visibility — not the module it sits in — decides who may name
it.#[tool]and#[prompt]reach#[mcp]as inert tokens, so they need no
import either.- The second fact is load-bearing. rmcp generates
tool_router()without
pub, so reading it from the parent silently yields an empty tool list and
the duplicate-tool boot check would go blind. The expansion emits its own
pub(crate)accessor;DefaultToolRouteris replaced by
DefaultDeclaredTools. - Capabilities are derived from the operations present. A
#[tool]method
advertisestools, a#[prompt]methodprompts, and nothing claims a
surface no method serves. This closes a silent defect the CLI template itself
shipped: every scaffolded host declaredimpl ServerHandler for T {}, routing
tools it never advertised, so a client reading capabilities could decide never
to ask. - Descriptions come from the doc comment. The sentence was written twice —
once for a reader, once for the model — and two copies of one sentence drift. Opaque::opaquecarries the log-real/return-opaque posture. A tool body
talks to a language model, and aDbErr'sDisplaycarries schema, column
names and sometimes values. Three features had hand-rolled the same four
lines; it is one call now, and the real error still reaches the operator at
erroronnest_rs::mcp. A deliberateMcpError::invalid_paramsis returned
directly and never routed through it.- The escape hatch is explicit. A host serving a hand-written
ServerHandlersurface (resources, completion) cannot have a second one
generated beside it, so it stays on rmcp's raw shape;#[mcp]on a trait impl
is a compile error saying so.demo'spostsis that host, kept deliberately
as the witness of the raw form.
The endpoint is declared where the tools are
An MCP host's path is now optional, and every argument that says what the
endpoint is moved onto the decorator. A feature contributing tools to the
app's server writes a bare #[mcp]; one that wants its own endpoint writes the
whole URL path.
#[mcp] // → /mcp
#[mcp(path = "/mcp/posts", name = "assistant-posts")] // → /mcp/posts-
The path is a join key, not a namespace. Unlike a
#[controller]'s,
nothing nests under it: it names the one endpoint the host joins, which is why
peers writing the same path share it. So it is written whole, the way a client
config carries it, andnest_rs_mcp::DEFAULT_PATH(/mcp) is what a bare
#[mcp]takes — a constant, not configuration, because no other mount path in
the framework is settable from the environment either. -
Two spellings of one mount are one owner.
Route::nestappends a trailing
/internally, so/mcpand/mcp/collapse to one key inside poem and route
assembly panics — whileclaim_exclusive_path, written to keep exactly that
from reaching poem, compared the two raw strings and saw two owners.
HttpEndpointMeta::newnow normalizes, so every self-mount is canonical before
anything compares it: MCP, WS, OpenAPI, and GraphQL, whose path is deployment
input (NESTRS_GRAPHQL__PATH) rather than a literal an author controls. New
public surface onnest-rs-http:normalize_mount_path. -
Identity moved to its two real owners. The app declares itself once,
throughMcpOptions { server: Some(McpIdentity::new(name, version)) }— its
name,version, branding, and theinstructionsa client may fold into the
model's system prompt. All of it is the app's because a shared feature library
knows neither the deployment's version nor, on an endpoint several features
share, what the whole surface is. A host declares only which endpoint stands
apart —#[mcp(name = …, title = …)], each overriding the app's per field.
versionis not among them:#[mcp(version = …)]is a compile error
naming the app's seam, for the same reason the rest of the identity is the
app's. -
instructionsis not a#[mcp]argument, and writing one is a compile
error naming the seam that takes it. It describes the server; what each tool
does is already carried by its own#[tool(description = "…")]. Hosts that
write instructions throughServerHandler::get_infoare still joined when the
app declares none — a fallback, not a second spelling. -
The per-path
McpOptions::endpointslist is gone, and with it
McpEndpointanddeclared_endpoint. An app no longer restates, in its
composition root, a path its features already declare. -
Two boot errors, both naming what to fix: two hosts on one path each
declaring an identity, and a host that names its endpoint in an app that
never named itself (a name with no version behind it). An identity declared
in an app with no#[mcp]host at all still fails boot. -
One boot
warn, down from two: an endpoint neither its hosts nor the app
named reports rmcp's own build identity, which is what a client would read. -
Public surface:
McpIdentity,ResolvedIdentity,endpoint_identity,
DEFAULT_PATH,McpOptions::server. -
Migration:
#[mcp(path = "/mcp")]becomes#[mcp]; any other path is
unchanged; anendpointsentry becomes eitherserver(the app's name) or
a distinctnameon the host.
One seam per module: for_root takes one value
Configuring a module had grown a second spelling. McpModule let you chain
for_root(None).endpoint(..), and added McpModule::endpoint(..) to soften
the None — three ways to write one import, where every other module had
exactly one. StorageModule had drifted the other way: it owned a #[config]
with no for_root at all, so its config was reachable from the environment
only.
The rule is now written down (.claude/rules/framework.md, for_root — one
seam, one value, no chain): a module is configured in exactly one place, by
exactly one value. The DynamicModule it returns is opaque — no public
method on a *Setup, no second constructor on the module type. A declaration
that does not fit into the argument makes the argument grow a field, never
the seam a method.
-
McpModule::for_roottakes anMcpOptions. Server options and endpoint
identity travel together:McpModule::for_root(McpOptions { server: Some(McpIdentity::new("assistant", env!("CARGO_PKG_VERSION"))), ..Default::default() })
McpModule::endpoint(..)andMcpSetup::endpoint(..)are gone. An
McpConfigstill converts intoMcpOptions, so a call site that pins only
server options is unchanged. -
StorageModule::for_root(config)— the missing half of the dual-path
rule. Importing the bareStorageModulestill declares the dependency and
leaves the config toNESTRS_STORAGE__*. -
nest_rs_throttler::provide_guard/resolveare#[doc(hidden)]—
cross-crate seams for the store backends, never an app-facing way in. -
ConfigSetup<M, C>is the sharedDynamicModulebehind afor_root
whose whole job is "pin the config, then recurse":WsSetupand
StorageSetupare now aliases for it. Built byConfigModule::setuprather
than aConfigSetup::new, so a shared setup stays as opaque as a
hand-written one. Modules whosecollectqueues a pool or whoseregister
does more than recurse keep their own type.
for_root configures, for_feature registers
The two seams had started to overlap, and an overlap here is not cosmetic: two
factories for one config type resolve by import order, silently. imports = [AudioModule, StorageModule::for_root(cfg)] dropped cfg on the floor,
because AudioModule imports StorageModule and queued the environment-only
factory first. No warning, and the app ran on defaults.
nestrs now takes NestJS's split literally — forRoot configures a module,
forFeature registers against an already-configured one — and enforces it:
ConfigModule::for_feature::<C>()takes no value. It declares thatC
must load; the module that ownsCis where a base is pinned. A config
reachable through two seams is a config whose value depends on import order.- A pinned base supersedes a bare import's factory, wherever the two fall
inimports. NewContainerBuilder::provide_declared_factorycarries the
distinction. - Two declarations for one type fail the boot naming it
(ContestedDeclarationError), instead of letting position decide. Not
config-only:ThrottlerModuleandRedisThrottlerModuleboth bind
Arc<dyn ThrottlerStore>, so importing both is now a named failure rather
than whicheverimportslisted first. Here we exceed NestJS deliberately,
which lets the last registration win in silence. - The synchronous
App::newrefuses what it cannot resolve. It runs
registerbut never the factory phase, so aModule::for_root(cfg)used to
boot with the config simply absent — visible only as aNoneat first read.
It now runs a dynamic import'scollect(which is what made
ConfigModule::for_root()registerEnvironmenton that path at all) and
fails withUnresolvedFactoryErrorwhen a queued factory would never run. - The
for_rootobligation stays scoped tonest-rs-*, as the dual-path
rule always said. The split is who can edit the struct: you cannot touch
HttpConfig::default, soHttpModule::for_root(cfg)is your only in-code
path; your ownIssuerConfigalready has one in itsimpl Default. A
product's feature module writesfor_featureand no seam.
The ownership table lives in architecture.md, which every session loads and
which the CLI embeds into each scaffolded project's AGENTS.md.
Several module docs claimed a pinned config "wins over the environment". It
does not: the deployment's real environment outranks a pin, which only
outranks the .env cascade and the defaults. seaorm's went further and
offered the pin as a test hatch — that is the seed
(App::builder().provide(cfg)), the one tier nothing overrides. Ten sites
across seaorm, graphql, openapi, throttler, redis and the docs now
match the precedence table.
The rule has a converse, and SocialModule is what made it explicit: a
module that owns no #[config] gets no for_root. A social provider carries
its own config and its registry entry names it, so discovering a provider is
what loads its credentials — the module never learns which providers exist, and
has nothing to be configured about. SocialModule therefore stays a bare
import: giving it a seam would force a list of mutually unrelated config types,
hence type erasure, hence no duplicate detection and a hand-written Debug to
keep a client secret out of the format — all to declare something discovery had
already handled.
OpenTelemetry::init_with(config) stays the one recorded exception: the
global tracer must exist before any module registers, and its guard's Drop
flushes, so it belongs to main.
Full Changelog: v3.1.0...v4.0.0