Upgrading from 6.x to 7.0
The order that moves a 6.1 project to 7.0 — manifest, environment, HTTP vocabulary, layers, data port, deployment — and what fails when a step is missed.
7.0 is a major release, and the foundation every 7.x builds on: HTTP speaks the
http crate’s types on a server of nestrs’s own, every edge runs one pipeline
whose layers read the unit they wrap, a queue is pushed through its type and
kept on Redis Streams, a resource opens once per named instance, and every edge
runs its work through one unit-of-work port. This page is the order to take
the changes in: a 6.1 workspace goes in, a 7.0 one comes out, and each step
ends on something you can check. The
changelog says why each
change was made; this page says what to do about it.
You need the 6.1 project building, and — for a queue on Redis — its 6.x workers left running until they drain the 6.x jobs (step 18). Most steps are compile errors, so the compiler finds every site; a step that changes behaviour alone says so, and What fails if you get it wrong lists what the boot, a log or the wire shows when one is missed.
-
Move the CLI and the manifest.
nestrs updateinstalls the 7.0 CLI, whose scaffolds,lintanddoctorfollow the release. In the rootCargo.toml, thenest-rsrequirement under[workspace.dependencies]goes from6.1to7.0, and a few features move with it — the umbrella counts 30 capabilities:6.1 7.0 interceptors,exception-filtersnothing: nest_rs::core::{Interceptor, ExceptionFilter, interceptor}filtersnothing: an exception filter whose Exceptionisdyn Error + Send + Sync(step 10)workernothing: queueandschedulecarry what a job needs; the job deadline isnest_rs::core::JOB_TIMEOUTredis, for a queue on Redisredis-queue—redisalone is now the connectiongraphql, with#[authorize]on a resolvergraphqlandauthztesting, withTestAppand no other HTTP featuretestingandhttp, orHeadlessAppoauth-serverunchanged; it now enables authntoo, since its guard runs an authnStrategyCargo.toml # beforenest-rs = { version = "6.1", features = ["queue", "redis"] }# afternest-rs = { version = "7.0", features = ["redis-queue"] }redis-scheduleis new, and only a job firing once across replicas needs it (step 14). Then, in the same pass:- Move the toolchain to Rust 1.100, the release 7.0 builds on:
channel = "1.100"inrust-toolchain.toml,rust-version = "1.100"in the rootCargo.toml, and therustimage’s tag in a Dockerfile. rustup installs it on the nextcargorun; an older one makes cargo refuse before it builds anything, naming eachnest-rscrate and the rustc 1.100 it requires. - Drop
poemfrom[workspace.dependencies]and from every member that declares it, a test’s[dev-dependencies]included: nothing a nestrs application writes names it (step 8). - Move
testingoff the root line that a pre-7.0nestrs newwrote, onto each app’s[dev-dependencies](nest-rs = { workspace = true, features = ["testing"] }), so no release binary links the harness. - Deny the discarded
Resultthat a pre-7.0nestrs newleft open: add[workspace.lints.clippy] let_underscore_must_use = "deny"to the root manifest and[lints] workspace = trueto each member, which inherit nothing otherwise. - Without
seaorm, aUuidor a chronoDateTimeon a GraphQL type or operation of yours needsfeatures = ["uuid", "chrono"]on your ownasync-graphqlline, and a chrono type you serialize needsserdeon your ownchronoline. Withseaorm, nothing changes. - Raise the libraries you name beside nestrs to the floors 7.0 builds
on:
tokio1.54,uuid1.29,rmcp3.8 andredis1.8. The framework pinsredisat=1.8, so aredis = "=1.7"line of yours no longer resolves; a requirement such as1.7takes 1.8 with no edit. - A library the framework re-exported for its own expansions —
nest_rs::core::{serde, validator, schemars},nest_rs::http::{serde, validator},nest_rs::queue::serde_json— is a dependency of your own where your code names it, but forvalidator, which your code names atnest_rs::pipes::validator;#[input],#[expose]and#[config]still need none. - A script running
nestrs g resource <name>thennestrs g migration create_<name>drops the second line: the resource writes its table’s migration, from the columns it now takes (nestrs g resource posts title:string body:text). A later change to the table takes a migration of its own name,add_<column>_to_<table>. - A script running
nestrs g migration create_<name>beforenestrs g resource <name>drops the first line, for the same reason: a resource whose table a registered migration creates is refused. Over a migration you keep, write the feature and its entity alone,nestrs g feature <name>thennestrs g entity <name>.
Take the patched rustls while the lockfile moves — 0.23.44 carries RUSTSEC-2026-0285:
Terminal window nestrs updatecargo update -p rustlscargo check --workspaceThe check now fails on the calls steps 4 to 14 change. A refusal beyond them names the rule it applies: 7.0 judges every decorated method by one grammar, and the changelog lists what it refuses.
- Move the toolchain to Rust 1.100, the release 7.0 builds on:
-
Declare each process’s environment, and let
mainload it. A process that declares no<PREFIX>_ENVruns as production, where 6.x took it for development: it reads.env.productionrather than.env.development, serves no development surface, and refuses what production refuses. A local run outsidenestrs run dev—cargo run, an IDE’s run configuration, a script — declares<PREFIX>_ENV=developmenton the process; the variable cannot live in.env. A deployment that never set it sets<PREFIX>_ENV=production, which silences the boot’sno environment declared; running as productionline.6.x 7.0 #[tokio::main]on a binary’smain— an app, amigrateorseedtool#[nest_rs::main], and thetokioline a crate carried only for it dropped (its tests keep theirs as a dev-dependency)let _environment = Environment::init();onmain’s first linedelete the line and its use:#[nest_rs::main]publishes the.envcascade beforemainruns; a binary without it callsnest_rs::config::load_cascade(dir, Environment::from_env())first thingEnvironment::default()orEnvironment::from_env()expected to beDevelopmentwhen<PREFIX>_ENVis unsetProduction; branch onEnvironment::declared()to tell an undeclared process apart, or onis_deployed()for a development convenience!matches!(Environment::from_env(), Environment::Production | Environment::Staging)in aConfig::defaults()of your owna Surfacefield, read withis_open()(step 6);!Environment::from_env().is_deployed()where you branch on the profile yourselfa scaffolded project’s URLs in .envmove them to .env.developmentand.env.test; export<PREFIX>_ENV := "development"indb.justa development or test run reaching Redis on redis://127.0.0.1/, or storage onhttps://rustfs:9000with thenestrspair, with no variable setname them in .env.developmentand.env.test—<PREFIX>_REDIS__URL,<PREFIX>_STORAGE__URL,ENDPOINT,ACCESS_KEY,SECRET_KEY: no profile names an address or a credential<PREFIX>_GRAPHQL__PLAYGROUND=true,<PREFIX>_GRAPHQL__DISABLE_INTROSPECTION=falseor<PREFIX>_LOG_FORMAT=textin.env.developmentdelete the lines: a declared development or test profile serves the playground, answers introspection and writes text logs; a deployment writes JSON a scaffolded project’s .envholding<PREFIX>_AUTHN__SECRET=dev-only-insecure-secret-change-me-32bdelete that line; put <PREFIX>_AUTHN__SECRET=and the output ofopenssl rand -hex 32in.env.local(and another in.env.testif your suites sign tokens), and your own in every deployed environmenta scaffolded project’s .env.testnamingredis://localhost:6379redis://localhost:6379/1, so the suites never push on the database the development app drains#[nest_rs::main]builds the same runtime as#[tokio::main]and ends the process within the shutdown budget: under#[tokio::main], the runtime’s drop waits for every blocking call still running, so a hook abandoned while it waited on one held the exit past every bound. A secondSIGINTorSIGTERMduring the way down now exits at once, with code 130 or 143. -
Rename the variables that moved. A crate in a family puts the family first in its namespace, so the OAuth client and resource server read
<PREFIX>_OAUTH__CLIENT__*and<PREFIX>_OAUTH__RESOURCE__*— the same string as their paths,nest_rs::oauth::clientandnest_rs::oauth::resource. Rename them wherever the deployment sets them: the.envfiles, the chart’s values, the platform’s secrets.6.x 7.0 <PREFIX>_OAUTH_CLIENT__CLIENT_ID<PREFIX>_OAUTH__CLIENT__CLIENT_ID<PREFIX>_OAUTH_CLIENT__CLIENT_SECRET<PREFIX>_OAUTH__CLIENT__CLIENT_SECRET<PREFIX>_OAUTH_CLIENT__AUTH_URL<PREFIX>_OAUTH__CLIENT__AUTH_URL<PREFIX>_OAUTH_CLIENT__TOKEN_URL<PREFIX>_OAUTH__CLIENT__TOKEN_URL<PREFIX>_OAUTH_CLIENT__REDIRECT_URL<PREFIX>_OAUTH__CLIENT__REDIRECT_URL<PREFIX>_OAUTH_CLIENT__USERINFO_URL<PREFIX>_OAUTH__CLIENT__USERINFO_URL<PREFIX>_OAUTH_CLIENT__SCOPES<PREFIX>_OAUTH__CLIENT__SCOPES<PREFIX>_OAUTH_RESOURCE__RESOURCE<PREFIX>_OAUTH__RESOURCE__RESOURCE<PREFIX>_OAUTH_RESOURCE__AUTHORIZATION_SERVERS<PREFIX>_OAUTH__RESOURCE__AUTHORIZATION_SERVERS<PREFIX>_OAUTH_RESOURCE__SCOPES_SUPPORTED<PREFIX>_OAUTH__RESOURCE__SCOPES_SUPPORTED<PREFIX>_OAUTH_RESOURCE__BEARER_METHODS_SUPPORTED<PREFIX>_OAUTH__RESOURCE__BEARER_METHODS_SUPPORTED<PREFIX>_OAUTH_RESOURCE__RESOURCE_NAME<PREFIX>_OAUTH__RESOURCE__RESOURCE_NAME<PREFIX>_OAUTH_RESOURCE__RESOURCE_DOCUMENTATION<PREFIX>_OAUTH__RESOURCE__RESOURCE_DOCUMENTATION<PREFIX>_OAUTH_RESOURCE__RESOURCE_POLICY_URI<PREFIX>_OAUTH__RESOURCE__RESOURCE_POLICY_URI<PREFIX>_OAUTH_RESOURCE__RESOURCE_TOS_URI<PREFIX>_OAUTH__RESOURCE__RESOURCE_TOS_URI<PREFIX>_OAUTH__CLIENTS, the registered clients an app’s ownoauthconfig read (the demo’s)<PREFIX>_OAUTH__SERVER__CLIENTS, read bynest_rs::oauth::server::OAuthServerConfig<P>(step 9); the rest of that config moves under the module’s own domain word — the demo’sSIGN_IN_RESOURCESandDEFAULT_ORG_IDare<PREFIX>_SIGN_IN__RESOURCESand<PREFIX>_SIGN_IN__DEFAULT_ORG_ID<PREFIX>_STORAGE__BUCKET=media<PREFIX>_STORAGE__URL=s3://media(ors3://media/some/prefix)<PREFIX>_STORAGE__ENDPOINT=(empty for AWS)unset <PREFIX>_STORAGE__TLS_CERT/TLS_KEY, set and ignoredremoved: the boot now fails naming them <PREFIX>_HTTP__FAIL_SECURE_STRICTremoved: no mount is left for it to guard, and the boot says it retired <PREFIX>_HTTP__CORS_MAX_AGE<PREFIX>_HTTP__CORS_MAX_AGE_SECS, whole seconds from1to86400, or0for noAccess-Control-Max-Age<PREFIX>_HTTP__CORS_EXPOSED<PREFIX>_HTTP__CORS_EXPOSED_HEADERS, the field it sets<PREFIX>_HTTP__SECURITY_HEADERS<PREFIX>_HTTP__SECURITY_HEADERS_ENABLED<PREFIX>_HTTP__HSTS,FRAME_OPTIONS,CONTENT_TYPE_OPTIONS,REFERRER_POLICY,CROSS_ORIGIN_OPENER_POLICY,CROSS_ORIGIN_RESOURCE_POLICY,CROSS_ORIGIN_EMBEDDER_POLICY,PERMISSIONS_POLICY,CONTENT_SECURITY_POLICYthe same name after SECURITY_HEADERS_:<PREFIX>_HTTP__SECURITY_HEADERS_HSTS, …<PREFIX>_REDIS__WORKER__SHUTDOWN_TIMEOUT_SECS<PREFIX>_QUEUE__SHUTDOWN_TIMEOUT_SECS(step 17)<PREFIX>_GRAPHQL__EMIT_SDL<PREFIX>_GRAPHQL__EMIT— on by default under a declared development profile, so a.env.developmentsetting it drops the line<PREFIX>_GRAPHQL__SCHEMA_PATH<PREFIX>_GRAPHQL__EMIT_PATH, a relative path now the app crate’s:apps/api/schema.graphqlbecomesschema.graphql, the default<PREFIX>_GRAPHQL__DISABLE_INTROSPECTION<PREFIX>_GRAPHQL__INTROSPECTION, its opposite, and the boot refuses the old key set:DISABLE_INTROSPECTION=falseisINTROSPECTION=true. On by default under a declared development or test profile, so a.env.developmentsetting it drops the line<PREFIX>_OPENAPI__EMIT_DOCUMENT<PREFIX>_OPENAPI__EMIT— on by default under a declared development profile<PREFIX>_OPENAPI__DOCUMENT_PATH<PREFIX>_OPENAPI__EMIT_PATH, relative to the app crate:apps/api/openapi.jsonbecomesopenapi.json, the default<PREFIX>_LOG, in a.envfile or the deploymentRUST_LOG, unprefixed: the console’s filter is the ecosystem’s variable alone, and a realRUST_LOGoutranks one a committed file writes<PREFIX>_OPENTELEMETRY__SERVICE_NAMEOTEL_SERVICE_NAME, unprefixed — or nothing: the service is named after the binary<PREFIX>_OPENTELEMETRY__SERVICE_VERSION,SERVICE_ENVIRONMENT,SERVICE_INSTANCE_IDOTEL_RESOURCE_ATTRIBUTES=service.version=…,deployment.environment.name=…,service.instance.id=…— the version defaults to the binary’s<PREFIX>_OPENTELEMETRY__OTLP_ENDPOINTOTEL_EXPORTER_OTLP_ENDPOINT<PREFIX>_OPENTELEMETRY__SAMPLE_RATIO=0.1OTEL_TRACES_SAMPLER=parentbased_traceidratioandOTEL_TRACES_SAMPLER_ARG=0.1<PREFIX>_OPENTELEMETRY__METRIC_INTERVAL_SECS=5OTEL_METRIC_EXPORT_INTERVAL=5000, in milliseconds<PREFIX>_OPENTELEMETRY__TLS_CA_CERT,TLS_CERT,TLS_KEY(or their_FILE)OTEL_EXPORTER_OTLP_CERTIFICATE,OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE,OTEL_EXPORTER_OTLP_CLIENT_KEY, each a path to the PEM fileOpenTelemetry’s are the specification’s own, so they take no prefix: no
ACME_renamesOTEL_*, norRUST_LOG. Under a prefix of your own, the rest holds withACME_forNESTRS_. Every one of them — every namespaced variable, in fact — can now be given as a file instead, through its_FILEspelling; see the ConfigService API. A name you miss is not silent: the boot names it and its new spelling, as shown below. -
If you write decorators on
nest-rs-codegen, depend on it from aproc-macrocrate only, and use its root items alone, the kit semver covers. Read a decorator’s arguments throughGrammar: akey = valuegrammar is oneconst G: Grammar = Grammar::new("attr", &["key", …]), andG.parse2(args, |arg| …)refuses an unknown key and a repeated one before the closure sees a key; the closure reads the key’s value throughArg, which refuses a bare key that needs one, and reads a key that takes no value througharg.input(). Collect an item’s refusals inRefusalsand report them at once; read a duration withduration_millis, derive a name withpascal_caseorsnake_case, take a marker attribute off an item withtake_flag_attr,take_single_attrortake_path_list, and pass the finished expansion throughreroot. Emit a framework path as::nest_rs_<concern>::<item>, an item the docs show, and your own as::<your_crate>::…. Everything else innest_rs_codegenmoved to__privateand is not API — the job and pair tables,JobDecorator,job_key,transactional_value,CrudDeclaration,RoutePath,MountPath,VersionedEdgeamong them. The repository’sclippy.tomlrefusessyn::meta::parser,syn::Attribute::parse_nested_metaandsyn::MetaList::parse_nested_meta; copy those three entries if your crate should hold the same line. -
Follow the remaining renamed types and signatures. Each row is a compile error, so the compiler finds every site:
6.x 7.0 an exhaustive matchon a framework enum (ApiVersioning,Action,WsReply, …)the same ending in _ =>, its arm the default your code meansnest_rs::resource::{expose, wire_enum}nest_rs::seaorm::expose,nest_rs::core::wire_enumnest_rs::resource::{PkLoadable, RelatedTo, RelationKey, RelationPage, SoleForeignKey}nest_rs::seaorm::graphql::{…}nest_rs::resource::sea_ormnest_rs::seaorm::sea_orma pub usere-exporting an entity’s relation marker beside it,By<Column>(posts::ByAuthorId)posts::__ByAuthorId, the marker#[expose]emits for aviarelation, hidden like the rest of its expansionnest_rs::resource::{serde, validator, schemars, chrono, uuid, serde_json, tracing, async_trait},nest_rs::resource::graphql::{async_graphql, dataloader}nest_rs::pipes::validator,nest_rs::graphql::{async_graphql, dataloader}, or a dependency of your own on any othernest_rs_seaorm::TARGET,nest_rs::resource::TARGETnest_rs_seaorm::target::ORM,nest_rs::seaorm::target::LOADER(the strings are unchanged)nest_rs::health::unresolved_hostnest_rs::core::unresolved_hostnest_rs::core::operation_log::EDGESnest_rs::core::Edge::ALL, each word throughEdge::as_stran item through nest_rs::core::{access, app, container, discoverable, discovery, env_flag, env_prefix, error, error_message, layer, layer_chain, lifecycle, module, request_scope, trace_context, transport}::…(nest_rs::core::container::Container)the same item at nest_rs::core::…(nest_rs::core::Container): an item has one path, and those modules are privatenest_rs::core::problem::{Code, Problem, ToProblem},nest_rs::core::problem::code::CONFLICTnest_rs::core::{Code, Problem, ToProblem},nest_rs::core::code::CONFLICTnest_rs::core::operation_log::Edge,nest_rs::core::panic_messagenest_rs::core::Edge,nest_rs::core::panic::panic_messagenest_rs::core::trace_context::field::…nothing public: the framework writes the correlation fields, and trace_id,span_idandactor_idcome from contextnest_rs::social::providers::github::…,nest_rs::social::providers::google::…nest_rs::social::…EventBus::subscribe(listener)on a bus of your owna #[listeners]host with an#[on_event]methodnest_rs::pipes::{ValidateProbe, MaybeValidateFallback},nest_rs::graphql::{ValidateProbe, MaybeValidateFallback},nest_rs::ws::resolve_ws_data_pipenothing public: the decorators emit them nest_rs::pipes::ValidationPipe,Piped<ValidationPipe<T>, E>,nest_rs::pipes::Validnothing: every edge validates what it decodes; a hand-written check runs nest_rs::pipes::validator::Validateand converts withnest_rs::pipes::PipeError::from#[input]on a DTO an edge only sends#[output](nest_rs::core::output),SerializeandJsonSchemaalone — not a compile error:#[input]still compiles, carrying aDeserializeand rules nothing readsany other item that was #[doc(hidden)]at a crate’s rootnothing public: __privateis not APIasync_traitfromnest_rs::http,ws,graphql,guardsorqueuenest_rs::core::async_trait, oruse nest_rs::prelude::*inputfromnest_rs::http,ws,mcporqueuenest_rs::core::input, oruse nest_rs::prelude::*use nest_rs::guards::prelude::*;use nest_rs::core::{Layer, UnitContext, async_trait, injectable};anduse nest_rs::guards::{Denial, Guard, GuardFor};— the names the guard usesnest_rs::http::{current_request_scope, with_request_scope}nest_rs::core::{current_request_scope, with_request_scope}nest_rs::opentelemetry::LogFormatnest_rs::core::logging::LogFormat, the one type it re-exportedEnvPrefix::var(nest_rs::core::logging::var::FILTER)"RUST_LOG": the console’s filter is the ecosystem’s variable, which no prefix renamesnest_rs::http::{version_path, versions_declare, join_path, normalize_mount_path, literal_mount_path, declared_versions}nothing public: #[controller],#[gateway]and the framework’s own mounts call themnest_rs::ws::{ReplyValue, ReplyOutcome, ErrorReport, HandlerFailed}and their fallbacks,nest_rs::ws::targetnothing public: #[messages]emits them; a handler returns its value or itsResultnest_rs::ws::nest_rs_http::…nest_rs::http::…, which thewsfeature turns onnest_rs::guards::GuardSpecs(vec![…]),nest_rs::pipes::PipeSpecs(vec![…])seeded by handGlobalGuards<(…)>,GlobalPipes<(…)>in the providers of the modulemainbootsnest_rs::core::layer_chain::GlobalSpecsnothing public: each family’s pool is a declaration the root module lists — GlobalGuards,GlobalPipes,GlobalInterceptors,GlobalExceptionFiltersnest_rs::mcp::hosts_on(container, path)Discovery::new(container).meta::<McpHostMeta>(), filtered onmeta.path()nest_rs::mcp::current_container()in a tool’s bodyan #[inject]ed field on the#[mcp]host, or aScoped<T>parameternest_rs::schedule::nest_rs_database::TransactionPolicynest_rs::database::TransactionPolicy, which theschedulefeature turns onscope: Scope<E, A>on a route, itsConditionapplied to a query of the handler’s own (nest_rs::authz::http::Scope)the query in the service, through Repo::<E>::scoped(A::ACTION), which applies the caller’s filter itselfCorrelation::mint()Correlation::minted(None)TlsConfig,CorsConfig,SecurityHeadersConfigHttpTls,HttpCors,HttpSecurityHeadersmethod.retries,method.queueon aProcessMethodmethod.options().retries(),method.queue()entry.provider,entry.method,entry.replicason aScheduledMethod(likewiseListenerMethod,HealthIndicator,SocialProviderEntry)entry.host(),entry.method(),entry.replicas()entry.provider_type_id(),Discovered’sprovider_type_id,CronJobMeta::provider()entry.host_type_id(),host_type_id,CronJobMeta::host()BootStep::InitHook { provider, .. }BootStep::InitHook { host, .. }entry.run,entry.wire,entry.build,entry.declaration_index,entry.provider_type_nameorentry.moduleon a registry entrynone: only the boot runs a discovered entry a CronJobMeta { … }registered by handCronJobMeta::new(module_path!(), host, method, trigger, run), then.with_timeout(…),.with_transaction(TransactionPolicy::Pool),.with_replicas(Replicas::One),.with_key(…)for each field you set away from its defaultBound { count, why }Bound::new(count, why)let _otel = OpenTelemetry::init("api")?;let _otel = OpenTelemetry::init()?;— the service is the binary’s name and versionOpenTelemetryModulein the root’simportsdelete it: main’slet _otel = OpenTelemetry::init()?;is the whole wiring; the module stays only where a provider injectsArc<Metrics>.with_test_telemetry()on aTestApp::builder(), andnest-rs-testing’sopentelemetryfeaturedelete them: a suite asks nothing of telemetry, and logs through the console the boot installs OpenTelemetryError::InitMissingmatchednothing: no module refuses; App::runrefuses an OTLP endpoint no exporter serves withnest_rs::core::UnservedExportErroran app’s mainwith noOpenTelemetry::init()let _otel = OpenTelemetry::init()?;as its first line, with theopentelemetryfeature on the app’snest-rs, wherever a deployment setsOTEL_EXPORTER_OTLP_ENDPOINTOpenTelemetryConfig::new("api"),OpenTelemetryConfig::from_env("api")?OpenTelemetryConfig::default(),OpenTelemetryConfig::from_env()?;service_name: Some("api".into())to name the service otherwise.with_log_filter(f),.with_log_format(x),.with_log_source_location(b),.with_otlp_endpoint(e),.with_service_version(v),.with_deployment_environment(d),.with_trace_sample_ratio(r),.with_metric_interval(i)on anOpenTelemetryConfigthe field in a literal over its base: OpenTelemetryConfig { trace_sample_ratio: 0.1, ..OpenTelemetryConfig::from_env()? }; a ratio outside[0, 1]now failsinit_withinstead of being clampedOpenApiLicense { name, identifier: Some(id), url: None }OpenApiLicense::new(name).with_identifier(id)the queue’s Processortraitnothing: a consumer is a #[processor]host and its#[process]methodsenvelope::seal(payload)andenvelope::open(value)from the queue crate, in a driverthe port seals before enqueueand opens in its worker; the type isEnvelopeat the crate’s root — see Writing a drivera driver’s own worker Transport, its fetch loop and its retriesa JobConsumerbound as aBoundConsumer: the port’sQueueWorkerruns the loop, the attempt and the drainCheckpointStore::clearnothing: the backend lets a job’s checkpoint go in the settle that ends the job check_duplicate_queue_claims(&methods)nothing: the port’s worker refuses two methods on one queue at boot RedisWorkerModule::for_root(cfg), fromnest_rs::redisQueueModule::for_root(cfg), fromnest_rs::queue, besideRedisQueueModule, which now binds the consumer tooRedisWorkerConfig { shutdown_timeout }QueueConfig { shutdown_timeout }; the lease isRedisQueueModule::for_root(RedisQueueConfig { lease })RedisWorker::new(), spawned in a testQueueWorker::new(), fromnest_rs::queuethe queue crate’s tracingre-exporta tracingdependency of your ownasync fn hit(&self, key: &str, limit: Throttle) -> Decisionon a rate-limit store of your own-> Result<Decision, ThrottlerStoreError>: your client’s failure asErr(ThrottlerStoreError::new(error)), never a decision of your own, and no log lineMaskReplyError::Irreconcilable(serde_json::Error)MaskReplyError::Irreconcilable(DecodeError)ProblemDetails::from_error(status, title, err)with anyDisplaythe same with &err, an error, whose decode failure it says without the value; a sentence of your own is.with_detail(…)problem.extensionsmoved or compared as aserde_json::Map*problem.extensions: the map is boxed, so aResultcarrying the problem stays under clippy’sresult_large_errthreshold; indexing,getandinsertread through the box unchangedpanic_message(payload)borrowed as a&stran owned String, any decode failure in it said without the valuepost: Bind<Update, PostsService>on a route,nest_rs::seaorm::Bind#[authorize(Update, bind = PostsService)]on the route andpost: Authorized<Update, PostEntity>as its parameter,nest_rs::seaorm::Authorized; the route’s whole path, its controller’s included, names the id alone (/{id},/{id}/publish)nest_rs::seaorm::graphql::bind::<A, S>(ctx, &id)orbind_required::<A, S>(ctx, &id)in a resolver#[authorize(A, bind = S)]on the operation and anAuthorized<A, E>parameter, itsidargument synthesised; a nullable lookup is#[crud]’s generated query, orCrudService::accessin the bodya hand-written Authorize<A, E>parameter on a route that is not#[public]#[authorize(A, E)]on the route, the parameter dropped#[public]and_authz: Authorize<Read, post::Entity>on a route#[public(Read, post::Entity)], the parameter dropped: the same gate, the same reads, and no line a cleanup can take for unused#[public]on a route loading its row withCrudService::accessin the body#[public(Read, bind = PostsService)]and apost: Authorized<Read, PostEntity>parameter#[public]on a GraphQL operation, a WS message or an MCP operation reading rows underdefine_visitor#[public(Read, post::Entity)], returning the wire type: a read under a bare#[public]now answers nothing, and.fields([...])holds therea covered WS message or MCP operation stating no posture, or gated on a #[subject], reading rows#[authorize(Read, Entity)]: such a read now answers nothing, as on a routea #[field_resolver]or a relation serving a visitor’s rowsa root field naming them, #[public(Read, Entity)], or a query returning what it read: a nested read answers a visitor nothinga guard of your own covering a route, a message or an operation, its phase()left at the defaultfn phase(&self) -> GuardPhase { GuardPhase::Authentication }, orAuthorization: the boot reads ita route, a message or an operation under ThrottlerGuardor another guard identifying no one, alone#[public]on the unit, a guard identifying a caller beside it, or for an MCP host writing its own handlerMcpModule::for_root(McpAccess::Public)HttpRouteMeta::scoped_guarded,HttpRouteMeta::access_is_implicit,HttpRouteParts::scoped_guardednothing public: the boot reads the composed chain nest_rs::authz::http::AbilityShapingnothing public: #[authorize]declares the gate, and each wire row judges itselfa hand-written getoruseroverride on a#[crud]block, kept only for its#[api]textapi(get(summary = "…", description = "…"))in the#[crud]arguments, the override deletedpaginate = …on a#[crud]block that writes its list operation by handthe key dropped: nothing generated read it, and your method bounds its own list a #[crud]block generatingget,updateordeleteunder a controller path naming a parameter (/orgs/{org}/users)those operations written by hand, reading every parameter, or the resource mounted under a path naming none: the generated ones answered 500on every request#[crud(service = svc, entity = E, output = Dto, create = CreateDto, update = UpdateDto)]#[crud(service = UsersService)], naming the type of the servicesvcholds: every type is read off the service’sCrudService,CreatableandUpdatableimpls and the entity’s#[expose], and every operation reaches it through the host’s#[inject]field of that typea bare #[crud(service = svc, entity = …, output = …)]over a read-only service (list,getanddeleteby default)#[crud(service = UsersService, ops = [list, get])], orops = [list, get, delete]beside aDeletableimpl: the default is all fivea #[crud(service = svc, entity = …, output = …)]that leftcreateorupdateout, over a service implementingCreatableorUpdatable#[crud(service = UsersService, ops = [list, get, delete])], the operations it served: withoutops, the block serves every write its service implementsa #[controller]or#[resolver]injecting one type in two fieldsone field: the container holds one instance of the type, and the second field is refused at compile time <E as PkLoadable>::Wire,<E as RelatedTo<P, V>>::Wire<E as Exposed>::Wire,nest_rs::seaorm::ExposedName your own log target by the constant the feature declares, as a 7.0 scaffold does (
pub const TARGET: &str = "features::chat";inchat/mod.rs), and file anerrorfield through the framework’s one walk of a chain:crates/features/src/chat/ws/gateway.rs use nest_rs::core::error_message;tracing::warn!(target: "features::chat", error = %e, "broadcast failed");tracing::warn!(target: crate::chat::TARGET, error = %error_message(&e), "broadcast failed"); -
Import a module bare to read its environment, pin a config as a struct literal, and open an instance by its type. Every module owning a config is imported bare to read its variables, and
for_roottakes only the value it pins — neverNone. A module’s config is one value, pinned throughfor_rootas a struct literal over its base: everywith_*helper is gone. A config’sDefaultis its one base — no loopback URL, no development credential, and what a development run opens aSurfaceleft to the profile, closed in a deployment — and a pinned config reads the process environment, never.env. A struct gaining fields within 7.x keeps a literal ending in..Default::default()compiling, as the semver policy promises.6.x 7.0 SeaOrmModule::for_root(None),RedisModule::for_root(None),ThrottlerModule::for_root(None),AuthnModule::for_root(None),HttpModule::for_root(None)— anyX::for_root(None)the bare import, SeaOrmModule,RedisModule, …: it reads<PREFIX>_<NS>__*over the defaults, andfor_rootonly pinsX::for_root(Some(cfg))X::for_root(cfg)OAuthServerModule::for_root::<P>(None)OAuthServerModule::<P>; a pin infersPfrom its value,OAuthServerModule::for_root(cfg)ConfigModule::for_root()first in a root’simportsdelete it: the cascade needs no import, and the first config the boot loads registers Environmentand says an undeclared one atinfoHttpConfig::default().with_global_prefix(p)(and every configwith_*)the field in a struct literal over ..Default::default()HealthConfig::default().with_probe_deadline(Duration::from_millis(400))HealthConfig { probe_deadline: Duration::from_millis(400), ..Default::default() }impl Config for MyConfig { fn from_env(…) }beside#[config(namespace = "…")]delete it: #[config]writes it, each field reading<PREFIX>_<NAMESPACE>__<FIELD>, its name in SCREAMING_SNAKE, through the reader its type chooses. A field yourfrom_envread under another key is renamed, or its key is renamed in the deployment; a field it read withenv.jsontakes#[config(json)], one withenv.count#[config(bounds = RANGE)]on anOption<usize>, its range aCountBounds, one it judged itself#[config(with = your_fn)](fn(&ConfigService, Field, T) -> Result<T>); afn defaults()goes: what it set moves toDefault, what it opened by profile to aSurfacefield, and a value that differs by profile to.env.developmentand.env.test. Fields that depend on each other, and a generic config, whose bounds the derive does not write, keep the impl under#[config(namespace = "…", from_env = "manual")]a duration field window_secs: u64ortimeout_ms: Option<u64>read throughDURATION.read(env, …)window: Durationwith#[config(bounds = WINDOW)], its default inDefault;Option<Duration>only whereNoneturns it off. The field’s key takes the range’s unit after it (WINDOW_SECS), so no variable movesDurationBounds::secs("WINDOW_SECS", "MyConfig::window", floor, ceiling)(ormillis)DurationBounds::secs(floor, ceiling): the key and the path are the field’s, which#[config(bounds = …)]binds the range to asMyConfig::WINDOWFloor::UnitsOrOff(bound)Floor::Units(bound)on anOption<Duration>field:0from the environment andNonein code are off because the field is anOptionBOUNDS.key(),BOUNDS.field(),BOUNDS.check(namespace, field, value)MyConfig::WINDOW.key(),.field().path(),.check(namespace, value)— a value set through another type’s field names it,MyConfig::WINDOW.pinned_through("MyOptions::window").check(namespace, value);var(namespace)andvar_or_field(namespace)name the variable wholea count held to a range by a with = readerof your own#[config(bounds = RANGE)]withconst RANGE: CountBounds = CountBounds::new(floor, ceiling)on ausizefn reader(env: &ConfigService, key: &str, base: T) -> Result<T>named bywith = readerfn reader(env: &ConfigService, field: Field, base: T) -> Result<T>:field.key()is the key,field.path()the path a value set in code is refused undernest_rs::http::{MAX_CONNECTION_FLOOR, MAX_CONNECTION_CEILING},{SSE_KEEP_ALIVE_FLOOR, SSE_KEEP_ALIVE_CEILING},{UNIT_TIMEOUT_FLOOR, UNIT_TIMEOUT_CEILING}MAX_CONNECTION_BOUNDS,SSE_KEEP_ALIVE_BOUNDS,UNIT_TIMEOUT_BOUNDS, each oneDurationBoundsnamed on the fielda field of a type of your own read with env.parseimpl FromSetting for YourType, saying what a refused value was expected to beConfigModule::for_feature::<C>()in a module’simportsdelete it: the provider that injects Arc<C>loadsC. A module readingConly in aregisterof its own callsConfigModule::provide_feature::<Unnamed, C>(builder)from itscollectSeaOrmConfig { connect_timeout_secs: Some(5), statement_timeout_secs: Some(10), max_connections: Some(20), min_connections: Some(2), .. }connect_timeout: Duration::from_secs(5),statement_timeout: Duration::from_secs(10),max_connections: 20,min_connections: 2— unset isDefault’s 10 s, 15 s, 10 and 0, which the pool is now always handedAuthnConfig { leeway_secs: Some(45), expires_in_secs: Some(7200), explicit_typing: Some(false), .. }leeway: Duration::from_secs(45),expires_in: Duration::from_secs(7200),explicit_typing: false—Defaultholds 30 s, an hour andtrueThrottlerConfig { limit: Some(120), window_secs: Some(30), .. }limit: 120, window: Duration::from_secs(30)—Defaultholds 60 a minuteHttpConfig { max_body_bytes: Some(n), .. }max_body_bytes: n—Defaultholds 2 MiB, and there is no offHttpTls::from_files(cert, key)?.with_reload_secs(300), or.with_reload_secs(0).with_reload(Some(Duration::from_secs(300))), or.with_reload(None)to stop the watch; a pinnedSome(Duration::ZERO)fails the bootHttpModule::for_root(HttpConfig { port: 3002, ..Default::default() })— a pin of what varies by machine or by app — beside<PREFIX>_HTTP__*keys in.envfilesno pin — a listed controller brings HttpModulebare — and<PREFIX>_HTTP__PORT=3002in the app’s ownapps/<app>/.env, read over the root’s underdevelopmentandtest; the deployment sets it on the process. A pin takes its whole namespace off every.envfile, and the boot names each key it shadowsRedisModule::for_root(RedisConfig { …, ..Default::default() })relying on the loopbackurlwritten in the pin, or<PREFIX>_REDIS__URLin the deployment: no profile holds a URL, and a pinned config reads the process environment, never.envStorageModule::for_root(StorageConfig { …, ..Default::default() })relying on the development pairthe pair from the deployment’s environment in every profile; plain HTTP stays open in development and test over ..Default::default()GraphqlConfig { emit_sdl, schema_path, .. },OpenApiConfig { emit_document, document_path, .. }emitandemit_pathon both; a relativeemit_pathis resolved against the app crate’s directoryGraphqlConfig { disable_introspection: false, .. }introspection: Surface::Open: the field says what it serves, asplaygrounddoesGraphqlConfig { playground: true, introspection: true, emit: true, .. },OpenApiConfig { enabled: true, emit: true, .. },ServerTimingConfig { enabled: true },StorageConfig { allow_http: true, .. }, and the same withfalseSurface::Open, orSurface::Closed, fromnest_rs::config: each field is aSurface,ByProfileinDefault, and its variable keeps its name and reads the same booleansa surface read as a bool,config.enabledconfig.enabled.is_open(), resolved where it is used; an emit readswrites(), whoseByProfileopens under development alone#[config(namespace = "…", defaults = Self::for_profile)], orfn defaults()in animpl Config, setting a field by profilea field it opened is a Surface,ByProfileinDefault, and the code using it asksis_open(); a value that differs by profile and opens nothing (a pool size, a level) goes in.env.developmentand.env.test, never in aDefaultreading the profile; delete the function and the key..GraphqlConfig::defaults(),..StorageConfig::defaults(), any..T::defaults()orC::defaults()..Default::default(),C::default(): a config has one base. Dropuse nest_rs::config::Config;if it was there for thatGraphqlModule::for_root(GraphqlConfig { …, ..Default::default() })expecting the playground or introspection in developmentnothing to change: a pin closes nothing it does not name a suite asserting that GraphqlModule, bare or pinned over..Default::default(), answers a plainGETwith405, or refuses introspection, under the test profilepin playground: Surface::Closedorintrospection: Surface::Closed: the test profile opens bothOpenApiModule::for_root(OpenApiConfig { …, ..OpenApiConfig::default() })expecting/apiservedserved in development and test only; enabled: Surface::Openwritten in the pin opens it everywherean HttpConfig,StorageConfig,AuthnConfig,GraphqlConfig,WsConfig,McpConfig,OAuthClientConfigorOpenTelemetryConfigliteral written out wholethe same, ending in ..Default::default()— each gained fields (shutdown_timeout;operation_timeout,read_timeout,tls;jwks_uri,algorithms,tls; the graphql-ws bounds,ping_interval,ping_timeout;message_timeout,connect_timeout,disconnect_timeout,ping_interval,ping_timeout;operation_timeout,max_concurrent_sessions,session_idle_timeout,ping_interval,ping_timeout;tls)McpModule::for_root(McpOptions { server: Some(identity), .. })McpModule::for_root(identity)McpModule::for_root(McpOptions { config: Some(cfg), server: Some(identity) })McpModule::for_root((identity, cfg))— the declaration first, the config last;McpAccess::Publicleads when the app opens the endpoint,(McpAccess::Public, identity, cfg)env.get("KEY")andenv.list("KEY", default)in afrom_envenv.get("KEY")?andenv.list("KEY", default)?— a_FILEread can failenv.seconds("KEY", base), or anyenv.*reader asked for a key ending in_SECSor_MSa DurationBounds::secs(…)orDurationBounds::millis(…)declared beside the config and named on the field,#[config(bounds = …)]; a hand-written overlay binds it once,BoundedSetting::new(RANGE, Field::new("KEY", "MyConfig::field")), and readsSETTING.read(env, base)?; see Variablesserde_json::from_strover a structured variable in afrom_envof your ownenv.json::<T>("KEY")?, which refuses it naming the variable, where it failed and the type it expected, never the valuesetting.shown()in a refusal of your ownsetting.refuse("<what was expected>")— the variable is named, the value neverOpenTelemetryConfig::from_env(name)returningResult<_, ConfigError>it returns Result<_, OpenTelemetryError>; aConfigErrorof its own variables is insideOpenTelemetryError::ConfigErr(OpenTelemetryError::InvalidLogFilter { value, .. })Err(OpenTelemetryError::LogSettings(error))— it names the variable orOpenTelemetryConfig::log_filter, never the directiveLogFormat::resolve(raw)LogSettings::from_env()?.format, orLogFormat::parsewithLogFormat::ByProfile; what comes back may beByProfile, so ask itwrites_json(), never== LogFormat::JsonLogFormat::by_profile()LogFormat::ByProfile, whichLogFormat::default()now is, resolved where the console is built;LogFormat::by_profile() == LogFormat::JsonisLogFormat::ByProfile.writes_json()tracing_subscriber::fmt().with_env_filter(…).with_writer(ConsoleWriter::get()).init()in a binary with noAppnest_rs::core::logging::install_console(&LogSettings::from_env()?)nest_rs::config::crypto_provider()nothing to call: the framework installs the provider its clients and listeners use let opts = config.connect_options();let opts = config.connect_options()?;, refused for an empty URL, an unverifiedsslmode, a certificate file the URL or a libpq variable names that this process cannot read, a connect budget or a pool bound out of range, or a minimum above the maximumRedisConnection::connect(url),connect_within(url, budget)RedisConnection::connect(&config)conn.manager()the connection itself — it is ConnectionLikeandCloneMaterial { bytes, path: None }Material::inline(bytes)Throttle { limit, window }and its fields, on the rate limiterThrottle::new(limit, window),.limit(),.window()— a window under a millisecond is refusedThrottlerGuard::new(store, limit)gone: ThrottlerModulebuilds the guard; aThrottlerConfigliteral gainspseudonym_keya Stringor aformat!given toSeaOrmConfig::url,RedisConfig::url,StorageConfig::access_key/secret_key,ThrottlerConfig::pseudonym_key,AuthnConfig::secret/private_key, orclient_secretonOAuthClientConfig,GithubSocialConfig,GoogleSocialConfigthe same with .into(): each is anest_rs::core::Secret<String>(in anOptionwhere it was one); a literal"…".into()compiles as it wasconfig.url,config.secret,config.client_secretread as a stringconfig.url.expose_secret():Debugprints<redacted>in its placea secret field of your own config, kept out of logs by a hand-written Debugor by noDebugpub api_key: Secret<String>and#[derive(Debug)], read withexpose_secret(); acustom(function = …)rule on it takes&Secret<String>a password held as a Stringin an#[input]DTO#[schemars(with = "String")] pub password: Secret<String>, read withexpose_secret(): its#[validate(length(…))]still judges the value, and what serializes the DTO writes"<redacted>"Two values of one type are two types. String-keyed injection is gone: a second Redis, or a second value your app builds, is a named instance — a type of its own, declared
#[instance] pub struct Cache;— and a resource opened more than once is imported per instance:RedisModule::<Cache>bare, orRedisModule::for_root((Cache, cfg))to pin. A second Valkey reads<PREFIX>_REDIS__CACHE__*. See Instances.6.x 7.0 #[inject(key = "cache")] cache: Arc<RedisConnection>#[inject] cache: Arc<RedisConnection<Cache>>App::builder().provide_keyed("cache", RedisConnection::connect(&cfg).await?)RedisModule::<Cache>in the root’simportsto read the environment,RedisModule::for_root((Cache, cfg))to pin#[inject(key = "x")] client: Arc<T>, a value your app builds#[inject] client: Arc<XClient>, a newtype, orArc<Instanced<X, T>>.provide_keyed("x", value), a value your app builds.provide(XClient(value)), or.provide(Instanced::<X, _>::from(value))container.get_keyed::<T>("x")container.get::<XClient>(), orcontainer.get::<Instanced<X, T>>()KeyedDependencyError, matched after a bootnothing: a missing type is AccessGraphErrororMissingDependencyErrorRedisError::InvalidUrl { endpoint, source },ConfigNotResolvedError { type_name }in a patternthe same ending in ..: each holds morea RedisErrorvariant’ssourcemoved out as aredis::RedisError, or found in its chain withdowncast_ref::<redis::RedisError>()*source, anddowncast_ref::<Box<redis::RedisError>>(): the client’s error is boxed, so aResultcarrying aRedisErrorstays under clippy’sresult_large_errthreshold, and the bare type’s downcast now finds nothing; a method reads through the box unchangedA module of your own that owns a config, written by hand:
6.x 7.0 fn for_root(config: impl Into<Option<C>>) -> CSetup { ConfigModule::setup(config) }fn for_root(config: C) -> CSetup { ConfigModule::setup(config) }, and the module imported bare reads its environment: animpl ModulewhosecollectcallsConfigModule::provide_feature::<Unnamed, C>(builder), or a#[module]whose provider injectsArc<C>ConfigModule::setup::<M, C>(cfg)ConfigModule::setup::<M, C, Unnamed>(cfg), or no turbofish; it takes the value to pin, neverNoneConfigModule::provide_feature::<C>(None, builder)ConfigModule::provide_feature::<Unnamed, C>(builder), what a bare import readsConfigModule::provide_feature::<C>(Some(cfg), builder)in a setup of your ownConfigModule::provide_root(cfg, builder), the declaration afor_rootpinsa hand-written Namespacedimpl settingDECLARATIONleave it out: a hand-written impl answers by its type name -
Compose the container, and follow the lifecycle’s order. The boot now refuses what 6.x left to chance — a provider listed and never built, a binding made twice, an override nothing reads — and a lifecycle hook runs its dependencies first. Each row is a compile error or a boot refusal naming what to fix:
Providers and modules
6.x 7.0 providers = [Foo, Foo as dyn Trait]providers = [Foo as dyn Trait]: the binding holdsFoounder its own type tooFoolisted in one module andFoo as dyn Traitin anotherlist it once, as the binding, and import that module where Arc<Foo>is injecteda scope = requestorscope = transientprovider, or an edge host, boundas dyn Traitbind a plain #[injectable]singleton; reach a scoped provider through aScoped<T>parametera request-scoped or transient provider listed in two modules, or one type registered under two scopes register it once two modules importing each other, a provider of one injecting the other’s move what both need into a module both import a provider injecting a type a hand-written module or a for_rootregisters, from a module that does not import itimport that module in the provider’s module an Option<Arc<T>>field whoseTa module the app imports provides, outside the consumer’s importsimport that module in the consumer’s module a singleton holding Option<Arc<T>>of a request-scoped or transientTreach it through a Scoped<T>parameter, or make the consumer request-scopedrequest-scoped or transient providers injecting each other move what both need into a third provider, pass the value as an argument, or publish an event #[injectable(scope = transient)]on a layer a#[process],#[scheduled]or#[on_event]site binds#[injectable], a singleton: the site builds it onceT::from_container(&container)on a decorated typenone: the container builds T; read it withcontainer.get::<T>(), or register it with<T as Discoverable>::register(builder)in a testT::from_scope(&scope)on a request-scoped or transient providerscope.get::<T>()AuthnGuard::from_container(&c),Storage::from_container(&c),McpMount::from_container(&c)AuthnGuard::new(strategy),Storage::connect(&config), the container’s; the boot builds an MCP mount when it serves the pathprovide_factory_after::<T, A, _, _>(f), and the same for the declared anddynformsprovide_factory_after::<T, (A,), _, _>(f)a module filling a registry the app reads from an OnApplicationBootstraphookContainerBuilder::provide_wiring("<crate>::<registry>", wire)in itsregisterbuilder.provide_meta(TransportContribution { name: "MyTransport", build: |c| Ok(Box::new(MyTransport::new(c)?)) })builder.provide_transport(|c| MyTransport::new(c))— namedMyTransport, read off the typea feature module importing HttpModule(or GraphQL’s, OpenAPI’s) to declare it serves over HTTPdrop the line where the module lists a host, which brings its edge’s module bare; a module listing none keeps a bare HttpModule(GraphqlModule,OpenApiModule) in itsimports, and the app keeps afor_rootonly to pin a configan edge adapter importing its port alone, and the app root importing HttpModule,GraphqlModule,QueueModuleorScheduleModulebeside it, or an adapter importing them itself (WsModuleandHttpModulefor a gateway,McpModuleorHttpModulefor a tool)drop the line, unless the root pins a value ( McpModule::for_rootstays where it declares the identity or the opening): a host a module lists brings what serves its edge, bare, so a controller reads<PREFIX>_HTTP__*, a gateway<PREFIX>_WS__*and a tool<PREFIX>_MCP__*. A module listing no host, an interceptor’s, keeps its import, and the queue’s backend binding (RedisQueueModule) stays at the root. Nothing refuses the old shape: it still runs one transport of each typeSeaOrmModulebesideSeaOrmDatabaseModule, orRedisModulebeside a Redis binding, neither pinneddelete the resource’s line: a binding imports the resource it runs on, by its instance. The pair still boots, and a root names the resource only to pin it ( RedisModule::for_root(cfg)) or for a connection it injects with no bindingThrottlerModuleat the root for a controller bindingThrottlerGuardThrottlerModule, bare, in that controller’s adapter, and the root drops the line unless it pins a policy; a root’sRedisThrottlerModulestill supersedes the in-process storea container built by hand importing GraphqlModule,HealthModule,OpenApiModule,McpModule,StaticFilesModuleorOAuthResourceModule, seeding the module’s configseed HttpConfig::default()beside it: each importsHttpModulea container built by hand importing a module that lists a controller, a gateway, a resolver, an #[mcp]or#[process]hostseed what its edge’s module reads beside it ( HttpConfig,WsConfig,GraphqlConfig,McpConfig,QueueConfig): the host brings that module, and a container built by hand drains no factoryMcpModule::for_root(..)declaring an identity orMcpAccess::Publicat two importsdeclare each at one; the other imports leave it out, or import McpModulebarean impl Moduleorimpl DynamicModulewritten by handthe same with _: Collecting<Self>after the builder incollectand_: Registering<Self>inregister; reach another module withbuilder.import::<M>()in both, and dropmark_collected,mark_registeredand a leadingSelf::collectApp::new::<AppModule>()?, and a match onUnresolvedFactoryErrorApp::builder().module::<AppModule>().build().await?, the one boot: every module owning a config queues a factory, which the synchronous boot refusedApp::builder().provide_meta(x)or.provide_wiring(name, wire)attach it from the registerof a module the app imports (ContainerBuilder::provide_meta,provide_wiring)ReachableProviders::reaches(Some(&set), id),ReachableProviders(set)built by handReachableProviders::of(container, "<what you discover>")?.reaches(id); a test boots the modules it means throughTestApp,HeadlessApporApp::builder, which seal the set they reacha matchonInertHost::BoundUnderAnotherKey, or onDuplicateProviderError { type_name }drop the arm; read DuplicateProviderError’sfirst,secondandscopeswith.., and matchInertHostwith a_armProviderCycleError { module, type_names },ContestedDeclarationError { … }naming every fieldread chainandscope;firstandsecond; each with..nest_rs::core::is_framework_owned(origin)nest_rs::core::inert_host(container, origin, host).is_the_apps(), which reads the compositionreport_inert_host!(target: …, what: …, origin: …), in an edge of your ownthe same with host:andcontainer:, so the line names its causeA container built by hand, and a test’s overrides
6.x 7.0 let container = Container::builder().provide(x).build();.build()?in a function returning aResult,.build().expect("…")in a test:buildreturns what it refusesa test building a module by hand ( Container::builder().import::<M>()) whosecollectqueues a configprovide the config first ( .provide(C::default())), or bootMthroughTestApp—buildotherwise returnsContainerError::LateFactorynaming ita test configuring a transport or running a wiring over Container::builder()boot through TestApporHeadlessApp, importing the modules whose entries the test meansoverride_arc::<RecordingUpstream>(upstream)where the app bindsHttpUpstream as dyn Upstreamoverride_dyn::<dyn Upstream>(upstream.clone())— override the key the consumers injectan override of a type no module, factory or seed provides, read back with container().getprovide it with provide/provide_arcinstead: a seed, not a doublean override of a #[controller](or another edge host)override the provider the controller injects a seeded config outside its ranges or its validate()rulesseed a value a read would accept TestApp::builder()….build_headless()in a suite withouthttp, and in aKitBackend’sfn appHeadlessApp::builder()….build_headless()a KitBackend’sfn app(&self)andfn lease(&self) -> Durationfn app(&self, lease: KitLease)andfn lease(&self, lease: KitLease) -> Duration:KitLease::Briefthe lease you had, a few seconds for a networked backend (a renewal goes a third into it, so a runner stalled past the rest lapses it),KitLease::Lastingone longer than a stalled runner with your connection’s bounds as wide;lapseandtakelapse a lease of either kind.use_guards_global(…),.use_pipes_global(…),.use_interceptors_global(…)or.use_exception_filters_global(…)onTestApp::builder()nothing for the app’s suite, which boots the module declaring them; a test of a feature declares its pool on a root module of its own, #[module(imports = [Feature], providers = [GlobalGuards<(G,)>])]a suite arming the app’s outbox by hand ( container.get_dyn::<dyn OutboxStore>()…arm())delete it: TestAppandHeadlessApparm the outbox of an app binding a store and a queue backend, as the relay does at boota service test installing Executor::Pool(pool)withwith_request_executororwith_job_executor, and an ability withwith_abilityapp.unit(ability, || svc.call())as a request,app.system_unit(|| svc.call())as a job, on aTestAppbooting the binding —nest-rs’sauthzanddatabasefeatures besidetestingEphemeralDatabase::create::<M>()held in a tuple beside the app it seedsTestApp::builder()…ephemeral_database::<M>(), held and dropped by the app;app.container().get::<DatabaseConnection>()reaches it to seed rows.EphemeralDatabase::createstays for a test that boots no appa test helper signing a bearer with app.container().get::<JwtService>(), or with a private key the suite commits.ephemeral_signing_key()on the builder, thenapp.bearer(&claims)— the app verifies the test’s key in place of its own, for its own audience and issuer —nest-rs’sauthnfeature besidetestingan AuthnConfiga suite seeds to verify its own tokensdelete it: the app reads its audience and issuer from its .env, andephemeral_signing_keyreplaces its key aloneapp.socket(path).bearer(token)on aWsAppapp.socket(path).header("authorization", app.bearer(&claims))a test reading silence from next_frame(),next_message(),next_event()ornext_item(id), which now wait sixty secondsname its bound: expect_silence(within),next_frame_within(within),next_message_within(within),next_event_within(within),next_item_within(id, within)Lifecycle hooks and the way down
6.x 7.0 hosts named so their hooks run in the wanted order ( AaFirst,ZzLast)inject the provider whose hooks must run first: its hooks then run before yours at init and after yours at shutdown a hook reaching another provider through Container::getand relying on that provider’s hook having runinject that provider, so the graph orders the two app.init().await?on aTestAppdelete it: TestApp::builder().build()already ran the init phases, which run once per appa shutdown hook that expects what its init filledif let Some(..): it now also runs after a failed or interrupted inita one-shot command reaching the pool around the container, its teardown skipped let app = App::builder()…build().await?; app.init().await?;…app.close().await;a test that could not run the shutdown hooks TestApp::close(),HeadlessApp::close(),WsApp::close()a module ending its resource in a Dropbuilder.provide_close::<T, _, _>(|t| async move { … })beside the factorya provider injecting Arc<DatabaseConnection>only for a lifecycle hookgo through its service and Repo: the hook runs in a unit of work, its writes committing together on itsOkan emit from a task spawned at construction, relied on to be dropped silently emit from an #[on_module_init]hook or later: the listeners are live before the first hooka test matching a factory’s error at the top of a boot error the boot error is FactoryFailedError; findEin its chain (err.chain()) or read{err:#}an impl Transportwritten by handthe same with fn stop_bound(&self) -> Duration— its drain window plusSHUTDOWN_SETTLE_TIMEOUT, at mostMAX_STOP_BOUND(a day) — andasync fn listen(&mut self) -> anyhow::Result<Listening>binding its socket, whichservethen serves onApp::runandApp::closeneed a runtime with its time driver, as#[nest_rs::main]and#[tokio::test]build it. A#[nest_rs::main]program that built an app and never serves it (a one-shot command) keeps running at the firstSIGTERM, its appDraining: readAppLifecycle::stopping()to stop, or a second signal exits it. -
Write HTTP code on nestrs’s HTTP vocabulary. 6.x’s HTTP surface was poem’s; 7.0’s is
nest_rs::http—Request,Response,Body,HttpError,Endpoint, the extractors — over thehttpcrate’s head types, which it re-exports, and the server underneath is nestrs’s own on hyper. A route’s path is OpenAPI’s path templating. Each row is a compile error unless it says otherwise:Routes and handlers
6.x 7.0 #[get("/:id")]#[get("/{id}")]#[get("/files/*rest")]#[get("/files/{*rest}")]#[get("/@:handle")]#[get("/@{handle}")]#[get("/:id<\\d+>")]#[get("/{id}")]withPath<u64>, or a pipe#[controller(path = "/orgs/:org")]#[controller(path = "/orgs/{org}")]a root catch-all ( /*rest) that also served/the catch-all ( /{*rest}) and a route at/beside it (#[get("/")]) — not a compile error:/otherwise answers the fallback’s404a handler reading an empty parameter: /a//bmatched/a/{x}/bwithxemptynothing reaches it — /a//banswers the fallback’s404; a value that may be absent travels in the query stringuse poem::web::{Json, Path, Query}in a controlleruse nest_rs::http::{Json, Path, Query}— andForm,Multipart,Header<T>,ClientIp,RawBody-> poem::Result<T>,poem::Error::from_status(s)-> nest_rs::http::Result<T>,HttpError::from_status(s)impl poem::error::ResponseError for MyErrora domain error: impl nest_rs::core::ToProblem for MyError(step 9); an answer that is no problem document:impl nest_rs::http::ResponseError for MyError—status(), andas_response()for a body of its own; render only, since the edge files a5xx’s chainreq: &poem::Requestas a handler parameterreq: &nest_rs::http::Request, or the extractor for what it readspoem::web::Data<&T>an #[inject]field on the controller, orScoped<T>for a request-scoped provideruse nest_rs::http::poem::…nest_rs::http::{Request, Response, Json, IntoResponse};ProblemDetailsanswers throughnest_rs::http::ResponseError/IntoResponsefield.into_byte_stream()throughnest_rs::http::PartExtField::into_byte_stream()onnest_rs::http::Multipart’s fieldRawBody::extract_with_limit(&mut poem_body, n)in an extractor of your ownthe extractor implements nest_rs::http::FromRequest, whoseRequestBodyextract_with_limittakes; a handler readsbody.into_bytes_limit(n)body: Valid<Json<T>>,Valid(input): Valid<Json<T>>— and overQuery,Form,Path,HeaderJson(input): Json<T>: every extracted value is held to the rules its type declares, with nothing to wrapnest_rs::http::Piped<P, E>, read throughinto_inner()orDerefnest_rs::pipes::Piped<P, E>spelled out in the handler’s signature, boundPiped(value)—into_inner()andDerefstill read itPiped<P, E>behind a type alias, or read withFromRequeston a route registered onHttpRoutesthe carrier spelled out where #[routes]reads it; by hand, extractE, thenPiped::<P, E>::apply(extracted.into_inner())—Pipedis no extractorimpl nest_rs::http::IntoInner for MyExtractor<T>impl nest_rs::pipes::Source for MyExtractor<T>(type Value,into_value), andnest_rs::pipes::validator::ValidatewhenTdeclares rulesSseEvent::retry(ms)SseEvent::message("").retry(Duration::from_millis(ms))match event { SseEvent::Message { .. } => … }none: an event is written, never read back SseEvent::message(serde_json::to_string(&payload)…), with a fallback body when it failsSseEvent::json(&payload): a payload that does not serialize sends no event — its chain is filed and the stream ends thereSseSettings::respond(stream), answering poem’sSSEthe same, answering a Responsemarked to end at the shutdown signalPATCH /<resource>/{id}on a#[crud]controllerPUT /<resource>/{id}— a wire change, no compile errorimpl RouteResponseShaper/ResponseShapingonpoem::Request,poem::Response,poem::Resultthe same impl on nest_rs::http::{Request, Response, Result}challenge::stamp_bearer_erroron apoem::Responsethe same call on nest_rs::http::Responseset_created_location(&mut res, caller_path(req), id)beside#[http_code(201)]and#[api(response = T)]return Created<Json<T>>:Ok(Created::at(id, Json(dto)))— theLocationis written on the path the caller addressed, and the document reads the201, theLocationandToff the return type, an alias includedset_next_link(&mut res, caller_path(req), first, cursor)return Paginated<Json<Vec<T>>>:Ok(Paginated::new(Json(items), first, page.next_cursor))— theLinkis written on the path the caller addressed, and the document declares it andTClientOrigin::of(&poem::Request)ClientOrigin::of(&nest_rs::http::Request)Rust’s #[deprecated]on a#[routes]handler or a#[controller]struct#[api(deprecated = "YYYY-MM-DD")]on each route’s handler, the date itsDeprecationheader states — see OpenAPI operationsRoute records, self-mounts and the fallback
6.x 7.0 HttpVerb::Get,HttpVerb::Post, …Method::GET,Method::POST, … (nest_rs::http::Method)route.verb,route.path,route.handler, any field of anHttpRouteMetathe accessor of the same name: route.method(),route.path(),route.handler()route.maskedon anHttpRouteMetaroute.names_an_entity(): the route’s posture names an entity, a subject a table holds. Which properties a grant may withhold is no route’s to say: every route answers judged rows, and each#[expose]d type’s schema says it on the property, its description reading Field-level authorization applies: readsnullwhere the caller’s ability withholds itmeta.routes,meta.path,meta.controller,meta.token,meta.versionson anHttpControllerMetameta.routes(),meta.path(),meta.controller(),meta.token(),meta.versions()an HttpRouteMeta { … }orHttpControllerMeta::new(…)built by handnone: a #[controller]struct and a#[routes]block record each routeroute.throttledon anHttpRouteMetanone: a guard declares the 429it answers inGuard::denial_statuses, and the route’s OpenAPI document lists itroute.success_status() == 200, au16route.success_status() == Some(200);Noneis a status only the handler knows, a(StatusCode, B)pair, a bareStatusCodeor a builtResponse, which the document lists under2XXfn mount(c: &Container, route: poem::Route) -> poem::Routeon a hand-writtenControllera #[controller]struct and a#[routes]block; a surface registering entries of its own is a self-mount, belowHttpEndpointMeta::new(path, label, mount), with.exempt()HttpEndpointMeta::new(&SITE, path, label, |c, routes| { routes.route(Method::GET, &path, ep); })overstatic SITE: Handler = nest_rs::http::declare_endpoint::<M>("M", path, posture),Mthe type that mounts it:.exempt()becomesPosture::Public, a mount the global pool gatesPosture::Gated;meta.handler().posture()reads a mount’s postureroute.nest(path, ep)in a self-mountroutes.route_any(&path, ep), at exactlypath; its subtree is registered as{path}/{*rest}HttpFallbackMeta::new(path, owner, |c, route| route.at(…))HttpFallbackMeta::new(path, owner, |c| BoxEndpoint::new(ep))MethodTable::new().get(ep).into_endpoint()routes.route(Method::GET, &path, ep); the table answers405withAllowandHEADnest_rs::http::matched(ep)nothing: every entry records its template view.route()as aCow<str>view.route(), anOption<&str>nest_rs::graphql::async_graphql_poem::…gone: GraphqlModulemounts the schema; an app serving a schema of its own over poem depends on async-graphql-poem itselfnest_rs::ws::poem::…,nest_rs::ws::GatewayEndpointgone: a gateway names no poem type, and #[messages]mounts itnest_rs::ws::CloseCodematched exhaustivelythe same with a _arm: it is nestrs’s own#[non_exhaustive]enum, with the same variantsThe transport and its tests
6.x 7.0 TestApp::builder().http(HttpTransport::new().compression(true))TestApp::builder().provide(HttpConfig { compression: true, ..Default::default() }), or nothing when the app’sHttpModule::for_rootalready pins the valueHttpTransport::new().bind(addr)handed toHeadlessApp::spawn_transportHttpTransport::from_config(&HttpConfig { host, port, ..config })?,configread from the app’s containerHttpTransport::new().mount(path, |container| endpoint)an HttpEndpointMetaattached by the providing module’sDiscoverable::register, as aboveVersionSelector::new(strategy, header, default)HttpConfig { versioning, version_header, default_version, .. }Box::new(http_transport).serve(cancel)driven by handhttp_transport.listen().await?first; the port it bound is inListening::addressesTestClient::new(transport.take_endpoint()?)on a hand-booted transporttransport.take_endpoint()?.call(request), orTestAppHttpCors { .. }.into_middleware()nothing: set HttpConfig::cors, which the transport checks at bootHttpConfig { trusted_proxies: vec![ip], .. }vec![ip.into()], orvec![trusted_proxy!("10.42.0.0/16")]for a literal, checked as the program compiles ("…".parse()?for a value read at run time): an entry is aTrustedProxyClientOrigin::resolve(forwarded, forwarded_for, real_ip, peer, &[ip])&[ip.into()]for the last argumentClientIp’sipcompared with::ffff:a.b.c.don a listener on[::]a.b.c.d: a mapped address is the IPv4 address it carries — not a compile erroran OPTIONSfrom a listed origin that relied on the CORS layer’s403nothing, or a guard: it reaches its route now, 405withAllowwhere none answers — not a compile errorHttpCors { methods: vec!["TRACE".into()], .. }drop the forbidden method; list the methods a page sends ( PUT,DELETE, …)a CORS policy without max_age, whose preflight a browser kept a daymax_age: Some(Duration::from_secs(86_400)), or<PREFIX>_HTTP__CORS_MAX_AGE_SECS=86400— not a compile error: a preflight otherwise carries noAccess-Control-Max-Agea write guarded by If-Matchagainst theETagof a readcompressionencodedread the tag the write sends from an unencoded answer (a request without Accept-Encoding) — not a compile error: an encoded answer’s strong tag is now sent weak (W/"…", RFC 9110 §8.8.3), and a weak tag matches noIf-Matchcurrent_body_limit().unwrap_or(RawBody::DEFAULT_LIMIT)current_body_limit()normalize_error_response(poem_response)normalize_error_response(response), with anest_rs::http::Responseuse poem::test::{TestClient, TestForm, TestFormField, TestResponse, TestJson};use nest_rs::testing::{TestClient, TestForm, TestFormField, TestResponse, TestJson};use poem::http::{StatusCode, header};in a suiteuse nest_rs::http::{StatusCode, header};TestClient<BoxEndpoint<'static, poem::Response>>,TestClient::new(poem_endpoint)TestClient,TestClient::new(endpoint)over anest_rs::http::Endpointresp.0.into_body().into_vec().await?resp.0.into_body().into_bytes().await?resp.0.into_body().into_json::<T>().await?resp.json().await.value().deserialize::<T>()resp.0.header("x-name")resp.0.headers().get("x-name").filter(|event| event.level == "error")overlogs.events()logs.events_at(tracing::Level::ERROR)a test catching a request’s unwind ( catch_unwindaroundTestApp::http()…send())the 500the request now answers: a handler that panics is answered and its connection serves onA response header a route sets — a
#[response_header], a handler, a surface setting a security header orServer— now wins over the deployment’s<PREFIX>_HTTP__*default, which fills only a response that sets none: a deployment relying on its global value to override a route’s removes the route’s header. AScoped<T>or a servicebind = Sloads through whose module the app does not import fails the boot. -
Follow the error and authentication types. An error nobody meant for the client is answered opaquely and its chain logged, on every edge: a client reads a sentence only from a deliberate client error — a
ToProblemtype,WsError, aProblem— and every failure names its class by onecode. An error carries its cause as a source chain rather than aformat!ted string.6.x 7.0 async fn f(&self) -> async_graphql::Result<T> { Ok(self.svc.f().await?) }over a foreign errorreturn the error, -> Result<T, MyError>, and implementnest_rs::core::ToProblemfor what the client may read; or convert explicitly:async_graphql::Error::new(..),nest_rs::graphql::problem_error(&e)a Resultalias over a foreign error as a resolver’s returnspell Result<T, MyError>a GraphQL client reading the parser’s rendering out of a syntax error’s message,--> 1:46and the source linelocationsfor the place, and themessage,Syntax error at line 1 column 46: expected name, for what the grammar expected: it no longer holds the documenta WebSocket client reading a handler error’s text the handler returns WsError::new(..)or an error implementingToProblem; anything else answers"internal error"McpError::internal_error(e.to_string(), None)over an error you did not buildnest_rs::mcp::problem_error(&e)(aToProblemerror),.opaque()?, or theToProblemerror returned from an operation spelledResult<T, E>impl nest_rs::http::ResponseError for MyErrorbeside itsimpl ToProblem, twomatches over one enumthe ToProblemimpl alone, which makesMyErroraResponseErroranswering the problem it says, its type and title included: a route spelledResult<T, MyError>and?in a body answeringnest_rs::http::Result<T>both answer it?on ananyhow::Errorin a body answeringnest_rs::http::Result<T>,HttpError::from(anyhow_error).opaque()?, or the route spelledanyhow::Result<T>: either answers the opaque500, the chain filedHttpError::from(StatusCode::NOT_FOUND),StatusCode::NOT_FOUND.into(), a route returningResult<T, StatusCode>HttpError::from_status(StatusCode::NOT_FOUND), the route returningnest_rs::http::Result<T>impl nest_rs::http::ResponseError for MyErroralone, itsstatus()amatchimpl nest_rs::core::ToProblem for MyError:Some(Problem::new(status, code))per variant,Nonefor one the client is owed no word of — or no impl and.opaque()?where every variant is onean ExceptionFilteranswering a domain error withProblemDetails::…().with_type(uri).with_title(t)throughHttpViewProblem::new(status, code).with_type(uri, title)in the error’sToProblem, best in aconst: every edge answers the type —extensions.typeandextensions.titleon GraphQL,data.typeanddata.titleon WebSocket and MCP — and the filter goesservice_error.status(),service_error.as_response()on aServiceErrorHttpError::from(service_error).status(),.into_response(), orservice_error.to_problem():ServiceErroris aToProblemerror, no longer aResponseError, and?on it into anHttpErroris unchanged.opaque()over a borrowed error, or one that is onlyDisplayan owned std::error::Errorthat converts intoBox<dyn Error + Send + Sync>: it logs the whole chain;JobError::retry/abort,WsReply::from_handler_errorandOccurrenceLockError::newtake the sameServiceError::internal(format!("password hashing failed: {e}"))ServiceError::internal_because("password hashing failed", e)ServiceError::internal(&reason),reasona localStringor a borrowed&strServiceError::internal(reason.clone())or.to_owned(): the detail is'static; aStringor a&'static strpasses unchangedServiceError::Internal(msg)built or matchedServiceError::internal(msg); matchServiceError::Internal { .. }, the detail, then the cause’s chain, read aserr.source()’sDisplayerr.source()of aServiceError::Validationor aServiceError::Db, downcast toValidationErrorsorDbErrthe variant’s own field: ServiceError::Validation(errors), andServiceError::Db(err), aRepoErrortomatchon;source()says the failure aserror_messagedoeserr.source()of aServiceError::Internal, walked to the causeinternal_becausewas given and downcasta variant of your own error holding it, for a failure a caller decides on: source()is one sentence, whaterror_messagesays of the detail and the cause’s chain, with nothing beneath itServiceError::Masking(msg)built or matchednothing: the variant is gone, as no path built it. A wire row’s refusal is the edge’s own answer, and a failure of your own is ServiceError::internal(msg)AuthError::Failed(format!("…: {e}")),AuthError::Failed(msg)AuthError::failed_because("…", e),AuthError::failed(msg)AuthError::Unavailable(detail)orAuthError::Unavailable { detail, retry_after }builtAuthError::unavailable(detail, retry_after), orAuthError::unavailable_because(detail, retry_after, e)match err { AuthError::Failed(msg) => … },AuthError::Unavailable { detail, retry_after }matchedAuthError::Failed { .. },AuthError::Unavailable { retry_after, .. }, the detail read aserr.source()’sDisplayor the chain asnest_rs::core::error_message(&err)err.to_string()on anAuthError::FailedorUnavailable, read for its detailnest_rs::core::error_message(&err): theDisplayis"authentication failed"or"authentication unavailable"aloneasync fn authenticate(&self, req: &mut poem::Request)in aStrategyasync fn authenticate(&self, req: &mut nest_rs::http::Request)req.raw_path_param("provider"),req.params::<Q>()in a strategyreq.path_param("provider"), andQuery::<Q>::from_request(req, &mut RequestBody::new(Body::empty())).awaitbearer_token(req),basic_credentials(req)bearer_token(req.headers()),basic_credentials(req.headers())jwt.verify(token)?the same with .awaitbefore the?— a verification may fetch an issuer’s JWK Set;verify_handshakestays synchronousJwtConfig, from the authn cratenest_rs::authn::AuthnConfig, with the same fields and variablesJwtOptions { algorithm: …, ..JwtOptions::new(secret) }, oroptions.algorithm = …let mut options = JwtOptions::new(secret);thenoptions.algorithms = vec![…]jsonwebtoken::Algorithmpassed toJwtOptions::algorithmsorAuthnConfig::algorithmsnest_rs::authn::Algorithm, the same variants;"RS256".parse::<Algorithm>()fails withUnknownAlgorithmErrorAlgorithm::default();#[derive(Serialize, Deserialize)]over a field holding anAlgorithm;algorithm.family()name the algorithm ( Algorithm::HS256); storealgorithm.as_str()and read it back withparse::<Algorithm>(); match the variantsa matchonJwtKeynaming every variantthe same with a _arm: it gainsJwksPasswordError::InvalidHash(e)withe: argon2::password_hash::Error;error == othere: Arc<dyn Error + Send + Sync>— downcast it, or read the chain; match with a pattern#[inject] meter: Arc<OpenTelemetryMeter>#[inject] metrics: Arc<Metrics>meter.u64_counter("x").build().add(1, &[KeyValue::new("k", "v")])metrics.counter("x").add(1, &[Attribute::new("k", "v")])meter.f64_histogram("x").with_unit("ms").with_boundaries(b).build()metrics.histogram_with("x", Describe::default().with_unit("ms"), &B),Ba&'static [f64]AccessTokenResponse { access_token, token_type: "Bearer".into(), expires_in }AccessTokenResponse::bearer(access_token, expires_in), plus.with_scope(granted)when the issuer grants another scope than the one requesteda token handler returning Result<Json<AccessTokenResponse>>,Ok(Json(…))Result<AccessTokenResponse>,Ok(…): it answersCache-Control: no-store, and the document reads the body off the return typea token endpoint authenticating its clients through AuthnGuard<S>ClientAuthenticationGuard<S>over the same strategy: §5.2’sinvalid_client,401with theBasicchallenge over theAuthorizationheader,400withouta token route reading Form<AccessTokenRequest>, or code decoding it with serderequest: AccessTokenRequest, the handler parameter: the type derives noDeserialize, and its refusals areinvalid_requestif request.grant_type != "client_credentials" { return Err(TokenError::UnsupportedGrant) }nothing: request.grant_typeis aGrantType(GrantType::ClientCredentials), and a grant the endpoint does not serve is refusedunsupported_grant_typebefore the handler runsrequest.scoperead as anOption<String>and narrowed to the client’s scopes by handclient.scope_for(&request.scope)?:scopeis §3.3’sVec<String>, and the grant is strict — none asked is the whole registration, an unregistered scopeinvalid_scopea client registry in a config of your own, checked by a strategy calling authenticate_against_registryOAuthServerModule::<P>in the module’simports,Pyour payload, read from<PREFIX>_OAUTH__SERVER__CLIENTS; the token route binds#[use_guards(ClientGuard<P>)], which the module provides with its strategy, andArc<OAuthServerConfig<P>>is injectable where you read the registryClientSecretBasicStrategy<P>andClientAuthenticationGuard<ClientSecretBasicStrategy<P>>in a module’sproviders, behind a guard alias of your owndelete both lines and the alias: OAuthServerModule::<P>provides them, and the route bindsnest_rs::oauth::server::ClientGuard<P><OAuthServerConfig<P> as Namespaced>::NAMESPACEOAuthServerConfig::<P>::NAMESPACE, withNamespacedin scopeexp: jwt.expiry()in a claims literal,pub exp: u64on a claims type the app signsdelete both: the signer stamps exp, itsexpires_inafteriat; a token living another time names it withexp: jwt.expiry_in(secs), as asign_handshake’s claims must.requires_scope("posts:read")pub const POSTS_READ: Scope = Scope::new("posts:read");(nest_rs::guards::Scope) once, then.requires_scope(POSTS_READ)<PREFIX>_OAUTH__RESOURCE__SCOPES_SUPPORTEDrepeating the scopes your rules gate onOAuthResourceModule::for_root([POSTS_READ, …])(or([…], config)beside a pinned config), and delete the variable; a deployment still setting it advertises its list insteada social authorize handler building its 302fromprovider.authorize(&jwt, resource)—Set-Cookie,Location, a404for an unknown providerOk(providers.authorize(&provider, &jwt, resource)?): aSocialRedirect, the302with the cookie andCache-Control: no-store, or the404a nestrs g authdev-token handler returningJson<DevTokenResponseDto>with two#[response_header]linesResult<AccessTokenResponse>,Ok(AccessTokenResponse::bearer(self.jwt.sign(&claims)?, self.jwt.ttl_secs())), withoauth-serveramong the features crate’snest-rsfeatures; delete the DTO — the old one still compileshash_password(p)?stored or compared as aStringa Secret<String>: store it as is, and passhash.expose_secret()toverify_passwordthe development-token route’s DevOnlyGuardandDevTokenAudit, written by an earliernestrs g authnest_rs::authn::DevelopmentOnlyGuard, bound with#[use_guards]on the controller and listed in its module’sproviders; deleteauthn/http/guard.rsandauthn/http/audit.rsTokenError::InvalidClientbuilt or matchedTokenError::InvalidClient(TokenEndpointAuthMethod::ClientSecretBasic)for a client refused over theAuthorizationheader,ClientSecretPostfor credentials in the body,Nonefor none; matched asInvalidClient(_)TokenError::InvalidClientanswered for a rejected resource-owner passwordTokenError::InvalidGrant(400 invalid_grant)RegisteredClient { client_id, client_secret, scopes, payload }/AuthenticatedClient { payload, scopes }RegisteredClient::new(client_id, client_secret, scopes, resources, payload)/AuthenticatedClient::new(client_id, scopes, resources, payload): the RFC 8707 resources the client’s tokens may be minted forresponse.access_token,tokens.access_token/id_token/refresh_token,JwtKey::Hmac(secret)orJwtKey::Pem { private_pem, .. }read as a string.expose_secret()on each: they arenest_rs::core::Secret<String>profile.email.as_deref(),profile.name.clone()on aSocialProfileprofile.email.as_ref().map(|e| e.expose_secret().as_str()): a provider’s email and name areOption<Secret<String>>, whichDebugprints asSome(<redacted>)a client registry in configuration, [{"client_id": …, "scopes": […], "payload": …}]each client lists "resources": [...], the URIs of the resource servers it calls; a registry without it fails the bootjwt.sign(&claims)minting an access token another app verifiesjwt.sign_for(audience, &claims),audiencethe resource it is for — at a token endpointclient.audience_for(&request.resource)?, which answers RFC 8707’sinvalid_targetfor a resource the client is not registered for;signstamps this app’s own audience, for what it mints for itself<PREFIX>_AUTHN__AUDIENCEset to<PREFIX>_OAUTH__RESOURCE__RESOURCEbesideOAuthResourceModuledelete it: the resource is the audience. Keep it only for an audience your authorization server mints by policy <PREFIX>_AUTHN__ISSUERbesideOAuthResourceModulenaming anything but an entry of<PREFIX>_OAUTH__RESOURCE__AUTHORIZATION_SERVERSthat entry, exactly, or no ISSUER: a token’sissmust then be one of themAuthnModuleimported at the root besideOAuthResourceModuledelete the line: the module imports the verifier it binds. Keep AuthnModule::for_root(cfg)only to pin a configuration in code — not a compile error, the bare line is merely redundantAuthenticatedClient::actor_id()read asNoneit is the client’s client_id— not a compile error; code keying “a machine caller” onNonereads the principal’s typePrincipalIdentity::actor_idreturningNonefor a machine principalits subject — the client id when it acts for itself (RFC 9068 §2.2) an OAuth authorize handler building its 302fromauthorization.urlandauthorization.transaction—Location, a hand-writtenSet-CookieOk(client.authorize(&jwt, provider, resource)?), underResult<AuthorizationRedirect>: the302with the cookie andCache-Control: no-store, documented by the type; behind a social provider, theSocialRedirectSocialRegistry::authorizeanswersthe callback’s own parsing of the transaction cookie OAuthClient::transaction_from(req.headers().get_all(header::COOKIE).iter().filter_map(|field| field.to_str().ok()))impl SocialSignIn for Swithasync fn sign_in(&self, profile, resource)(E0050)async fn sign_in(&self, profile: SocialProfile, tokens: TokenSet, resource: Option<&str>),TokenSetfromnest_rs::oauth::client: the provider’s access token and the refresh token it issued;_tokenswhen you keep neitheran OAuthClientConfig { … },GithubSocialConfig { … }orGoogleSocialConfig { … }literal listing every field (E0063)add authorization_parameters: AuthorizationParameters::default(), or end the literal with..Default::default()a social callback strategy of your own reading provider,code,stateand the cookieAuthnGuard<SocialStrategy<S>>on the callback route,SocialStrategy<S>and the guard in the module’sproviders, andimpl SocialSignIn for Ssaying who aSocialProfileis — the rest, §4.1.2.1’serrorincluded, is the strategy’sjwt.sign(&serde_json::json!({ … })), orsign/sign_foron claims with noPrincipalIdentity(E0277)#[derive(PrincipalIdentity)]on the claims struct,#[principal(actor)]on the field naming the subject: claims with nosubfield are stamped it. A test forging a token hands it toapp.bearer(&claims), which signs what it is givenclaims signorsign_formints naming noclient_idpub client_id: Stringon the claims, the client the token is issued to — the one a user signed in through, a machine client’s own — set in each literal; a test’s claims name one too (client_id: "e2e".into()). Not a compile error:signanswers aSignErrornaming the claimJwtOptionsbuilt in code with noissueror noaudienceset both: options.issuer = Some(…)andoptions.audience = Some(…);JwtService::newrefuses naming each it lacksjwt.sign(&claims)?,sign_fororsign_handshakein aResult<_, AuthError>(E0277)a handler answers nest_rs::http::Result, into whichSignErrorandAuthErroreach convert on their own status; a service holds#[from] SignErrorin its own error.TokenErrordoes already, so?needs nomap_err.map_err(|e| TokenError::Sign(e.into()))oversign_fororauthorize,TokenError::Sign(anyhow!(…))built?for the first;TokenError::Sign(SignError::new("…"))for the second: the variant holds aSignError.opaque()oversign,sign_for,client.authorizeorproviders.authorizedelete it — not a compile error: ?answers the same opaque500impl SocialProvideroverridingauthorizeto returnResult<AuthorizationRedirect, AuthError>, or matchingAuthError::Failed { .. }fromsign,authorizeResult<AuthorizationRedirect, SignError>, built withSignError::neworSignError::because;nest_rs::core::error_message(&error)reads what failedredirect.urlread,redirect.url.push_str(…)in a provider’s overrideredirect.url(): read-only, and no setter appends to itredirect.transaction,redirect.set_cookie()delete them: return the redirect, whose answer alone carries the cookie, with Cache-Control: no-store. A test readsSet-Cookieoffredirect.into_response()a RegisteredClient’sclient_secretreadnothing outside the crate reads it ( E0616): it is the registry’s to compareclient.authorize(&jwt, provider),provider.authorize(&jwt)client.authorize(&jwt, provider, resource),provider.authorize(&jwt, resource): the RFC 8707 resource the sign-in asks for, orNone, signed into the transactionclient.exchange(&jwt, provider, transaction, state, code).await?let response = OAuthClient::callback(&jwt, provider, transaction, req.uri().query().unwrap_or_default())?;thenclient.exchange(response).await?—callbackreadsstate,codeand §4.1.2.1’serroroff the query itself;response.resource()reads the resource backa SocialProvider::exchangeoverride taking the transaction,stateandcodethe same override taking the matched AuthorizationResponse, and building its answer withTokenSet::new(access_token),.with_id_token(…),.with_refresh_token(…)#[module(imports = [SocialModule, …])], providers enabled by their credentialsimport each provider’s module in its place: GithubSocialModule, GoogleSocialModule, each importingSocialModulea SocialProviderEntry { … }of your ownSocialProviderEntry::new::<AcmeProvider, AcmeSocialModule>(key, AcmeSocialConfig::NAMESPACE, build), and a#[module(imports = [SocialModule])] pub struct AcmeSocialModule;the app importsAbility::can(action, &model)under a grant resting on a relation, which answeredtruefalse:Repo::<E>::can(action, &model).await?asks SQL, one indexed queryPredicate::matcheson a relational predicatefalse:Ability::canis the instance checknest_rs::authz::graphql::ability(ctx)?,ctx.data::<Arc<Ability>>()nest_rs::authz::graphql::ability()?,nest_rs::authz::current_ability()with_ability(ability, fut)in a request, running the body under an ability the service builtthe caller’s rules in the AbilityFactory:with_abilityonly narrows — what both allow inside a unit holding an ability, nothing installed in a request no ability guard authorizedwith_ability(ability, fut)in a job, to act for a principalunchanged: in a job, which holds none, the body runs under abilityan Abilityattached by a guard of your own (cx.attach(ability)), or installed withwith_ambient(Arc::new(ability), fut)AbilityGuard<F>over anAbilityFactory, after the authentication guard: the ability guard is the one place an ability comes fromab.cannot(action, E).requires_scope(scope)ab.cannot(action, E): a denial holds whatever the token carries. To let a narrower token through, gate the grant withrequires_scopeinsteadab.cannot(action, E).fields([...])drop .fields: a denial hides rows, never columns. Narrow what a grant exposes with the grant’s own.fieldsab.can(Action::Update, E).fields([...]), onCreateor onManage, written to narrow the write’s replythe list is both what the write sets and what its reply shows, so a reply narrower than the write cannot be declared. List each column the write chooses, and its reply shows them. Dropping the list answers every exposed column on that write, whose reply reads its own grant, never Read’s. A column a service sets by itself goes on the list or inbefore_saveFieldSet::Only(cols)read against a wire keythe set holds Column::as_str(), the table’s name:fields.permits(column.as_str()). Only acolumn_nametells the two apartRuleSpec<'_, E>naming whatcannotreturns, a helper’s return type or a binding’sRuleSpec<'_, E, Cannot>,Cannotfromnest_rs::authz; a grant’s staysRuleSpec<'_, E>masked_item_for::<A, E, _>(ctx, item)on a subscription’s itemnothing: build the wire row in the stream, .map(|event| Post::from(&event.post)), and the posture judges each item for its subscriber where the socket polls it, an item its grants refuse leaving the streammodel_attrs(derive(PartialEq, Serialize, Deserialize))— or aSerializeorDeserializein the entity’s#[derive]— anduse serde::{Deserialize, Serialize}on an#[expose]d entityrefused at the derive: delete both, and the features crate’s serdeline if nothing else names serde.#[expose]writes the wire type’s serde, so theModelderives none. Keepmodel_attrs(derive(PartialEq))only where your code compares rowsJson(model),WsReply::reply(&model)answering a rowits exposed type, Json(User::from(&model)): once the derive goes, a rawModelanswers nowhere, and its hidden columns with ita route, message, GraphQL field, tool or resource answering a Modelno#[expose]decorates, derivingSerialize,JsonSchemaorSimpleObjectitself —Json<secret::Model>,Vec<…>,Option<…>, a stream’s items,#[api(response = secret::Model)]refused at the type, a row crosses no wire:#[expose]the entity and answer its exposed type, or answer a DTO naming the columns it answers; the derive on the row then goes tooa SerializeorDeserializewritten by hand on an#[expose]dModelorModelEx, or derived above#[expose];#[output]or#[input]on one; aJsonSchemaon one; with thegraphqlfeature, aSimpleObject,InputObjector#[Object]on onerefused, each writing or reading columns no mask shapes: answer the exposed type, User::from(&model), and take the inputs#[expose(input(..))]declares. A row kept in a cache or a queue payload is its exposed type too, or a DTO of its own that lists what it holdsa blanket of your own over one of those traits, impl<T: Serialize> Audited for T, beside a specific impl on an#[expose]dModelorModelEx,impl Audited for ModelE0119, since rustc reads what#[expose]emits on the row as an impl upstream could make hold. Delete the row’s impl: the exposed type already meets the blanket,User::from(&model).audit(), and an impl on it would overlap the same way. A row that keeps its own bounds the blanket on a trait of yours, implemented on the exposed types#[derive(Default)]and#[wire_enum]on an enum a hidden column alone holds, there for the maskoptional: drop both — a hidden column’s type needs no serde, and no reply rebuilds it a hand-written impl WireModelDefaults, oruse nest_rs::authz::WireModelDefaults#[expose(name = "…")]on the entity: the trait is gone, and the wire type is the decorator’s aloneAbility::mask,mask_manyormasked_replyon a row or a valuegone: build the exposed type from the row, User::from(&row), which judges it for the caller whose ability is installed therea subscription pushing the wire row its publisher built ( PostPublishedEvent { post: Post })carry the row, post: Model, and build the wire row in the stream: a wire row answers only the caller whose ability judged it, so the publisher’s answers no subscriber and leaves the stream, oneerrorline eachab.can(Action::Read, E).fields([...]), or onManage, leaving out a column the reply cannot answernull#[expose(nullable)]on each column the grant may withhold, or anOptioncolumn: the grant failsbuild()otherwise, naming the column. The field readsnullfor that caller, nullable in every edge’s schema, its key still requireda GraphQL client of a member selecting a column the member’s grant withholds, which answered FORBIDDENrefusing the selection (ordata: nullover a list)the column reads nullon each row and nothing is refused, since the schema now says it is nullable#[authorize(Action, Entity, unmasked)]or#[public(Action, Entity, unmasked)], on any edge#[authorize(Action, Entity)]: no reply mask is left to leave to the body, so the key is refused naming whyunmaskedbeside a posture on a#[subject](#[authorize(Manage, Transcoding, unmasked)]) whose body reads rows throughRepo#[authorize(Manage, Transcoding)]: a posture naming a capability opens its unit’s reads to the caller’s ability as an entity’s does, each row it answers judged for that caller. A visitor’s reads stay withheld there#[wire_default]or#[wire_default(expr)]on a hidden columndelete it: no reply rebuilds a row, so the attribute is refused naming why a wire type built by struct literal ( User { id, name, .. }) or read back with serde (serde_json::from_*::<User>)User::from(&row): a wire row carries a private proof of its judgement and has noDeserialize. A test reading a reply decodesserde_json::Value, or a type of its owna wire row handed to WsServer::broadcast,emit_tooremitfrom a requesta DTO every recipient may read, or a row a job built: a row judged for the caller pushing it refuses on a push to other connections a route under #[authorize(Update, E)]answering the row it wrote to a caller whoseReadgrants refuse that row403, the write rolled back, where the reply was masked atUpdate’s fields; in a GraphQL mutation’s reply the row answers its key alone. A write-only client answers204or the keya GraphQL query or subscription answering a row its caller’s grants refuse, built by hand ( { members { id } }over a list the body put a stranger’s row in)FORBIDDEN, the key included: a refused row answers its key in a mutation’s reply alone. A list fails closed whole, and a subscription item holding such a row bare, in a list, anOptionor aResultleaves the stream. AReporead never hands a body such a rowa wire row a job built kept past the job (a cache, a static) and answered by a route, a message or a tool 500and anerrorline: a row a job built answers inside a job and on a push to other connections alone. Build the row where it answers, from theModelthe job kepta client reading a write’s reply as Update’s.fieldscut it ({ "id", "title" }under.fields([Id, Title]))the reply holds what the caller may read, every column its Readgrants permit, whatever the write’s own list:.fieldson a write names what it may set. A columnReadwithholds readsnullthere as on any reply, where a write grant with no list answered every exposed columnA project scaffolded by an earlier
nestrs g authkeepssub: Option<Uuid>in its claims, which cannot hold a client’s own id; the JWT page shows the claims a 7.0 scaffold writes, whose subject is always present. Optionally, the claims’ two hand-written impls may be derived:#[derive(PrincipalIdentity)]on the struct,#[principal(actor)]on the fieldactor_idreturned, and#[principal(tenant)]and#[principal(scopes)]on thosetenant_idandscopesread, then deleteimpl AmbientValueandimpl PrincipalIdentity. Kept, they compile as before. Anhttp://localhostOAuth or social-login redirect, a protected resource’s or an issuer’s loopbackhttpURI, serve a declared development or test profile alone. -
Move every layer onto the unit context. One pipeline runs every unit on every edge, and every layer reads it through
UnitContext— see Execution context and the request lifecycle. Each row is a compile error unless it says otherwise; work through them in this order, guards first, since an interceptor or a filter often reads what a guard attached.Guards
6.x 7.0 a guard’s async fn check_http(&self, req: &mut Request)async fn check_http(&self, cx: &mut UnitContext<'_>): the request throughHttpView::of(cx)?.request()—request_mut()to read the body and set it back — and the route’s#[meta]and posture throughcx.reflector()a guard’s check_graphql,check_ws_messageorcheck_mcpone async fn check(&self, cx: &mut UnitContext<'_>): the field, message or operation throughcx.switch_to::<GraphqlView>(),WsVieworMcpView, its name throughcx.handler().address()one decision written twice, in check_httpand in an in-band entrythe decision once, in check:check_httpruns it unless the guard overrides it, which it does only where the request differs from the unit (it reads the request, or a value missing at the request means something else)an impl Guardwriting onlycheck_http, or nothingits decision in check, whichcheck_httpruns:checkhas no default. A guard whose decision is the request’s alone — an authentication guard in the global pool — keepscheck_httpand admits the units the request carries:async fn check(&self, _cx: &mut UnitContext<'_>) -> Result<(), Denial> { Ok(()) }; one admitting an in-band request readsPosture::Gatedthere, to refuse what its principal is absent froma guard whose decision is a field’s, a message’s or an operation’s alone, registered with use_guards_globalthe same check, andasync fn check_http(&self, _cx: &mut UnitContext<'_>) -> Result<(), Denial> { Ok(()) }beside it: a pooled guard’schecknow runs on every request tooimpl Layer for X {}, empty#[derive(Layer)]on the struct —#[layer(priority = …)]for an override ofLayer::priority; a layer overridingserveskeeps itsimpl#[derive(Default)]beside#[injectable]on a struct with no fieldnothing: a fieldless struct, unit or braced, is built as written a tracing::warn!orerror!a guard files before returning itsErrthe denial names why — Denial::forbidden("…").with_reason("banned_author")— and the guard its target,fn target(&self) -> &'static str { crate::TARGET }: the edge files each denial once,guard denied …on that target, with the reason and, when the denial keeps a cause (.with_source(err)), the whole chain from its own text downcx.ambient::<Claims>()with anelsereturningDenial::internal("… must run first"), a value an earlier guard must have attachedcx.require::<Claims>()?: its absence is a500the edge files once aterror, naming the guard and the typea guard reading the principal in two bodies, check_httpfor the route’s wiring gap andcheckfor/graphql’s visitorone checkcallingcx.require::<Claims>()?, andfn expected_principal(&self) -> Option<PrincipalClaim> { Some(PrincipalClaim::of::<Claims>()) }: absent, it is the caller’s401on every edge, and nothing attaching it fails the bootan authentication guard of your own, beside a guard declaring expected_principalfn produced_principal(&self) -> Option<PrincipalClaim> { Some(PrincipalClaim::of::<Claims>()) }on it: the boot reads who attaches the principala guard that reads a principal where one is and decides a visitor itself, declaring it through expected_principalPrincipalClaim::of::<T>().or_visitor(): nothing attaching it stays awarna Denial::Unauthorized(…),Forbidden(…),RateLimited { … }or other variant built or matchedits constructor — Denial::forbidden(…),Denial::rate_limited(…)— and, to tell denials apart,denial.http_status()anddenial.bearer_error():Denial’s fields are privateimpl HttpGuard for X {},GraphqlGuard,WsGuard,McpGuardimpl GuardFor<HttpView> for X {},GuardFor<GraphqlView>,GuardFor<WsView>,GuardFor<McpView>req.extensions_mut().insert(value)in a guard, read back withCtx<T>cx.attach(value), withimpl AmbientValue for T {}beside the type; a guard after it readscx.ambient::<T>()use nest_rs::http::Ctx;, aCtx<T>parameteruse nest_rs::core::Ambient;, anAmbient<T>parameter — named for the ambient context it reads, the same parameter on a route, a resolver, a message handler and a tool;nest_rs::prelude::*carries ita Strategy::Principalor anAbilityFactory::Actorthat is not your own type ((),&'static str)a type of your own implementing AmbientValueandClone— the guard attaches it; aClaimsgainsimpl AmbientValue for Claims {}, or derives it with itsPrincipalIdentity(step 9)if Reflector::new(req).is_public() { return Ok(()) }in an authentication guardif matches!(cx.reflector().posture(), Posture::Public | Posture::InBand) { return Ok(()) }—/graphqlisInBand, each operation declaring its own posturenest_rs::guards::prelude::HttpRequestHttpView, andnest_rs::http::Requestfor the type it holdsa Denial::Unavailable { retry_after_secs, reason }built in fullDenial::unavailable(retry_after_secs, reason)— and.with_source(err)to keep what failedthe graphql,mcporwsfeature ofnest-rs-throttlerornest-rs-guardsnothing: a guard’s edges are its GuardFordeclarations, andThrottlerGuarddeclares every viewnest_rs::guards::{GuardEndpoint, GuardExt}, a guard wrapped around an endpoint by hand#[use_guards]on the controller or gateway, or the app’s global pool: each edge runs its own guard stage#[use_guards(X)] #[force_guards(X)]on a method#[force_guards(X)]a guard, interceptor, filter or pipe overriding Layer::priorityto run before a broader scope’s layersdeclare it at that broader scope, or list it first there: a priority orders within one scope #[use_guards(…)]beside a handler listing an authorization guard before the authentication guard it readslist the authentication guard first, or declare the pair on the controller nest_rs::authz::graphql::authorize::<A, E>(ctx)?,ws::authorize::<A, E>(event),mcp::authorize::<A, E>()?in a hand-written body#[authorize(A, E)]on the operation, ornest_rs::authz::class_gate::<A, E>on its unit’s contextnest_rs::authz::gate::<A, E>(&ability)andGateVerdictnest_rs::authz::class_gate::<A, E>(cx)What a site declared, and what a unit carries
6.x 7.0 nest_rs::http::Reflector,HandlerMetadata,Reflector::new(req)cx.reflector()req.extensions().get::<Throttle>()in a guard, for a route’s#[meta(Throttle(..))]cx.reflector().get::<Throttle>()— the method’s value over its controller’sreq.extensions().get::<Public>()in a guardcx.reflector().is_public()a #[meta(..)]repeated on every route of a controllerone #[meta(..)]under#[controller], a route’s own overriding itGraphqlOperationContext,McpOperationContextGraphqlView,McpViewa value an interceptor, a middleware or a test put in the request’s extensions, read back with Ctx<T>the value made ambient around what reads it — nest_rs::core::with_ambient(Arc::new(value), next.run(cx)), orcx.attach(value)beforenext.run(cx)— or attached by a guard;Ambient<T>reads no extensiona value of your own in a tokio::task_local!carried by handimpl AmbientValue for T {}, added withwith_ambientorcx.attach, read withambient::<T>()RequestContinuation::current()RequestContinuation::capture(Continuation::Task), or the continuation the work isanother driver’s after_commitre-installing the scope and the ability around held workcapture RequestContinuation::capture(Continuation::Commit)and readcurrent_executor_scope()where the work is registered; run it inside the captureThe guards in front of
/graphql,/mcpand a socket6.x 7.0 GraphqlAbilityBridge<AuthnGuard, AuthzGuard> as dyn GraphqlOperationGuardin a module’sprovidersEndpointGuards<GraphqlView, (AuthnGuard, AuthzGuard)>McpAbilityBridge<AuthnGuard, AuthzGuard> as dyn McpOperationGuardin a module’sprovidersEndpointGuards<McpView, (AuthnGuard, AuthzGuard)>an impl GraphqlOperationGuard/impl McpOperationGuardof your owna Guardwithcheck_httpandimpl GuardFor<HttpView>, listed inEndpointGuards<…>AllowAllMcpGuard as dyn McpOperationGuardMcpModule::for_root(McpAccess::Public)in the app’s rootGlobalPoolOperationGuard,GlobalPoolMcpGuardnothing: the transport runs the global pool at the /graphqland/mcprequestsforward_principal!(Claims);in a module,ctx.data::<Claims>()?in a resolvernothing in the module; a claims: Ambient<Claims>parameter on the operation, no argument of the schemanest_rs::core::ambient::<Claims>()read by hand in a resolver, a message handler or a tool, with an.ok_or(…)of its owna caller: Ambient<Claims>parameter — not a compile error: the hand-written read still compiles, and the parameter answers a miss opaquely, its type filed aterrorLoaderScope as dyn GraphqlBatchContextin a module’sproviders,use nest_rs::seaorm::graphql::LoaderScope;nothing: a DataLoader batch carries the request’s ambient values itself impl McpToolContext for X(capture,around), providedas dyn McpToolContextan interceptor making the value ambient ( cx.attach,with_ambient), inGlobalInterceptors<(…)>or#[interceptor(stage = unit)], read withnest_rs::core::ambient::<T>()#[use_guards(G)]beside an#[mcp]host writing rmcp’sServerHandlerEndpointGuards<McpView, G>declared by a module, or the host’s tools under#[tools]impl SocketContext for MyBridgelistedas dyn SocketContext, carrying a value from the upgrade into each messagea guard on the gateway (or the app’s pool) attaching the value with cx.attach(value)incheck_http: the connection carries it into every message and hooknest_rs::ws::{SocketContext, Captured, BoxFuture}nothing: the seam is gone app.graphql_socket().data(ability)to subscribe as a callerapp.graphql_socket().ability(ability), anArc<Ability>(testingwithauthz);attach(..)takes any other value a guard attaches,data(..)a context value alonePipes
6.x 7.0 fn transform_body(&self, v: &mut Value) -> Result<(), PipeError>on a global pipefn transform(&self, cx: &UnitContext<'_>, argument: ArgumentKind, v: &mut Value) -> Result<(), PipeError>, acting whenargument == ArgumentKind::Bodyfn transform_graphql_variables(&self, v: &mut Value)the same transform, onArgumentKind::Variablesfn transform_ws_data(&self, event: &str, v: &mut Value)the same transform, onArgumentKind::Data; the event iscx.handler().address(), orcx.switch_to::<WsView>()’sevent()App::builder().use_guards_global([guard::<AuthnGuard>(), guard::<AuthzGuard>()])inmain, anduse nest_rs::guards::{AppBuilderGuardsExt, guard};GlobalGuards<(AuthnGuard, AuthzGuard)>in the providers of the modulemainboots,use nest_rs::guards::GlobalGuards;, andmainkeepsApp::builder().module::<AppModule>(): a suite booting that module runs the pool, so delete the copy it made (.use_guards_global(…)onTestApp::builder())App::builder().use_pipes_global([pipe::<P>()]), throughnest_rs::guards::AppBuilderPipesExtornest_rs::pipes::AppBuilderPipesExtGlobalPipes<(P,)>in the providers of the modulemainbootsnest_rs::guards::{PipeSpec, PipeSpecs},nest_rs::guards::{GuardSpec, GuardSpecs, guard},nest_rs::pipes::{PipeSpec, PipeSpecs, pipe},nest_rs::core::{InterceptorSpec, ExceptionFilterSpec, interceptor(), exception_filter()},nest_rs::core::layer_chain::GlobalSpecsnothing: the pools are the declarations above, a decorator builds its own layer list, and the registries are no API GlobalGuards<…>or another pool listed in a feature’s modulethe module the app boots lists it: one an imported module lists fails the boot Interceptors and exception filters
6.x 7.0 impl Interceptorfromnest_rs::interceptors,async fn intercept(&self, req: Request, next: Next<'_>) -> Result<Response>nest_rs::core::Interceptor,async fn intercept(&self, cx: &mut UnitContext<'_>, next: Next<'_>) -> Outcome: run the rest withnext.run(cx).await, the request throughHttpView::of(cx)?.request(), the reply throughresponse_mut()once it returned — see Interceptorsimpl ExceptionFilterfromnest_rs::exception_filters,async fn catch(&self, err: E) -> Responsenest_rs::core::ExceptionFilter,async fn catch(&self, err: &E, cx: &mut UnitContext<'_>) -> Caught:match HttpView::of(cx) { Ok(view) => Caught::Answered(view.respond(response)), Err(_) => Caught::Declined },Caught::Problem(problem)orCaught::Declined— see Error handlingimpl Filterfromnest_rs::filters,#[use_filters(F)],use_filters_global([filter::<F>()])an exception filter whose type Exception = dyn Error + Send + Sync, bound with#[use_exception_filters(F)]orGlobalExceptionFilters<(F,)>in the providers of the modulemainboots;#[use_filters]is refused naming itLayerKind::FilterLayerKind::ExceptionFilteruse nest_rs::interceptors::AppBuilderInterceptorsExt;,AppBuilderExceptionFiltersExt,AppBuilderFiltersExt, andApp::builder().use_interceptors_global([interceptor::<I>()]),.use_exception_filters_global([exception_filter::<F>()])GlobalInterceptors<(I,)>andGlobalExceptionFilters<(F,)>fromnest_rs::core, in the providers of the modulemainboots#[nest_rs::http::interceptor(priority = n)], a module bringing it to every handler#[injectable]on the struct andGlobalInterceptors<(I,)>in the providers of the modulemainboots, at the handler stage: a bare#[interceptor]is refused naming it. Around the guards,#[nest_rs::core::interceptor(stage = unit)], which its module’s import brings; the order within a stage isLayer::priorityon the struct’sLayerimpla layer listed twice at the root, providers = [P, GlobalPipes<(P,)>]providers = [GlobalPipes<(P,)>], each pool alike: a pool registers what it lists unless the app already does. The longer form still boots, and a layer a module lists stays that module’sa type in a pool that no decorator makes a provider, registered by hand or by a factory #[injectable]on it, or aDiscoverableimpl: a pool’s entries are providers, and the compiler says so where the pool names it#[use_interceptors]/#[use_exception_filters]on a#[controller]onlyalso on a #[resolver]and beside its fields, a#[gateway]and beside a#[subscribe_message], an#[mcp]host and beside its#[tool],#[prompt],#[resource]and#[resources]methods, a#[processor],#[scheduled]or#[listeners]blockan interceptor or exception filter written around a gateway’s handler bodies by hand #[use_interceptors(...)]/#[use_exception_filters(...)]on the#[gateway]or beside a#[subscribe_message]a global interceptor or filter written for HTTP requests alone the same with fn serves(&self, unit: Unit) -> bool { unit == nest_rs::http::unit::REQUEST }on itsLayerimpl — not a compile error: without it, it now runs around every unit on every edgeThe unit of work and the framework’s internals
6.x 7.0 nest_rs::seaorm::DbContext, listed or built by handnothing: importing SeaOrmDatabaseModulemakes every edge run each unit as a unit of worknest_rs::http::MappedErroron a filter’s responsenothing: a failed unit never commits, whatever a filter answered nest_rs::http::{CarriedUnits, carried_units}nothing: the transport runs a /graphqlor/mcprequest on the pool itselfconst GATE: Option<fn(&poem::Request) -> Option<poem::Response>>on aRouteResponseShaperconst GATE: Option<for<'b> fn(&mut UnitContext<'b>) -> Result<(), Failure>>, refusing with aDenial(Err(denial.into()))HttpBootCheck::new(|container| …)listed as a provider’s metadataa step on ContainerBuilder::provide_wiring: it runs in every app importing the modulenest_rs::guards::layer_chain::{LayerSpec, LayerSite}nest_rs::core::{LayerSpec, LayerSite}nest_rs::guards::{dispatch, RouteShaper, GraphqlSite, run_layered_graphql_chain, run_layered_mcp_chain, GuardAsWsMessageCheck},nest_rs::http::{GlobalGuardsActive, Public},nest_rs::ws::{WsMessageCheck, EventLayerTable, gateway_endpoint},nest_rs::graphql::GraphqlFederationGuard,nest_rs::authz::run_ability_chainnothing: the decorators’ expansions call each edge’s own stage, which is no API nest_rs::guards::denial_to_graphql_error,denial_to_ws_error,denial_to_mcp_errornest_rs::graphql::denial_to_graphql_error,nest_rs::ws::denial_to_ws_error,nest_rs::mcp::denial_to_mcp_errornest_rs::guards::denial_to_http_response,denial_to_http_errora guard returns its Denial; an extractor answers aProblemDetailsor an error of its own implementingResponseErrornest_rs::guards::NoBearerChallengenest_rs::http::challenge::NoBearerChallengetwo #[meta(Tag::new(..))]on one method or one hostone: the boot refuses the second An anonymous caller of an
#[authorize]route that is not#[public]is refused401, where the visitor’s rules used to decide it: declare the route#[public(A, E)]to serve visitors. -
Move data onto the unit of work. Every edge — a request, a GraphQL operation, a WebSocket message, an MCP operation, a job, a tick, a listener, a lifecycle hook — runs its work through one port,
nest_rs::database::UnitOfWork, whichSeaOrmDatabaseModulebinds. Delete the data contexts from your authz modules first:WsDataContext as dyn SocketContextleavesauthz/ws/module.rs— andnestrs g wsnow writes none: a gateway’s adapter importsAuthzModuleitself, as an HTTP adapter does — andMcpDataContext as dyn McpToolContextleavesauthz/mcp/module.rs; the edges open their units themselves. An app reaching a#[crud]host, a route or field under#[authorize(A, bind = S)], or the service a GraphQL-exposed entity names (#[expose(service = S, graphql)]) importsSeaOrmDatabaseModule, which imports theSeaOrmModuleopening its pool: 6.x booted without it and failed every call such a host made; 7.0 refuses the boot naming it.6.x 7.0 nest_rs::worker::JobContextnest_rs::database::UnitOfWork(withOpenUnit)nest_rs::worker::JobTransaction(PerAttempt,Pool),ScheduledMethod::transaction,CronJobMeta::transactionnest_rs::database::TransactionPolicy(PerUnit,Pool)nest_rs::worker::JobSettlement,Unhonoured,BACKEND_REMEDYnest_rs::database::{Settlement, Unhonoured, BACKEND_REMEDY}nest_rs::worker::run_in_job_context(ctx, transaction, fut, ok, unhonoured)nest_rs::database::run_unit(unit_of_work, UnitSpec::new(unit, scope, policy), fut, ok, unhonoured)nest_rs::worker::TARGET,nest_rs::worker::context,nest_rs::schedule::nest_rs_worker::JOB_TIMEOUTgone; the job bound is nest_rs::core::JOB_TIMEOUT, and nothing files onnest_rs::workerany morenest_rs::seaorm::WorkerDbContext;nest_rs::seaorm::ws::WsDataContext,mcp::McpDataContext; the seaormwsandmcpfeaturesnest_rs::seaorm::SeaOrmUnitOfWork; nothing: delete thema database driver’s request interceptor and JobContextone UnitOfWork, bound throughnest_rs::database::provide_unit_of_work, which also runs every lifecycle hook in a unit; it implementssettle_net, andExecutor::atomicto offer an atomic block (Writing a driver)a matchonExecutorScope,TransactionPolicyorRepoErroroutside its crateadd a _arm that fails closedResult<T, DbErr>fromRepo, aRepoSelect, a page read orCrudService(list,access,create,update,delete), andretry_on_conflict’s answer;Err(DbErr::RecordNotUpdated),DbErr::RecordNotFound,DbErr::RecordNotInsertedorDbErr::AccessDeniedmatched;ServiceError::Db(db_err)nest_rs::seaorm::RepoError:RepoError::NotFound,RepoError::Forbidden { columns, .. }(a create its scope refuses names no column),RepoError::UniqueViolation(key)withkey.constraint(),ForeignKeyViolation,SerializationFailure,QueryCanceled,Other { .. }.?into aServiceErroris unchanged, and no reader of it prints the server’s message ordetail; aDbErrof your own (a migration, a seed, a transaction you opened) becomes one withRepoError::froma DbErr?-ed into ananyhow::Result:Migrator::up(conn, None).await?in your migrations crate’smigratehelper and binary, a seed’s statements.map_err(RepoError::from)before the?, the helper answeringResult<(), RepoError>: ananyhowreport of aDbErrprints the row a data migration refused.nestrs g migrationregeneratesmigrator.rswith the helperRepo::<E>::conn(), and a query run on it (Entity::find()….all(&conn),active.insert(&conn))Repo::<E>::scoped(action)with its own methods, then.all(); an ability-less readRepo::unscoped, an insertCreatable::create_from_activeorRepo::insert_unscoped(active).all(&conn),.one(&conn),.count(&conn),.exists(&conn)onRepo::scoped,with_tombstones,unscoped,unscoped_by_id.all(),.one(),.count(),.exists(): aRepoSelect<E>runs on the ambient executoruse sea_orm::{QueryFilter, QueryOrder, QuerySelect}for aReposelectdelete the import: filter,order_by,order_by_asc,order_by_desc,order_by_with_nulls,limit,offsetandapply_ifareRepoSelect<E>’s own.query(),.as_query(),.into_query(),select_only,column,column_as,expr_as,group_by,having,distinct,joinor alock_*method on aReposelectgone: narrow with the select’s own methods, and read a related row through its own service’s loader, under its own filter an expression as a Reposelect’s order key (.order_by_asc(Expr::col(…)))a column of the entity; an order by anything else is not offered in 7.0 raw text in a service’s condition: Expr::custand itscust_with_*,custom_keyword,Expr::Custom,Expr::CustomWithExpr,Keyword::Custom,Func::cust,cast_as,as_enum,Expr::AsEnum,Expr::Constant,sea_query::Enum,OptionEnum::None,ArrayType::Enum,BinOper::Custom,PgFunc::json_exists,json_value,json_query,json_table,Order::Field,OnConflict::constraint,order_by_customs,partition_by_customsea-query’s typed builders ( Func::lower,PgFunc::to_tsquery,Condition), their values bound; where only raw text can say it, a JSON path among it,#[expect(clippy::disallowed_methods, reason = "…")], once your project has theclippy.tomlnestrs newwrites, and an empty one incrates/migrations, where raw DDL stays free#[sea_orm(select_as = …, save_as = …, save_array_as = …)]on an entity, under thatclippy.tomlthe derive expands to cast_asbeside the struct, so the#[expect]goes on the module holding the entity:#![expect(clippy::disallowed_methods, reason = "…")]at the top of its file#[derive(DeriveActiveEnum)]withdb_type = "Enum"and nors_type, under thatclippy.tomlrs_type = "String", which expands to nothing the list names; or#![expect(clippy::disallowed_methods, clippy::disallowed_types, reason = "…")]on its moduleRepo::insert_unscoped(active, &conn),resolve_unique_slug(&conn, column, …)Repo::insert_unscoped(active),resolve_unique_slug::<E>(column, …)a secret column typed as a newtype with a hand-written Debug(PasswordHash), and animpl Debug for Model/ModelExrestating every column to hide itpub password_hash: Option<Secret<String>>and#[derive(Clone, Debug, DeriveEntityModel)]; the service readshash.expose_secret()#[expose]on a secret columnrefused at compile time: drop the #[expose]— aSecretnever crosses the wirea row or a struct serialized with its secret and read back (a cache, a payload) a Secretserializes as"<redacted>": store the value itself, read throughexpose_secret(), where you mean to keep itnest_rs::seaorm::Executor,LazyTransaction,FinalizeOutcomenothing: the edge’s unit installs and settles the handle, and Reporeads itExecutor::Txn(txn), a transaction you opened and installedan atomic block, nest_rs::database::atomic(work), for aRepowrite; adb.begin()of your own runs its statements ontxn, whichReponever joins, and commits out of the framework’s sightCommitError, and itsis_retryable_conflict()nest_rs::seaorm::retry::is_retryable_conflict(&err)on theDbErrof acommit()of your own, orRepoError::SerializationFailure(_)on whatretry_on_conflictanswersnest_rs::seaorm::{with_request_executor, with_job_executor}(executor, fut);nest_rs::seaorm::with_executorornest_rs::database::with_executorno public function installs an executor of its own: the edge’s unit runs the body, and a service test runs it through app.unit(ability, || …)orapp.system_unit(|| …)nest_rs::seaorm::{current_executor, ExecutorScope, current_executor_scope}nest_rs::database::{ExecutorScope, current_executor_scope}; a statement of a service’s own goes throughRepoUnhonoured { reason, retryable },JobTimedOut { timeout }Unhonoured::new(reason, retryable)(or::retryable,::deterministic),JobTimedOut::new(timeout)a service catching a unique violation on the request’s transaction and querying on an insert that may meet the row holding its key: Repo::<E>::insert_unscoped_or_existing(active, [key]), which answersInsertion::NeworInsertion::Existingand aborts nothing; any other statement: run it innest_rs::database::atomicand matchRepoError::UniqueViolation(_)matches!(err.sql_err(), Some(SqlErr::UniqueConstraintViolation(_)))to tell a taken keymatches!(err, RepoError::UniqueViolation(key) if key.constraint() == Some("users_email_key"))fn soft_delete_column() -> Option<Column> { Some(Column::DeletedAt) }on aCrudServicedelete it: #[expose(..., soft_delete)]alone stamps and hides.filter(live_condition::<E>())after aReporead,CrudService::live_read_filter(),audit_soft_delete_bindings()delete them: every Reporead carries the condition;live_condition::<E>()stays for a query outsideRepoa Reporead meant to see deleted rows (admin, retention)Repo::<E>::with_tombstones(action)a restore through Repo::update(clearingdeleted_at)not offered in 7.0: updatehides the rowimpl SoftDeletable for Entityby hand#[expose(..., soft_delete)]on the entitya create handler or service method stamping the tenant or the author ( active.org_id = Set(auth.org_id),create_in_org), and the#[crud]op it overrodea Creategrant pinning the column —.when(|p| p.eq(Column::OrgId, actor.org_id))— and#[crud]’s generated create, orCreatable::create; the author is aCreategrant of its own, for a subject that can authoractive.status = Set(Draft)before a create#[expose(default = Status::Draft)]on the column, which the create input does not carryid: Set(Uuid::now_v7()),created_at: Set(now)on a row built forRepo::insert_unscoped..Default::default(): the insert fills the key on an exposed entity, andcreated_atundertimestamps; a table no transport exposes takesDEFAULT uuidv7()on its key in its migration#[expose(..., timestamps)]on an entity withcreated_atand noupdated_at, refusedaccepted: updated_atis stamped when the entity has onea unique column on a soft_deletetable,unique_key()a partial unique index, … WHERE deleted_at IS NULLparams.after_uuid()params.cursor().map_err(|refused| nest_rs::http::pipe_error(&refused))?Page::next_cursor: Option<Uuid>;Repo::page,Repo::relation_pages,CrudService::page,RelationKey::aftertakingOption<Uuid>Option<PageCursor>:PageCursor::from(uuid)builds one,cursor.to_string()is its texta Page { items, next_cursor, has_more }literalPage::new(items, next_cursor, has_more)SeaOrmHealthModuleinimports;nest_rs::seaorm::SeaOrmHealthIndicatornamed in codedelete both: SeaOrmModuleattaches the pool’s indicator, andHealthModulechecks every resource the app or its features openeda hand-written #[readiness] async fn redis(&self)sendingPINGover an injectedRedisConnectiondelete it: RedisModuleattaches each instance’sPING— a method namedredisbeside it fails the bootreport.details.keys().copied()as&'static str;IndicatorReport { name: "x", .. }&Cow<'static, str>keys;name: "x".into()Readiness waits on every resource the app opens. 6.x checked the pool only beside
SeaOrmHealthModule, and no Valkey or store; an app importingHealthModulenow answers/health/readyand/health/startup503while its own or a feature’s database, any Valkey instance or the store is down, so the orchestrator takes the replica out of rotation until it is back. Each of those probes sendsSELECT 1, aPINGper instance and one page of the bucket’s listing — a request a store billing per request bills.A GraphQL operation is a unit of work, and each mutation root field a savepoint settled on the answer that field gives: a failed nullable root field answers
nulland rolls back alone; a Non-Null root field’snullreachingdatarolls the whole operation back and runs no later root field; a mutation naming one root field twice runs it once, its copies merged, and one naming it twice with different arguments is refused. ReturnResult<Option<T>>from a mutation whose work must stand beside a sibling’s failure, and put the writes that stand or fall together in one field. A batch’s operations no longer share one transaction. A driver whose executor offers no atomic block answers every GraphQL mutationINTERNAL. -
Follow each edge’s own moves: storage, GraphQL, WebSocket and MCP.
6.x 7.0 Storage::new(Arc::new(config))Storage::connect(&config).await?, which opens and proves the storestorage.bucket_name()storage.url(), the URL shown without credentialsStorageConfig { bucket: "media".into(), endpoint: "https://…".into(), .. }StorageConfig { url: "s3://media".into(), endpoint: Some("https://…".into()), .. };endpoint: Noneis AWSstorage.list(prefix)?storage.list(prefix), the stream itselfStorageError::Get(e)and its siblings,eanobject_store::ErrorStorageError::Get { store, source }, whosesourcesays the failure by its kind and holds noobject_store::Error:error_messagereads itmatches!(e, object_store::Error::NotFound { .. })on a downloadmatches!(e, StorageError::NotFound { .. }), noobject_storein your manifesta line on nest_rs::storagefiltered by itskeyfieldthe field is gone: each names its store, andtrace_idthe callStorageError::Presign { method: String, .. }methodis anhttp::MethodObjectMetadata { byte_size }/ObjectEntry { .. }built by handboth are #[non_exhaustive]: read them, never build them;byte_sizeisu64let url: String = storage.presign_put(&key, ttl).await?let put = storage.presign_put(&key, &SignedPut::new("audio/mpeg"), ttl).await?, then hand the clientput.url,put.methodandput.headers, which it sends verbatimlet url: String = storage.presign_get(&key, ttl).await?storage.presign_get(&key, ttl).await?.urla presign ttlpast 7 days, or under 1 seconda ttlwithin SigV4’s bounds: anything else isStorageError::Unsignablekeeping the content type supplied at upload, since headcould not read itstorage.head(&key).await?.and_then(|meta| meta.content_type)Scoped::<T>::from_context(ctx)?in a resolver, a message or a tool bodya cache: Scoped<T>parameter on the method; a miss is answered opaquely and filedctx.data::<DataLoader<L>>()?orctx.data_unchecked::<DataLoader<L>>()in a resolvera loader: &DataLoader<L>parameter, on a root field as on a#[field_resolver], which the boot checksa #[field_resolver]’s&DataLoader<L>parameter,LaLoaderwritten by hand and seeded throughGraphqlContextSeedLas a method of a#[dataloader]impl block, the parameter naming the loader it generates; or actx: &Context<'_>parameter andctx.data::<DataLoader<L>>()?, which the boot does not checka tokio::sync::broadcastprovider, and a#[listeners]host feeding it, behind a#[subscription]#[inject] bus: Arc<EventBus>andself.bus.stream::<E>(), fromnest_rs::events; a subscription needing noErrreturns the bareimpl Streamnest_rs::ws::WsScopeErrornothing #[query]+#[graphql(entity)]#[entity], withGraphqlConfig::federationGraphqlContextSeed { owner_type_id: || Some(TypeId::of::<R>()), lifetime, seed }GraphqlContextSeed::new(Some(TypeId::of::<R>), lifetime, seed)ErrorReport(error).into_frame(event)Err(error)returned from the#[subscribe_message]handler: its frame is rendered by the error’s typeimpl Gateway for X { async fn dispatch(..) }written by hand#[subscribe_message]methods in a#[messages]block:#[messages]alone writes aGatewayWsReply::unknown(event)WsReply::unknown()WsReply::payload_error(event, &error)with anyDisplaythe same with any Into<DecodeError>— aserde_json::Erroramong them — reported without the valueWsError::with_details(message, map); the class read offWsError::errorsWsError::new(message).with_errors(map)for a field map; the class atframe.code(andreason,required_scopes,retry_after_secs); a class from aProblem,WsError::from_problemrefused.origin(),refused.expected()on anOriginRefusednothing public: the surface files each refused origin itself, at warnServerInfo, returned by a host’sget_infonest_rs::mcp::ServerConfigrmcp’s Parameters, named from rmcp in an operation’s signaturenest_rs::mcp::Parameters, the framework’s own type with rmcp’s shapean impl McpHostwritten by handthe same with negotiate_initializeMcpIdentity::declared(name, title)#[mcp(name = …, title = …)], or the app’s ownMcpIdentityliteralMcpIdentity::new("assistant", env!("CARGO_PKG_VERSION"))inMcpOptions::serverMcpModule::for_root(McpIdentity { title: Some(…), ..Default::default() }), or the bare import: the name, version and description are the binary’s; itsnameandversionfields report othersMcpIdentity::new(name, version).title(…).instructions(…), any settera literal over Default:McpIdentity { name: Some(…), version: Some(…), title: Some(…), instructions: Some(…), ..Default::default() }McpIdentity::is_empty()== McpIdentity::default(): its fields are publicnest_rs::mcp::{tool, tool_router, tool_handler, prompt, prompt_router, prompt_handler, schemars, ToolRouter, PromptRouter}in a host writingServerHandlerby hand,nest_rs::mcp::{handler, transport, LocalSessionManager, StreamableHttpServerConfig, StreamableHttpService}nest_rs::mcp::rmcp::…:nest_rs::mcpkeeps rmcp whole there, and#[tools]needs none of themnest_rs::mcp::{CallToolResult, ContentBlock, ServerCapabilities, ProtocolVersion}nest_rs::mcp::model::…nest_rs::http::Scoped,nest_rs::ws::Scoped,nest_rs::graphql::Scoped,nest_rs::mcp::Scopednest_rs::core::Scoped, whichnest_rs::preludenames: one type on every edgenest_rs::authz::masked_output_ambient,nest_rs::authz::graphql::masked_value_for,nest_rs::authz::mcp::masked_value_for,nest_rs::authz::ws::masked_reply_forin a body#[authorize(Action, Entity)], and the exposed type built from the row,User::from(&row), judged for the caller where it is builtnest_rs::http::RejectedCredential,nest_rs::http::RequestDeadlinenothing: authn’s guards write the first and the edge the second, and neither is a developer’s to name validator::ValidationErrorin acustom(function = …)rule, on avalidatorline of your manifestnest_rs::pipes::validator::ValidationError, and delete the line if nothing else names the crate.map_err(|e| problem_error(&e))?in an operation answeringMcpErrorreturn the ToProblemerror itself from an operation spelledResult<T, E>#[mcp] struct Host<T>,#[tools] impl<T> Host<T>a non-generic host type per instantiation nest_rs::mcp::McpMount,endpoint,resolve_operation_guardthe #[mcp]host; a request’s guards are the transport’sa suite calling nest_rs::testing::mcp::call_toolon a gated endpoint whose guard names no subjectcall_tool_statelessly, or have the guard name its caller: the handshake is otherwise refused403two #[mcp]hosts on one path declaring one prompt namerename one, or give each host its own path: the boot refuses the paira host serving resources by hand — #[tool_router]tools, aget_info,list_resources/read_resourceparsing its URIsits tools, prompts and resources under #[tools]:#[resources]lists,#[resource(template = "post://{id}")]reads,ida typed parameter, each beside#[authorize(…)]or#[public]a McpError::resource_not_found(…)built for a row the caller may not readOk(None)from the#[resource]method, answered Resource not found under theNOT_FOUNDclassa #[resource]reading one row withCrudService::access(&*self.svc, Action::Read, id)and a match overAccess#[authorize(Read, bind = PostsService)]and apost: Authorized<Read, PostEntity>parameter, noid: Uuid:Denied,Missingand an id no v7 answer Resource not found, and the body runs on the row alone#[public]on a message or an MCP operation behind an upgrade or an endpoint whose guards authenticate itnothing: the guards cover it, and the boot refuses a #[public]that could open nothing there.#[authorize(Action, Subject)]where it needs a gatea hand-written Posture::Gatedself-mount (declare_endpoint) with no guard, which served every caller after onewarnGlobalGuardscovering it, orPosture::Publicwhere it is open on purpose: the boot refuses it#[authorize(Action, Entity, unmasked)]on a message only because it returns a bare value or aResultbehind an alias#[authorize(Action, Entity)]: nothing reads the reply back, andunmaskedis refuseda #[prompt], or a#[tool]answeringContentBlockorInputRequiredResult, beside#[authorize(Action, Entity)]nothing: the posture stands as written, since no mask reads the answer back input: Valid<T>on a GraphQL argument, a WebSocket payload or a job;Parameters<Valid<T>>on MCP;nest_rs::mcp::Validinput: T,Parameters<T>: each edge validates what it decodesPiped<P, T>on a GraphQL argument, a WebSocket payload or a job,Parameters<Piped<P, T>>on MCP;nest_rs::mcp::PipedPiped<P>fromnest_rs::pipes, whose wire value is the pipe’sIn, boundPiped(value)An app-wide exception filter or
#[interceptor(stage = unit)]now also runs around a WebSocket frame no handler reads, an event none serves or a frame no envelope holds, as it runs around a route’s404;WsView::eventreads_OTHERthere. One assuming a handler stood behind every message narrows itself on that word. No compile error says so. -
Push through the queue’s type, on the port’s handle. A feature injects
Arc<nest_rs::queue::Jobs>, which the backend’s binding registers, where it injected the backend’s producer.push_to::<Q>(job)and the string-takingpush(name, job)are gone: a push names the queue’s#[queue]marker and answers with aPushReceiptnaming the job’s id;push_withtakesPushOptionsfor a delay or a unique key:crates/features/src/audio/service.rs queue: Arc<dyn JobProducer>,jobs: Arc<Jobs>,// …self.queue.push_to::<AudioQueue>(TranscodeCommand { file }).await?;self.jobs.push(AudioQueue, TranscodeCommand { file }).await?;The queue section lists every call a producer changes,
push_manyandpush_jsonincluded, under Your code.QueueNameis now the checked name a backend receives, so a queue’s type isQueue:<AudioQueue as QueueName>::NAMEbecomes<AudioQueue as Queue>::NAME. Apush_manythat fails after the backend accepted part of it answersQueueError::PartiallyQueued, carrying the receipts of the jobs already queued: a caller that retries the whole batch on any error leaves those out.A push inside a transaction is filed after its commit. On an app binding
seaormand a queue backend, a push in a mutating request, a GraphQL mutation, a message or an attempt is written into the transaction and filed once it commits — never lost, never left behind by a rollback. That table,nestrs_outbox, is the framework’s migration, created bynestrs g migration nestrs_outboxthennestrs run db up(orBox::new(nest_rs::seaorm::queue::OutboxMigration)in your migrator’smigrations()). An event whose listener pushed only to wait for the commit pushes in the service, inside the transaction. A push meeting a unique key another job holds answersOkand is dropped atinfoafter the commit, where it answeredUniqueKeyHeld. See Producing jobs. -
Check what each consumer declares. A
#[process]method compiles as it did, and these read differently now:retries = Nruns a failed attempt again after a backoff — one second after the first failure, doubling, at most five minutes — where 6.x ran it again at once. AProblemcarryingwith_retry_after(n)holds it back at leastnseconds when that is longer, stretched by up to a fifth, what it asks counted up to an hour, where 6.x read no such wait. See Retries and failure.- A job failing with a client’s error dead-letters at once. A
JobError::abort(…), or aServiceErroror aProblemwith a4xx, dead-letters on its first attempt, where 6.x retried it until the budget was spent; returnJobError::retrywhere a later attempt may succeed — a row the producer has not committed yet. - A delivery whose process died has a limit of its own. An OOM kill or a pod killed mid-job still spends no retry: the job runs again at the same attempt, as in 6.x. But a job whose deliveries end that way three times in a row is dead-lettered without running, where 6.x ran it again every time. See Crashes, and the stall limit.
- A job a newer release pushed is handed back, not failed. During a
rolling deploy, a 7.0 worker meeting a job sealed by a later wire format
runs nothing, spends no attempt and puts it back as stored, due a minute
later, with a
warn; 6.x failed such a job and spent its retries. A job still unread a day after its first hand-back — a rollout that stopped — is dead-lettered, naming both versions. - A job ends within its
timeout, ten minutes by default: a#[process],#[every],#[cron]or#[after]method running longer declarestimeout = "…"covering its longest run, up to"24h". An attempt past its timeout is cut and fails retryably; a job whose commit does not answer within the database’s statement budget plus a second is dead-lettered rather than retried, since its writes may have landed. concurrency = Nis accepted again, per method and per replica, and so arethrottle(limit, window)and aCheckpoint<S>parameter; see Concurrency and scaling. A#[process]method may take anAttempt— the job’s id and attempt — beside its job.- The tenant travels with every job, like the actor: a tenant id threaded
by hand into every payload becomes
fn tenant_id(&self) -> Option<String>on the claims’PrincipalIdentity, read withnest_rs::core::current_tenant_id()in the service, in the request and in every job it pushes. - Delivery is at least once, so a handler stays idempotent. On Redis a job runs again only once a delivery’s lease lapses — its worker crashed, froze, or was cut off past the lease — and what the first delivery writes after that lands nowhere. See At least once, and the fence.
- A queue name is checked: 1 to 128 of
[A-Za-z0-9_.-]. A name holding:or whitespace no longer compiles, so that queue takes a new name, and its 6.x jobs are drained in step 18 under the old one.
A scheduled job that should fire on one replica rather than all of them can now say so with
replicas = "one", besideRedisScheduleModule: each occurrence fires once across the replicas, and a run that outlasts its period overlaps the next one, fired by another replica. A job is its crate, its type and its method, so renaming one of them starts a new job — two, for the rolling deploy that ships the rename — unlesskey = "…"pins the identity its boot line names. See Firing once across replicas.An event emitted inside a transaction waits for it.
EventBus::emitin a mutating request, a GraphQL mutation, a WebSocket message, an MCP operation, a queue attempt, a scheduled tick or a lifecycle hook runs its listeners once the transaction commits — outside it, each listener in a transaction of its own, under the emitter’s scope and ability — and never when it rolls back; 6.x ran them inline, inside it. A listener that relied on writing inside the emitter’s transaction now writes in its own, and code that opens a transaction itself emits after its own commit. See What waits for the commit.6.x 7.0 an #[on_event]method logging its own failure and returning()return Result<(), E>: the bus rolls the call back and reports the error with its chaina listener relying on its writes landing one statement at a time #[on_event(transactional = false)]a listener running past ten minutes #[on_event(timeout = "…")], at most"24h", or a queue job it pushesa cross-cutting concern around jobs written inside every #[process]methodan interceptor bound with #[use_interceptors]on the#[processor]block, readingQueueView(step 10)ListenerMethod::wire(container, bus)none: only the boot runs a discovered entry A GraphQL operation returning a bare value —
i32,Vec<T>, animpl Streamsubscription — now runs its resolver’s guards and the app-wide ones, where 6.x served it past a deny-all#[use_guards]. An operation that answered only because of that gap now needs the posture its guards ask for. An operation returning a renamedResult—use async_graphql::Result as GqlResult, or a type alias — is read as one, so its error is a field error where 6.x served it as data. -
Boot every app, and read its first lines. A 7.0 boot names what it cannot use rather than falling back in silence. No
nest_rs::configwarning means no variable under a namespace the app reads went unread, none sits in a.envfile beside a config the app pins in code, and none spells such a namespace with other separators, in another case or one misspelled segment away; a namespace nowhere near any the app reads is taken for another binary’s and stays silent, so check the names the app should read against the env-var reference. Every resource the framework opens is proved at boot, each attempt awarn: a Postgres not listening yet, starting or full is waited for within<PREFIX>_SEAORM__CONNECT_TIMEOUT_SECS, a refused login fails at once naming the host and the SQLSTATE; a bucket that does not exist fails the boot naming<PREFIX>_STORAGE__URL, a key the store rejects fails it naming the credential variables, and any other403, most often a policy refusing the listing, leaves onewarn. A deployed profile reaching a backend in plaintext off this machine is onewarnper opening and the connection opens all the same:Redis is reached in plaintext outside a dev profile,Postgres is reached in plaintext outside a dev profileanda signal is exported over plain HTTP outside a dev profile; writerediss://,sslmode=verify-fullorhttps://to close it. A provider declaring a#[liveness],#[readiness]or#[startup]indicator in an app that does not importHealthModuleis awarntoo —host not served: the health probes are not mounted, with the host, its module and the import that serves it, and so is a host seeded or registered by a hand-written module with nothing importing what its edge runs on —host not served: its edge's transport is not attached, with the host and the import — or an instance of a controller, gateway or MCP host, which those edges do not mount whatever is imported —host not served: its edge does not mount an instance, with the host and a hint to list it. A host the app links but never reaches — a scheduled method, a#[process]method, a listener, a lifecycle hook, a health indicator — is awarnnaming itscauseand the remedy when it is this app’s own code, and adebugline when it belongs to a dependency (cause="dependency"). A configuration refusal’s first line names the variable it refuses —invalid value for <PREFIX>_HTTP__PORT: …— and a validation failure lists each field beside its variable. The boot’s last line isapp readyatinfo, naming the addresses bound. An HTTP route no guard covers and no#[public]opens, which 6.x served after oneunguarded routes detectedwarning, now stops the boot naming every such route: bind a guard on its controller, the route or the app’s global pool, or mark it#[public]where it is open on purpose. A guard counts only if it identifies or authorizes, by itsphase(). A WebSocket message and an MCP operation take the same rule, and a#[public]message or MCP operation behind a guard that authenticates stops the boot, the word having nothing to open. -
Regenerate every client from the 7.0 document, and move what it read off the wire:
- Every problem document names its class in
code—INVALID_ARGUMENT,UNAUTHENTICATED,FORBIDDEN,INSUFFICIENT_SCOPE,NOT_FOUND,CONFLICT,RATE_LIMITED,UNAVAILABLE,INTERNALand the classes of405to426— and itstypeisabout:blank. An opaque5xxcarriescodeand nodetail, where it said"internal error"; read the code. On WebSocket, the class sits beside the field map:data.code,data.reason,data.requiredScopes,data.retryAfterSecondswhere they were underdata.errors, which is now the field map alone; on MCP, a pipe’s field map is undererror.data.errors, its class aterror.data.code; GraphQL readsextensions.code. - A GraphQL field error names a field as the schema spells it:
extensions.errors.orgId, where it readorg_id, at every depth, under the rename rule the input declares. HTTP, WebSocket and MCP keep the name serde reads. - A value that does not decode is answered naming where, never what was
sent:
query parameter `p`: …,form field `p`: …,JSON body at `p`: …, and the same place in a WebSocket frame, an MCP argument refusal and a job’s dead-letter reason. A client matching poem’s or serde’s sentence meets the framework’s. - A failed GraphQL field is present as
nullbeside its error, whosepathnames it; a Non-Null field’snullclimbs to its nearest nullable parent,dataitself from a root field. A client branching on a missing key readsnull. - A refusal never hands a client’s value back: a GraphQL error names the
argument and the type, an MCP
unknown tasknames no id. - A paginated
#[crud]list links its next page inLink: </posts?first=20&after=…>; rel="next"(RFC 8288), where 6.x sent the cursor alone inx-next-cursor; follow the link, or readafteroff its query. The last page has noLink. A stale or mangled cursor answers400(a field error on GraphQL) instead of the first page. - A
#[crud]update isPUT /{id}, where it wasPATCH. - A route’s document lists what its guards answer:
401and503on an authenticated route,403where an ability can refuse,429under a rate limit, andsecurityread off the guards. - A route’s default tag is its controller’s token —
posts, notPostsController— and a#[crud]route no longer takes its entity’s name (Post). A generator grouping by tag renames its classes or files; keep a name withtags("…"). - An
#[expose]d timestamp reads…Zat UTC, where an unmasked route wrote+00:00: one instant, now spelled as a masked route already spelled it. A client parsing RFC 3339 sees no change; one comparing strings does. - Sockets close by their standard: a frame past the cap closes
1009 Message Too Bigon a gateway and on graphql-ws, where it closed1011; an admitted upgrade an in-process test drives answers426; a handshake offering no graphql-ws subprotocol answers400naming the two it accepts. A WebSocket envelope is the object{ "event": …, "data": … }; an array is refused as no envelope. - The GraphQL path answers
405withAllow—POSTfor a plainGETwith the playground off,POST, GET, HEADfor another method — and a sub-path of it is404. - MCP: a session shared across principals answers
404, as does aDELETEof a session the endpoint does not hold; sessions stored before 7.0 are refused on restore, so their clients open new ones once; a body that is no JSON-RPC message answers400with-32700or-32600, where it answered415, a message carrying a strayresultorerror, or a repeatedid, among them; an unknown tool answers-32602underNOT_FOUND. A request naming no session that is noinitializeanswers400, where it answered422; a JSON-RPC response sent with no session answers400with-32600, where it was accepted202. A tool or prompt asking its client for input at2026-07-28answers anInputRequiredResult: the peer’selicitandcreate_messageare refused at that revision. - A token endpoint answers RFC 6749 §5.2’s JSON:
401 invalid_clientwith aBasicchallenge for a client refused over theAuthorizationheader,400 invalid_clientfor one that sent its credentials in the body or none,400 invalid_requestfor a request that does not parse, and400 invalid_grantfor a rejected password; a503authentication answer carriesRetry-After: 1at least.
- Every problem document names its class in
-
Update the deployment.
- HTTP has bounds of its own. A replica holds at most
<PREFIX>_HTTP__MAX_CONCURRENT_CONNECTIONSopen connections, 10 000 by default — WebSockets included: raise it, with the file limit (ulimit -n), for a replica holding more, and keep it at or above a proxy’s upstream cap. An HTTP/2 connection runs at most 200 streams and a header list of at most 16 KiB; on HTTP/1, a head past 64 KiB answers431. A connection that sends no complete head within<PREFIX>_HTTP__HEADER_READ_TIMEOUT_SECS(30 s) is closed; a kept-alive one idle past<PREFIX>_HTTP__IDLE_TIMEOUT_SECS(75 s) is closed — behind a load balancer whose backend keep-alive is longer (Google Cloud’s is 600 s), set it above the balancer’s (620), or the balancer reuses a connection as it closes and answers502; a peer that stops reading is dropped after<PREFIX>_HTTP__SEND_TIMEOUT_SECS(60 s). - A request runs 20 seconds by default, down from 30
(
<PREFIX>_HTTP__REQUEST_TIMEOUT_SECS), counted from its arrival, its body’s reading included; a body that stops arriving answers408after<PREFIX>_HTTP__BODY_READ_TIMEOUT_SECS(10 s), or that budget’s503when it stops within the budget’s last gap. A WebSocket message and an MCP operation are cut at 20 s too (<PREFIX>_WS__MESSAGE_TIMEOUT_SECS,<PREFIX>_MCP__OPERATION_TIMEOUT_SECS), and a WebSocket connection hook has<PREFIX>_WS__CONNECT_TIMEOUT_SECSandDISCONNECT_TIMEOUT_SECS. Handlers longer than 20 s raise their timeout, the window and the pod’s grace period together. A Redis budget, a statement bound or a storage operation set at 18 s or more under an authentication guard, a queue or a rate limiter is refused at boot: keep it under the 18-second net. - MCP sessions are capped: 1 024 per endpoint
(
<PREFIX>_MCP__MAX_CONCURRENT_SESSIONS, about 110 KiB each), idling out after<PREFIX>_MCP__SESSION_IDLE_TIMEOUT_SECS(five minutes) unused — what the server writes to a session no stream carries is no use, a call waiting on its answer is; a session is served to the principal that opened it alone, and a principal naming no subject opens none on a gated endpoint (initializeanswered403). The graphql-ws socket waits 3 s forconnection_init(<PREFIX>_GRAPHQL__CONNECTION_INIT_TIMEOUT_SECS, up to 60, for a client fetching a token first), and caps a message at 64 KiB and a socket at 100 operations (<PREFIX>_GRAPHQL__MAX_MESSAGE_BYTES,<PREFIX>_GRAPHQL__MAX_SOCKET_OPERATIONS). - A socket pings a silent peer: a gateway’s and a graphql-ws one send a
Ping once the peer has sent nothing for 20 s, and drop a peer that sends
nothing back within 20 s more (
<PREFIX>_WS__PING_INTERVAL_SECS,PING_TIMEOUT_SECS, and the same under<PREFIX>_GRAPHQL__). Every client answers a Ping as it reads, a browser included; a client that holds a socket without reading it turns the Pings off with0. An MCP session’s client holding its stream is sent MCP’spingon it the same way, its session closed when nothing comes back (<PREFIX>_MCP__PING_INTERVAL_SECS,PING_TIMEOUT_SECS). - A browser’s
Originis checked at both WebSocket upgrades and at/mcp, CORS on or off: a browser app on another origin is listed in<PREFIX>_HTTP__CORS_ORIGINS, and behind a proxy that terminates TLS or rewritesHost, a same-origin browser is refused until the proxy is listed in<PREFIX>_HTTP__TRUSTED_PROXIESand sendsForwardedorX-Forwarded-ProtoandX-Forwarded-Host. With CORS origins set, the server’s own origin is listed too. A*admits every origin; the list is read as origins, sonull, a path, a trailing/or a Unicode host fails the boot at that entry — write the ASCII form,https://xn--9ca.example. - Server-Timing is off outside development and test: a staging dashboard or a
synthetic check reading it sets
<PREFIX>_SERVER_TIMING__ENABLED=true. - OAuth and OpenTelemetry follow the outbound policy: every
<PREFIX>_OAUTH__CLIENT__*_URLof a provider ishttps, andREDIRECT_URLhttps— loopbackhttpin a declared development or test profile alone; a provider or anhttps://collector signed by a private authority is trusted through<PREFIX>_OAUTH__CLIENT__TLS_CA_CERTor the fileOTEL_EXPORTER_OTLP_CERTIFICATEnames. A flow begun before the deploy that renames the OAuth transaction cookie to__Host-oauth_txfails its callback once; the user signs in again. - KEDA reads the stream’s length now: a
redis-streamstrigger onnestrs:queue:{<queue>}:jobs, withstreamLengthwhere a list trigger hadlistLength, counting the jobs waiting and running. A trigger naming the 6.x list reads zero forever. KeepminReplicaCount: 1on a queue that takes delayed pushes or retries — they wait off the stream, and only a running worker files them back; see On queue depth, with KEDA. - An ACL confined to the framework’s prefix now runs every Redis binding,
and each page gives its rule whole — the commands a binding sends, those
inside its Lua scripts included, since Redis checks them against the
caller’s ACL as well: the queue
under
~nestrs:queue:*, the rate limiter under~nestrs:throttler:*and a schedule’s claims under~nestrs:schedule:*; an app running several gives one user each rule. A dashboard or an ACL written for the rate limiter’s 6.x keys follows it tonestrs:throttler:buckets:*. - The rate limiter on Redis counts each bucket under a pseudonym keyed by
<PREFIX>_THROTTLER__PSEUDONYM_KEY: set it, the same 32 bytes or more on every replica, or the boot refuses. 6.x’s buckets, named by the client’s address, expire with their window; see Redis, shipped. - TLS:
rediss://is verified against the URL’s host, and a Valkey whose certificate chains to an authority only Mozilla’s roots held needs it in the system’s store or in<PREFIX>_REDIS__TLS_CA_CERT;TLS_CERTandTLS_KEYname a client certificate, each with its_FILEform, and#insecurefails the boot — see the Redis variables. Postgres connects withsslmode=verify-fullunlesssslmode=disablein the URL, or libpq’sPGSSLMODE=disablebeside a URL naming no mode, turns it off:allow,prefer,requireandverify-cafail the boot, namingPGSSLMODEwhere it set one, and a server without TLS needs one of those two written. An authority named in libpq’sPGSSLROOTCERT, which 6.x read, is read as libpq reads it — the root of verification beside a URL naming nosslrootcert— so a server only the system’s store vouches for fails the boot, and a certificate file one of them names that cannot be read fails it at once, naming where it is set. - Shutdown ends within bounds you can read. HTTP stops waiting for open
connections once
<PREFIX>_HTTP__SHUTDOWN_TIMEOUT_SECSruns out, 20 seconds by default, where 6.x waited for every one: a request still running is dropped unanswered and a download is cut, while a stream with no end of its own — an#[sse]stream, an MCP session’sGETstream — ends at the signal, a gateway’s WebSocket closes with1001 Going Awayafter the message it is answering, and a graphql-ws socket completes each subscription, then closes the same way. A socket a hand-built self-mount upgraded ends with its handler or the process; half a second more lets what it stopped unwind. The worker hands back what still runs before its drain window closes — 20 by default, down from 30, read from<PREFIX>_QUEUE__SHUTDOWN_TIMEOUT_SECSwhere 6.x read<PREFIX>_REDIS__WORKER__SHUTDOWN_TIMEOUT_SECS: the window is the queue port’s now, so it survives a backend swap. A running attempt gets all of it but a reserve of one connection budget, so 10 seconds by default to finish where 6.x let it run the whole 30. A scheduled tick still running gets 5 seconds and is then stopped. The shutdown hooks —OnModuleDestroy,BeforeApplicationShutdown,OnApplicationShutdown— then share one 5-second budget, OpenTelemetry’s final flush takes 3 seconds at most, and the console’s 1: 29.5 seconds, inside the 30 Kubernetes grants by default. A window you widen — HTTP’s or the worker’s — needsterminationGracePeriodSecondsat least 9.5 seconds above it plus anypreStopdelay, which Kubernetes counts inside the grace; a worker pod you gave 45 seconds for the old 30-second drain can keep its drain and its grace, or drop both to the defaults. See the way down. - Deregistration is the platform’s: on Kubernetes, give each serving
container a
preStophook with thesleepaction (Kubernetes 1.30 or later) and raise its grace by as much, since the HTTP transport stops accepting at the signal and Kubernetes removes the endpoint at the same time. See leaving the load balancer first. - Operation lines say how each unit ended. A request dropped at the
window, or by a client that reset its connection, files its
http.requestline withoutcome="cancelled"and nostatusorbytes, a handler that panicsoutcome="panic"withstatus=500, and a stream ended at the signaloutcome="cancelled"beside itsstatus; every other edge files both words too, and an MCP tool that answeredisError: truefilesoutcome="error". The request line names itspathtemplate (/posts/{id}), not the path; a method outside RFC 9110’s is_OTHER; a WebSocket event no handler serves is_OTHER;user_agent,operation_nameand an MCP operation’s name moved to the spans (user_agent.original,graphql.operation.name,mcp.operation.name). A root field filesgraphql.field, an operationgraphql.operation, a lifecycle hooklifecycle.hook. A5xxis filed once, by the edge:service error surfaced as 500andtoken request failedreadrequest failed/request unavailableonnest_rs::http, a handler’s503atwarn. See the table in Logs. - A span says
Errorfor the server’s own failure alone. Aws.message, agraphql.operation, agraphql.fieldand agraphql.subscriptionrecord noerror.typeand no status for a failure their caller earned, as an HTTP4xxdoes not; their line still filesoutcome="error". An alert counting those spans inErrorreads the server’s failures alone, and one meant to count every failure reads the line. No compile error says so. - A library’s own lines are clamped. rmcp’s, h2’s, rustls’s,
tungstenite’s, sqlx-postgres’s and the OTLP exporter’s lines are written
only once
RUST_LOGnames the library (info,rmcp=info), and that directive writes what the library quotes; see the libraries the framework wires. - Every duration has a range, checked at boot whether it comes from the
environment or is pinned in code, and a value outside it fails the boot
naming the variable — the env-var reference
gives each one. Where
0is off it still is; in code, off isNone, and a pinnedSome(Duration::ZERO)fails the boot. A value 6.x accepted — a worker drain window of0or above an hour, a zero connect timeout or window, a token lifetime past thirty days, a connection ceiling past a day — has to move. - Every app that authenticates names its issuer and its audience:
<PREFIX>_AUTHN__ISSUER, the issuer its tokens name, and<PREFIX>_AUTHN__AUDIENCE, its own canonical URI — an app that mints and verifies its own tokens names its origin as both. A resource server underOAuthResourceModulereads both off its resource and sets neither, but names itsISSUERwhen it mints access tokens too. A scaffolded app holds them inapps/<app>/.envfor the development and test profiles alone: add<PREFIX>_AUTHN__ISSUER=http://localhost:<port>and<PREFIX>_AUTHN__AUDIENCE=http://localhost:<port>beside an app’s port when it was scaffolded before 7.0, andclient_id: "dev-token".to_owned()to the claims its/auth/dev-tokenroute builds. - Valkey 9.1, on one server, Sentinel or Cluster — Redis is no longer a
supported server, and the scheme of
<PREFIX>_REDIS__URLdeclares the topology:rediss://,rediss-sentinel://orrediss-cluster://(see Valkey topologies). Runnoevictionon a server holding the rate limiter or the schedule, whose keys carry an expiry; a server holding the queue alone may run avolatile-*policy, neverallkeys-*, which can evict a job — see Eviction.
- HTTP has bounds of its own. A replica holds at most
-
Drain each Redis queue’s 6.x jobs. 6.x kept a queue’s jobs at the root of the keyspace; 7.0 keeps them on a stream under
nestrs:queue:{<queue>}and reads nothing 6.x left, so keep the 6.x workers running until those keys are empty — Upgrading queues from 6.x.
What fails if you get it wrong
Section titled “What fails if you get it wrong”-
A GraphQL client leaving a required variable out,
$id: ID!with no default, readsVariable "$id" of required type "ID!" was not provided., and the operation runs nothing: it used to run,@skip(if: $x)keeping its selection,@include(if: $x)dropping it, and an argument’s root field alone failing. Send the variable, or declare it a default. A client relying on@skipor@includeignoring a default now reads what its document says. -
A GraphQL client sending
nullfor a variable its type declares Non-Null,$hint: String!sentnull, or[1, null]for$ids: [ID!], readsVariable "$hint" of non-null type "String!" must not be null.(or… must not hold null at "ids[1]".), and the operation runs nothing: a nullable argument read thenull, and a mutation ran its root fields. Declare the variable nullable, or send a value. -
A GraphQL object with no key to answer reads
{}, where it readnull:{ org { name @skip(if: true) } }, or a type condition applying to nothing the value is,{ node { ... on Post { title } } }over aComment. An object selected twice at one place,{ org { name @skip(if: true) } org { id } }or two copies one of whose every field failed, reads what each copy selects, where whichever finished first hid the other. A client reading thatnullas “no object” reads the value’sNonealone now. -
A GraphQL document selecting a list of lists twice at one place with different selections,
{ grid { a } grid { b } }withgrid: [[Cell!]!]!, or two fragments each selectinggridotherwise, answers each cell’saandb, where it answered one copy’s cells and lost the other’s. -
A GraphQL type condition on a union spread where a member of it is resolved,
{ user { ... on SearchResult { ... on User { name } } } }withSearchResulta union holdingUser, answers the member’s fields, where it answered{}. Spread where a member is resolved among types the union does not hold, it is copied once per member, and nested deep enough readsQuery is too complex.once its copies would passmax_complexity. -
A GraphQL document selecting one key twice at one place with different fields or arguments under different type conditions,
{ a: user { id } ... on Query { a: org { id } } }, reads anINVALID_ARGUMENTrefusal at the copy that differs and runs nothing, where it answered both fields under one key. Give each copy its own alias. -
A GraphQL document selecting one key twice at one place in two shapes, whichever types its copies are selected on,
{ search { ... on User { x: name } ... on Org { x: size } } }withname: String!andsize: Int!, reads anINVALID_ARGUMENTrefusal,the operation selects "x" more than once at one place with different response shapes, at the copy that differs, and runs nothing, where it answered a string for one row and a number for the next. Give each copy its own alias. -
A GraphQL subscription whose root names other than one field — a second root field,
subscription { a b }, one twice, one through a fragment, or one under@skipor@include— reads anINVALID_ARGUMENTrefusal,the subscription selects "b" beside "a" at its root, and opens nothing, where it streamed each root field’s items beside the other’s, each copy’s twice, and nothing for a fragment (GraphQL §5.2.3.1). Open one subscription per root field, on one socket. -
A GraphQL document spreading its fragments again past
max_complexityreadsQuery is too complex.before anything walks it, a__typenameat the end of them included, which was answered; so does one whose arguments copy or scan more than twice what the request may carry,max_body_byteson aPOSTandmax_message_byteson a graphql-ws socket, a key repeated with thousands of arguments among them.max_complexity: Noneleaves a fragment’s repeats at ten million. Spread less, or raise the limit, which also holds a score under one that its repeats pass. -
A GraphQL subgraph whose guards identify no caller,
federation: trueunder a rate limit alone or no guard at all, fails the boot, where it served its SDL through_serviceto anyone. List a guard identifying the router, an authentication or authorization guard inGlobalGuardsor anEndpointGuards<GraphqlView, …>, or, for a subgraph only its router reaches on a private network, open it:federation_sdl: Surface::Open(<PREFIX>_GRAPHQL__FEDERATION_SDL=true). -
A GraphQL document whose fields below a list read more than 4 KiB of arguments, which each row reads again,
query($v: String) { rows { f(x: $v) } }with a large$v, readsQuery is too complex.and runs nothing, where every row copied the value. Read the value once, on a root field or one only objects stand above, or raisemax_list_argument_bytes(<PREFIX>_GRAPHQL__MAX_LIST_ARGUMENT_BYTES),Noneor0to turn it off. -
A GraphQL document holding a fragment no operation spreads reads
Fragment "F" is never usedfor the first in its text alone, where validation listed each beside the document’s other errors. It was refused either way. -
A
Datatype a resolver reads off itsContextand its request does not hold answers the opaque internal error, the type filed aterror, where the client readData `…` does not exist.A loader read so whose owner the app does not import moves to a&DataLoader<L>parameter, and its boot says which import. -
A guard declaring a status outside
400to599indenial_statusesrefuses the boot, naming the guard and the status: list what itsErrpaths answer, an error each. -
A
(StatusCode, Json<T>)route whoseThas no schema does not compile (E0277), as a bareJson<T>route does not: derive it with#[output]. -
A client generated from
/api-jsonreads2XXwhere it read200on a route whose status the handler computes, new responses on every operation, and a text or bytes body where it read none: a generated type naming200for one moves, or the route says#[http_code(200)]where its status never varies. -
McpSetup::from(x),StaticFilesSetup::from(x),OAuthResourceSetup::from(x), or.into()to one of them, does not compile (E0277): a setup has one way in, so writeMcpModule::for_root(x), which takes the same value. -
A lone Redis binding over a seeded
RedisConnectionnow reads theRedisConfigof the module it imports, so a suite with<PREFIX>_REDIS__URLunset is refused naming the variable: seed theRedisConfigbeside the connection. -
An import of
Scopedfrom an edge, of rmcp’s macros or types fromnest_rs::mcp’s root, anMcpIdentitysetter, ofwire_enumfromnest_rs::resource, or of an item through a modulenest_rs::coreornest_rs::socialno longer opens fails to compile (E0432,E0599): steps 5 and 12 list each with what replaces it.#[wire_enum(graphql)]or#[expose(..., graphql)]without thegraphqlfeature fails naming the feature to add. -
An
McpIdentitystating a name with no version behind it, or a version, a title, a description, a website or icons with no name behind them, refuses the boot in a process no#[nest_rs::main]started, naming the literal to write; the binary fills both anywhere else. -
A bare
#[interceptor], orstage = handler, does not compile:#[interceptor] declares what a module brings around the guards and takes `stage = unit`, then where the other goes.#[injectable]on the struct andGlobalInterceptors<(I,)>in the providers of the modulemainboots (step 10); one that must see a refusal or a404is#[interceptor(stage = unit)]. -
A type in a pool no decorator makes a provider does not compile:
`X` is not a provider a module or an app-wide pool can register, where the pool names it.#[injectable]on it, or aDiscoverableimpl. -
A singleton provider of the root injecting a layer only a pool lists fails the boot with
UnbuiltProviderError:only an app-wide pool's declaration lists it … list it in `AppModule`'s `providers`. A module injecting one fails the access graph, naming the root as the owner: list the layer in a module both reach. -
A pool naming a layer whose module the root does not import boots now, where it was refused: the pool registers the layer as the root’s, from what the root reaches. Import the module when you meant its provider and its configuration.
-
A suite calling
app.bearer(…)on an app booted without.ephemeral_signing_key()panics naming the builder call; 7.0’sbearersigns with a key of the test’s own, never the app’s. The key on an app that provides noJwtService, or one whoseJwtServicethe suite seeded, refuses the boot. -
A binary whose
maininstalls no exporter, run where the deployment setsOTEL_EXPORTER_OTLP_ENDPOINT(or a signal’s own endpoint) — a platform injecting it into every pod included — failsApp::runbefore serving, naming the variable and the line to add: 6.x booted it and exported nothing. Addlet _otel = OpenTelemetry::init()?;tomain, or setOTEL_SDK_DISABLED=truewhere that binary exports nothing. A suite, which boots withoutrun, is never refused. -
A
.envfile or a deployment still setting<PREFIX>_LOGfilters nothing: the console logs atinfo, or at whatRUST_LOGsays, and says once atwarnonnest_rs::appthat the variable is read by nothing (variable read by nothing since 7.0,read_asnamingRUST_LOG). Rename itRUST_LOG(step 3). -
nestrs g migration create_posts— orcreate_post— afternestrs g resource postswrites nothing:a migration creates the table `post` already: `crates/migrations/src/m…_create_posts.rs`. The resource wrote it; a change to the table takes a name of its own. -
nestrs g resource postsafternestrs g migration create_postswrites nothing either: the same sentence, then the two ways through — that migration removed with its two registrations, or the feature and its entity written alone. -
A deployment still setting
<PREFIX>_OPENTELEMETRY__*exports nothing through it:OpenTelemetry::initnames each such variable once atwarnonnest_rs::opentelemetry(variable read by nothing since 7.0,read_asnaming the specification’s variable that replaced it). Set theOTEL_*of step 3. AnOTEL_EXPORTER_OTLP_PROTOCOLother thanhttp/protobuffails the boot naming it. -
An
OTEL_TRACES_EXPORTER,OTEL_METRICS_EXPORTERorOTEL_LOGS_EXPORTERnaming an exporter nestrs does not build —console,zipkin,prometheus, a misspelling — failsOpenTelemetry::initwithinvalid value for OTEL_TRACES_EXPORTER: must name otlp, …, naming the variable and never its value; so dononebesideotlp,otlpnamed for a signal no endpoint reaches, and, in a binary built without theotlpfeature, any value butnone. 6.x read none of them: a deployment that set one for another service’s sake unsets it, or setsnone.noneandOTEL_SDK_DISABLED=trueare honoured, so a signal they switch off exports nothing, and the boot line saysoff (OTEL_TRACES_EXPORTER=none). -
An OpenTelemetry variable nestrs cannot honour fails
OpenTelemetry::initnaming it and never its value:OTEL_EXPORTER_OTLP_COMPRESSIONother thangzipornone(zstdincluded),OTEL_PROPAGATORSother thantracecontext,baggage(b3,jaeger,none, or one of the two alone),OTEL_TRACES_SAMPLERnaming a sampler the SDK does not build (xray,jaeger_remote, a name not in lowercase),OTEL_TRACES_SAMPLER_ARGoutside 0 to 1, anOTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCEother thancumulative,deltaorlowmemory, andOTEL_CONFIG_FILE. 6.x read none of them: unset it, or set what the sentence accepts. -
OTEL_EXPORTER_OTLP_HEADERSbeside anhttp://endpoint on another host fails the boot naming both variables, since the collector’s credential would cross the network in clear; so does such an endpoint carrying a query, naming the variable that set it. Export overhttps://, or to a collector on loopback (localhost,127.0.0.1,[::1]), which keeps receiving both, dialled past any proxy the environment names. -
A number the SDK reads that is not a whole number — an
OTEL_BSP_*orOTEL_BLRP_*setting (digits alone, as the SDK reads them), a span limit orOTEL_ATTRIBUTE_COUNT_LIMIT, an export timeout orOTEL_METRIC_EXPORT_INTERVAL— failsOpenTelemetry::initnaming the variable, where the SDK kept its default in silence. Write it in milliseconds, or as a count, or unset it. -
Userinfo in an OTLP endpoint (
https://key@collector:4318), which no request carries, fails the boot naming the variable or the pinnedotlp_endpoint, overhttps://and to loopback too: the collector never saw the credential, and answered 401. Move it toOTEL_EXPORTER_OTLP_HEADERS(authorization=Basic%20…). -
A query on
OTEL_EXPORTER_OTLP_ENDPOINT(or the pinnedotlp_endpoint) fails the boot naming it: the signal’s path landed inside the query, and the export at the collector’s root. Set each signal’s own endpoint with its query (OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, …), used as given, or move the parameter to a header. -
A headers pair the SDK dropped in silence — no
=, an empty key or value, a name no header may carry — fails the boot naming the variable; and a signal’s own headers variable set empty now reads as unset, so the generalOTEL_EXPORTER_OTLP_HEADERSreach that signal too, as the specification orders. -
OTEL_RESOURCE_ATTRIBUTESis percent-decoded, as the resource specification writes it: a%meant literally is written%25, and a member with no=, an empty key or an escape that does not decode fails the boot naming the variable, where the SDK dropped the member or exported the escape as written. -
A batch processor’s queue or batch size of
0, or a batch above its queue (OTEL_BSP_MAX_EXPORT_BATCH_SIZEaboveOTEL_BSP_MAX_QUEUE_SIZE, 2048 when unset; theOTEL_BLRP_*pair alike), fails the boot naming the variable: a queue of none dropped every span or log record, and the SDK lowered the batch to the queue in silence. Write a positive size, the batch at most the queue. -
An
OTEL_BSP_SCHEDULE_DELAYorOTEL_BLRP_SCHEDULE_DELAYof0, on which the SDK’s worker polled its channel without pause, a core per processor, or anOTEL_BSP_MAX_QUEUE_SIZEorOTEL_BLRP_MAX_QUEUE_SIZEabove 1,048,576, which the SDK allocates whole when the processor starts, fails the boot naming the variable, the queue’s sentence saying what the ceiling costs. Write a delay of 1 ms or more, and a queue within the ceiling. -
A zero export timeout is no limit now, as the specification reads it: the processor’s bound (
OTEL_BSP_EXPORT_TIMEOUT,OTEL_METRIC_EXPORT_TIMEOUT,OTEL_BLRP_EXPORT_TIMEOUT, 30 s by default) cuts the export, where a zero cut every export before it was sent. Both at zero fail the boot naming them: set one to a bound in milliseconds. -
A blank
OTEL_SERVICE_NAME, an empty or blankservice.nameinOTEL_RESOURCE_ATTRIBUTES, or an empty or blank pinnedservice_namefails the boot naming it, where the app exported under the blank name. Write the service’s name, or leave it unset for the binary’s. A binary built without theotlpfeature holds to it too, and fails on anOTEL_RESOURCE_ATTRIBUTESthat does not read. -
A filter on
an OpenTelemetry variable does not hold what it mustreadsan OpenTelemetry variable is passed overnow, itsexpectedfieldreason; it names, too, each specification variable this build serves nowhere (OTEL_LOG_LEVEL,OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT, …). -
A pipeline stripping colour escapes from a
textconsole finds none: the console colours a terminal alone, andNO_COLORoff one. -
A binary built without the
otlpfeature with an endpoint set —OTEL_EXPORTER_OTLP_ENDPOINT, a signal’s own, or a pinnedotlp_endpoint— fails the boot naming it and the feature, rather than export nothing in silence. Build it with the umbrella’sopentelemetryfeature, or switch the signal off (OTEL_TRACES_EXPORTER=none, orOTEL_SDK_DISABLED=true). -
A filter matching the boot line’s
traces=off (no endpoint)readstraces="off (no endpoint)"on a text console now; JSON is unchanged. -
A log setting pinned through
OpenTelemetry::init_with— alog_filter,log_formatorlog_source_locationin the config it takes — gives way toRUST_LOG,<PREFIX>_LOG_FORMATor<PREFIX>_LOG_SOURCE_LOCATIONwhere one is set, the.envcascade’s included, where 6.x kept the pin. Leave the variable unset where the pin must hold. -
A client comparing the OpenAPI document’s
inforeads the binary’s package name and version ininfo.titleandinfo.version, where 6.x publishednestrs APIand0.1.0; pin<PREFIX>_OPENAPI__TITLEandVERSIONto keep others. An MCP endpoint nobody named reports the binary’s name and version where it reportedrmcp’s. -
A hand-written
impl Configleft beside#[config]fails to compile,conflicting implementations of trait Config(E0119): delete it, or sayfrom_env = "manual". A field whose type no reader reads names the one it needs (Durationis read through its bounds,#[config(bounds = …)]), a field named for a unit (window_secs) names the field it should be, aDurationBounds::secsgiven a key and a path fails to compile (two arguments, not four), a range on a type no range holds names the five that are (Duration,Option<Duration>,usize,u32,Option<usize>), and a range of the other kind is refused at its name in the attribute,expected CountBounds, found DurationBounds. A#[config(count)]of a 6.x-style config fails to compile naming what replaced it,#[config(bounds = RANGE)]with aCountBoundson theOption<usize>;ConfigService::countis gone with it, and anOption<usize>pinned atSome(0)with its variable unset fails the boot: unlimited in code isNone. -
An associated constant of your own named for a field —
const PORTon a#[config]with a fieldport— fails to compile,duplicate definitions with name PORT:#[config]binds every field to the constant named for it. Rename yours. -
A count past its ceiling fails the boot naming the variable and the range, from the environment or pinned in code, never quoting the value: a deployment setting one past it has to move, or turn the limit off where
0does that.<PREFIX>_HTTP__MAX_BODY_BYTESruns to a tebibyte;<PREFIX>_MCP__MAX_REQUEST_BODY_BYTES,<PREFIX>_WS__MAX_MESSAGE_BYTESand<PREFIX>_GRAPHQL__MAX_MESSAGE_BYTESto a gibibyte;<PREFIX>_MCP__MAX_CONCURRENT_SESSIONSto 1048576, a million idle sessions holding over 100 GiB;<PREFIX>_GRAPHQL__MAX_DEPTHto 33, past which async-graphql’s own recursion bound refuses the document anyway;<PREFIX>_GRAPHQL__MAX_COMPLEXITYto ten million;<PREFIX>_GRAPHQL__MAX_BATCH_SIZEto 1024;<PREFIX>_GRAPHQL__MAX_SOCKET_OPERATIONSto ten thousand;<PREFIX>_GRAPHQL__MAX_REPRESENTATIONSto a hundred thousand;<PREFIX>_THROTTLER__LIMITto a billion, and at least1, where0used to boot and deny every request;<PREFIX>_SEAORM__MAX_CONNECTIONSandMIN_CONNECTIONSto 262143, Postgres’s own ceiling,MAX_CONNECTIONSat least1. -
<PREFIX>_SEAORM__MIN_CONNECTIONSaboveMAX_CONNECTIONSfails the boot naming both, where sqlx clamped it in silence and kept fewer idle than asked for. -
A deployment still setting
<PREFIX>_HTTP__CORS_MAX_AGEsends noAccess-Control-Max-Age: the boot says it atwarnas retired (variable read by nothing since 7.0),read_asnamingCORS_MAX_AGE_SECS. -
A deployment still setting a security header’s flat key (
<PREFIX>_HTTP__HSTS,<PREFIX>_HTTP__CONTENT_SECURITY_POLICY, …) fails the boot as retired, naming the key it became —<PREFIX>_HTTP__CONTENT_SECURITY_POLICY is read by nothing since 7.0 — set <PREFIX>_HTTP__SECURITY_HEADERS_CONTENT_SECURITY_POLICY: …: read by nothing, it would have left the header to its default, and aContent-Security-Policy,Permissions-PolicyorCross-Origin-Embedder-Policyit set not sent at all. One still settingCORS_EXPOSEDor the bareSECURITY_HEADERShas the default in its place — the exposed list empty, every default-on header sent, both more closed than what it set — and the boot says each atwarnas retired,read_asnamingCORS_EXPOSED_HEADERSandSECURITY_HEADERS_ENABLED. Move each to its row in step 3. -
ConfigModule::for_featureleft in an import list fails to compile; a config no provider of an imported module injects is no longer loaded — read it through a provider, or queue it from the module’scollect. -
X::for_root(None)left in an import list fails to compile —for_roottakes the value it pins,expected XConfig, found Option<_>— and so doesRedisModule::for_root((Cache, None)): write the bare import,XorRedisModule::<Cache>, which reads the same variables. -
ConfigModule::for_root()left in an import list fails to compile (no function or associated item named for_root): delete the line, nothing replaces it. A process declaring no<PREFIX>_ENVstill says so once atinfo, in every app that reads a config — appsnestrs newscaffolded included, which never said it in 6.x. An app that reads no config gets noEnvironment: a provider injecting it, or a test overriding it, is refused at boot naming the type — readEnvironment::from_env()there. -
async_traitorinputimported from an edge —nest_rs::http,ws,graphql,guards,queueormcp— fails to compile:Terminal window error[E0432]: unresolved import `nest_rs::http::async_trait`Import it from
nest_rs::core, its one path, or throughnest_rs::prelude::*;nest_rs::guards::preludeis gone the same way, andnest_rs::opentelemetry::LogFormatisnest_rs::core::logging::LogFormat. -
A provider still injecting
Arc<dyn JobProducer>fails the boot: no binding registers a backend’s contract any more, and the refusal names the handle to inject,Arc<nest_rs::queue::Jobs>. Apushstill passing a third argument,JobProducerExtimported, orpush_jsonfails to compile: the handle’spushtakes the marker and the job,push_withthe options too. -
McpOptions, orposture: Posture::InBandon it, fails to compile:McpModule::for_roottakes anMcpIdentity, anMcpAccessor anMcpConfig, alone or as a tuple, andMcpAccesshasPublicalone: a gated endpoint is the bare import,McpModule. -
A value breaking its type’s rules that 6.x let through, because no
Validwrapped its parameter, is now refused at the edge that decodes it:400 validation failedwith itserrorson HTTP, a field error underINVALID_ARGUMENTon GraphQL, an error frame on WebSockets,invalid_paramson MCP, and a job dead-lettered at once. A service that validated such an input itself no longer sees it, and itsServiceError::Validation, which 6.x answered422, answers400wherever it is still raised: one mistake, one status, whoever checks it.422staysServiceError::Invalid’s, a well-formed value the service refuses on business grounds. Keepvalidate()only where the service builds the input — from a provider’s profile, a seed. -
A
#[crud]block that leftcreateorupdateout, over a service that implementsCreatableorUpdatable, serves that write once its keys are dropped, with no compile error:POSTandPUTon a controller,createXandupdateXon a resolver, each behind the block’s guards and the caller’s grants. Listopswith the operations it served to keep the write closed. -
A
#[controller]or#[resolver]injecting one type in two fields fails to compile at the second field (`again` injects `UsersService`, which `svc` already injects): both held the one instance the container provides. Two fields spelling the type two ways (UsersServiceandusers::UsersService, or an alias), or under twocfgs that both hold, fail at the struct’s decorator with rustc’s E0119,conflicting implementations of trait …::Injects<UsersService>. Keep one field. -
A GraphQL
#[crud]resolver named apart from its wire type answers new field names with no compile error: the names come off the resolver’s name (AlbumsResolver→albums), where they came offoutput =(PagedAlbum→pagedAlbums), and a client asking the old field getsUnknown field. Name the resolver after its resource, or write the operation by hand under the name the client asks. -
A
#[crud]host named in the singular over a noun ending insreads its resource as that noun without thes:StatusResolverservesstatuandstatus, whereoutput = Statusgavestatusandstatuss, andStatusControllerdocumentsList Statu. Name the host in the plural, as a module is (StatusesResolver→status,statuss), or write the operation by hand under the name the client asks. -
A
Creategrant the create cannot complete — an org-wideManagethat lets a caller who authors nothing reach an insert whose author no grant pins — answers the insert’s NOT NULL violation as a500, filed aterroronnest_rs::orm. GrantCreateonly where the grants pin every column the server owns, andUpdateandDeletebeside it whereManagestood. -
An HTTP-only guard in the global pool whose decision moved into
checkruns it at every GraphQL field, WebSocket message and MCP operation too, whereHttpView::of(cx)?refuses each with the opaque500: the edge files every refusal aterror(guard denied …,status=500), itsguardfield naming the guard and itserrorchain the edit. Keep its decision incheck_httpand admit the units incheck(Ok(())). -
An
Ambient<T>no guard attached on a resolver, a message handler or a tool — the value an authentication guard attaches, read on an operation the guard never reached — answers the edge’s opaque internal error, and the type is filed once aterror(graphql operation failed,websocket message failed,mcp operation failed, itserrorfield naming the type). Attach it at the request —EndpointGuards<…>, the gateway’s guards — or on the operation. A principal a guard there produces, read on a#[public]operation by a caller it did not identify, is that caller’sUNAUTHENTICATEDinstead: readnest_rs::core::ambient::<P>()where the operation serves a visitor too. -
A global guard whose decision is a unit’s alone — a field’s, a message’s, an operation’s, written only in
check— now runs it on every request too: every route, the WebSocket upgrade and the/graphqland/mcprequests answer its refusal (a403, or the500of a guard reading a view the request does not have), filed once on the guard’s target. Admit the request in itscheck_http(Ok(())) where its decision is the unit’s alone, or write its decision so it holds for a request too. -
A domain error keeping its
ResponseErrorbeside itsToProblemfails to compile:Terminal window error[E0119]: conflicting implementations of trait `ResponseError` for type `PostError`Delete the
ResponseErrorimpl: theToProblemone answers on HTTP too, by?as from a route. A?on ananyhowerror or aStatusCodein a body answeringnest_rs::http::Result<T>fails to compile with E0277 (?couldn’t convert the error): write.opaque()?, orHttpError::from_status(status). -
A route 6.x served unguarded stops the boot:
Terminal window Error: routes no guard identifying a caller covers and none marks `#[public]`: POST /thing (create), GET /thing (read) — a route runs such a guard or is open on purpose; list `GlobalGuards<(...)>` in the providers of the module the app boots, bind `#[use_guards(...)]` on a controller or a gateway, `EndpointGuards<View, (...)>` on an endpoint carrying units, or open it on purpose: `#[public]` on a route, a message or a GraphQL operation, `McpModule::for_root(McpAccess::Public)` on an MCP endpoint. A guard that identifies no one, a rate limit or one of your own declaring no `phase()`, covers nothing: declare its `GuardPhase::Authentication` or `Authorization`, or write `#[public]`Bind a guard where the route should be closed, and write
#[public]where it is open on purpose. -
A route under a rate limit alone, or under a guard of your own declaring no
phase(), stops the boot the same way, as does a message under an upgrade running no other guard, an operation under such a/mcp, a hand-written MCP handler there and a gated self-mount:Edge What stops What boots HTTP #[use_guards(ThrottlerGuard)]orGlobalGuards<(ThrottlerGuard,)>and no posture#[public]on the route, or an authentication guard beside itWebSocket a message under ThrottlerGuardalone, at the upgrade or beside it#[public]on the message, or an authentication guard at the upgradeMCP an operation of a gated /mcpunderThrottlerGuardalone#[public], a guard of its own declaring its phase, or an authentication guard at the requestGraphQL nothing new: its posture is already mandatory — Write
GuardPhase::AuthenticationorAuthorizationon a guard of your own that does gate. -
A class gate no ability guard reaches stops the boot, on every edge, for
#[authorize]and#[public(Action, Subject)]alike. It answered500on every call:Terminal window Error: PostsController::list declares a class gate (`#[authorize]` or `#[public(Action, Subject)]`), and no guard in its chain or at its request attaches the ability the gate reads, so every call would answer `500`: bind `AbilityGuard` over your `AbilityFactory` with `#[use_guards]`, `GlobalGuards<(...)>` or, on an in-band endpoint, `EndpointGuards<View, (...)>`Bind
AuthzGuardwhere the message says. A guard of your own that delegated toAbilityGuardstops: listAuthzGuardin the chain beside it, the one guard the boot reads as attaching the ability. -
A gated unit whose
AuthzGuardsits at the unit alone — a resolver’s, a message’s, an MCP host’s — stops the boot, an opened MCP endpoint’s operations under the pool among them: an#[authorize]operation, message or tool, one stating no posture, and a#[field_resolver]of a resolver binding the guard. The guard builds an ability for a#[public]unit only; a gated one reads what its request attached, so every call answered401:Terminal window Error: query posts declares `#[authorize]`, and `AbilityGuard<AuthzAbility>` at the unit reads the ability its request attached, building one on a `#[public]` unit alone: no guard ahead of it or at its request attaches it, so every call would answer `401` — …Error: ShelvesResolver.label is gated by its guards alone, and `AbilityGuard<AuthzAbility>` at the unit reads the ability its request attached, …Bind
AuthzGuardat the request too:EndpointGuards<GraphqlView, (AuthnGuard, AuthzGuard)>orEndpointGuards<McpView, (…)>,GlobalGuards<(…)>, or the gateway’s#[use_guards]for a WebSocket message; or say#[public(Action, Subject)]where an#[authorize]unit serves a visitor. A field resolver reads what the/graphqlrequest attached, never what its root field built. At an endpointMcpAccess::Publicopens, whose request runs no guard, the refusal says so: declare the tool#[public], or#[public(Action, Subject)]to keep a gate, or stop opening the endpoint. -
An in-band chain listing authentication after authorization stops the boot, on a GraphQL field, a WS message and an MCP operation, reading its request’s chain ahead of its own. List the authentication guard first, or declare the phase of a guard of your own that attaches no principal as what it is.
-
A router answered
UNAUTHENTICATEDon_serviceor_entities: an anonymous caller no longer reads them under anAuthnGuard. Present a token._serviceruns the pool and now each guard ofEndpointGuards<GraphqlView, _>that identifies or authorizes a caller;_entitiesunderEndpointGuardsalone is still each#[entity]’s posture. -
A router answered
INTERNALon_service, withguard denied the federation fieldaterroronnest_rs::layers, itserrorchain namingcheck_http: a guard yourEndpointGuards<GraphqlView, _>lists declaresGuardPhase::AuthenticationorAuthorizationand reads the request incheck, which now runs there. Move the decision tocheck_http, and writeOk(())incheck(Federation). -
A
#[public]read answering nothing,200 []on HTTP and an empty value in band, withno ambient Ability outside a worker job — denying all rowsatwarnonnest_rs::orm: the unit names no read. Write#[public(Read, Entity)]:Edge Before After HTTP #[public],_authz: Authorize<Read, E>#[public(Read, E)]GraphQL #[public]#[public(Read, E)], each column a grant withholds#[expose(nullable)]or anOptionWebSocket #[public],#[use_guards(AuthzGuard)]#[public(Read, E)], the guard keptMCP #[public]on an opened/mcp#[public(Read, E)], each column a grant withholds#[expose(nullable)]or anOption -
Authorize<…>is not a handler parameter,E0277on a route keeping the parameter: the error names#[public(Action, Subject)]. -
A gateway or an MCP endpoint whose guards authenticate, still saying
#[public]on a message or an operation, stops the boot, naming the guard:Terminal window Error: the `nest_rs::ws::gateways` wiring failed: `#[public]` on history of the gateway at /ws can open nothing: its upgrade runs `AuthnGuard`, so a caller with no credential never reaches a message — drop `#[public]`, the guards covering a message deciding it (`#[authorize(Action, Subject)]` adds a gate), or take that guard off the upgrade to open the gatewayDrop the word; the guards cover the unit. Under the app’s pool the sentence says to move the guard from the pool onto the hosts it should cover, no gateway opening beneath it.
#[public]on a gated/mcpwith no guard at all stops it too, namingMcpModule::for_root(McpAccess::Public). -
A
#[public]dropped from a message no guard covers, or from an operation of an endpointMcpAccess::Publicopens, stops the boot, naming every such unit: keep the word where the gateway or the endpoint is open on purpose, or bind a guard. -
A gateway with no guard at its upgrade whose messages each bind their own, or one declaring hooks alone, stops the boot: any caller connects and its hooks run. Bind a guard on the gateway or the pool, or say
#[public]on the message open on purpose. -
A guard declaring
expected_principalbeside an authentication guard of your own that declares noproduced_principalstops the boot, naming both the guard and the type. Declare it on the guard attaching it, oror_visitor()where the guard does without. -
A client branching on
FORBIDDENfor a visitor’s call to a field whose guard reads the principal now readsUNAUTHENTICATED, the class a missing credential answers everywhere. On HTTP, a#[public]route with such a guard answers401, not500. -
A GraphQL client reading a
FORBIDDEN’sextensions.fieldsreads each as the schema spells it,workStatuswhere it readwork_status. A scalar’s keys stay what it reads in the scalar. -
A
#[field_resolver]answering an#[expose]d wire type, whatever holds its rows, readsnullin each column the caller’s.fieldsgrant withholds, where 6.x served it, and a row judged for another caller, or built where no ability is attached, answersINTERNALwith one line per operation, as a root and a relation do. A body reading a row out of a loader readsNonewhere the grant withholds a column: a loader answers judged rows. A#[field_resolver]whose parent answers no one — a row kept from another request, one the caller may not read — refuses before it runs,INTERNALorFORBIDDEN, where it derived a scalar from the parent’s columns. -
A subscription item that is a list keeps the rows that answer the subscriber, where it passed whole.
-
A WebSocket
#[on_connect]or#[on_disconnect]going throughRepofails closed, a read and a by-id write alike, andcurrent_ability()answersNonethere: no posture stands before a hook, so the ability the upgrade attached stays off its reads. The principal stays readable. Read what a client should see in a message whose posture names it; a hook’s system write isRepo::insert_unscoped, a visible line. -
use_guards_global,use_pipes_global,use_interceptors_globaloruse_exception_filters_globalleft inmainfails to compile (no method named use_guards_global found for struct AppBuilder): list the pool in the modulemainboots. Listed by a feature’s module instead, the boot refuses:Terminal window Error: the `GlobalGuards` wiring failed: `GlobalGuards<(TenantGuard,)>` is listed by `BillingHttpModule`, a module the app imports: the app-wide guard pool is declared by the module the app boots — list it in `ApiModule`'s providers -
A transient guard, pipe, interceptor or exception filter in the app’s pool booted in 6.x, built once and shared by every request. Its declaration now fails the boot, as a transient layer on a job does:
Terminal window Error: scope violation: `TenantGuard` is bound by `GlobalGuards<(TenantGuard,)>` (in module `ApiModule`), which resolves its layers once, at boot, and is request-scoped or transient — a request-scoped `TenantGuard` would never be built there, and a transient one would be built once and shared by every run. Make `TenantGuard` a singleton.Drop
scope = transientfrom its#[injectable]: the pool holds one instance either way. -
App::new::<M>()fails to compile: boot withApp::builder().module::<M>().build().await. -
An app’s suite pushing inside a unit no longer files the job on Redis: the harness armed the outbox, so the job waits in the test’s database until a relay the test spawns files it. A suite whose database lacks the outbox’s table now fails its boot naming
nestrs g migration nestrs_outbox, as the binary does. -
A variable kept under its 6.x name is read by nothing, and the boot says so once per variable, at
warn, before a missing required value stops it. The demo’sassistant, started with a 6.x.env:Terminal window WARN nest_rs::config: variable read by nothing since 7.0 variable="NESTRS_OAUTH_RESOURCE__AUTHORIZATION_SERVERS" namespace="oauth__resource" read_as="NESTRS_OAUTH__RESOURCE__AUTHORIZATION_SERVERS"WARN nest_rs::config: variable read by nothing since 7.0 variable="NESTRS_OAUTH_RESOURCE__RESOURCE" namespace="oauth__resource" read_as="NESTRS_OAUTH__RESOURCE__RESOURCE"WARN nest_rs::config: variable read by nothing since 7.0 variable="NESTRS_OAUTH_RESOURCE__SCOPES_SUPPORTED" namespace="oauth__resource" read_as="NESTRS_OAUTH__RESOURCE__SCOPES_SUPPORTED"Error: authentication failed: NESTRS_OAUTH__RESOURCE__RESOURCE (or NESTRS_OAUTH__RESOURCE__RESOURCE_FILE) must name this deployment's canonical URI (for example https://api.example.com)Rename what the
read_asnames, every row of step 3 said the same way. The report, and what it leaves silent, is described under Variables nothing reads. -
A module listing an edge’s host, in a binary not meant to serve that edge, now serves it, because the host brings what its edge runs on: a binary reaching a module that lists a controller listens on
<PREFIX>_HTTP__PORT, and one reaching a#[process]host with no queue backend bound fails the boot namingRedisQueueModule. Keep a host in its adapter (users/http/), never in the port (users/), and import the adapter only in the binary serving that edge. An app run with no transport at all filesapp serves nothing: no transport is attachedatwarnand stops once its init hooks ran, forStopCause::NoTransport, where it saidapp ready transports=""then drained forTransportFailed. -
An app importing
GraphqlModule,HealthModule,OpenApiModule,McpModule,StaticFilesModuleorOAuthResourceModulewithoutHttpModulenow serves HTTP: each imports it, so the binary listens on<PREFIX>_HTTP__PORT. A worker serving/healthwith no HTTP line of its own opens that port. -
A
.envkey beside a config the app pins in code reaches nothing — the pin takes its whole namespace off the cascade — and the boot names it once, atwarn, with the import that pinned it. An app still pinning its port:Terminal window WARN nest_rs::config: config variable from the .env cascade shadowed by a config pinned in code; export it into the real environment, or set it in the pin variable="NESTRS_HTTP__CORS_ORIGINS" namespace="http" pinned_by="`HttpModule::for_root(..)` at `imports[4]` of `ApiModule`"Pin nothing — drop the root’s
HttpModule::for_root(..), a listed controller bringsHttpModulebare — and write the port in the app’s ownapps/<app>/.env, or move the key’s value into the pin. -
The worker’s drain window kept under
<PREFIX>_REDIS__WORKER__SHUTDOWN_TIMEOUT_SECSis said retired atwarn,read_asnaming<PREFIX>_QUEUE__SHUTDOWN_TIMEOUT_SECS, by a boot reading the queue’s config, and the drain runs on whatfor_rootpins, or the default. -
A
redisrequirement of yours that excludes 1.8 —=1.7— fails to resolve beside the framework’s=1.8pin, cargo naming both requirements. -
A manifest naming a removed feature —
worker,interceptors,filters,exception-filters— fails to resolve, naming the featurenest-rsdoes not have; an import ofRedisQueueModuleunderredisalone fails to compile, its note naming thequeuefeature, whichredis-queueturns on. -
A process that declares no environment runs as production: its boot files
no environment declared; running as production, and each development convenience it relied on is refused naming its variable (<PREFIX>_STORAGE__ALLOW_HTTP, a loopbackhttpredirect or resource). -
A config still naming the second base fails to compile:
..T::defaults()has no such function,#[config(defaults = …)]is anunknown #[config] argument, afn defaults()in animpl Configis no member of the trait, and a surface written as aboolis a type mismatch againstSurface. Production’s behaviour does not move, but a pin over..Default::default()underdevelopmentortestnow keeps what the profile opens, so a suite asserting a surface closed there fails until it writesSurface::Closed. -
A program reading a log format back compiles and takes the other branch:
LogSettings::from_env()?.formatandOpenTelemetryConfig::from_env()?.log_formatareLogFormat::ByProfilewhen<PREFIX>_LOG_FORMATis unset, soformat == LogFormat::Json, or amatchwith its_arm, takes the text branch in production, with no error. The question to ask isformat.writes_json(). -
A run relying on the framework’s development Redis or store — the loopback, the dev container’s RustFS — fails its boot naming
<PREFIX>_REDIS__URL,<PREFIX>_STORAGE__URLor<PREFIX>_STORAGE__ACCESS_KEY, in every profile: name them in.env.developmentand.env.test. -
A
.env.developmentstill setting<PREFIX>_GRAPHQL__EMIT_SDLor<PREFIX>_OPENAPI__DOCUMENT_PATHis read by nothing, and the boot says each retired atwarn,read_asnaming itsEMITorEMIT_PATH; the development run writesschema.graphqlandopenapi.jsonbeside the app’sCargo.tomlanyway. A path the old key gave relative to the workspace root, kept under the new name, now lands under the app crate: drop it, or make it relative to the app. -
A process still setting
<PREFIX>_GRAPHQL__DISABLE_INTROSPECTIONfails its boot —… is read by nothing since 7.0 — set <PREFIX>_GRAPHQL__INTROSPECTION: …— inline or as a file: its successor is its opposite, so a rename by hand inverts it, and read by nothing,truewould leave introspection answering under a development profile. In a.envfile under aGraphqlModule::for_root(cfg), the pin holds the policy and the file reaches nothing, so it is said retired atwarninstead.<PREFIX>_GRAPHQL__INTROSPECTION=trueopens it, and a deployment’s boot says so atwarn. -
A configuration refusal opens on the variable it refuses —
invalid value for <PREFIX>_HTTP__PORT: …— and a validation failure lists each field beside its variable,client_id (<PREFIX>_ISSUER__CLIENT_ID): length, never the value; code downcasting the boot’s error toFactoryFailedErrorto read a config failure finds theConfigErroritself. A log setting that does not parse —<PREFIX>_LOG_FORMAT=jsno, aRUST_LOGdirective with a wrong level — stops the boot naming the variable, where 6.x took the default in silence. -
A log filter or a dashboard keyed on a unit’s boot line —
mounted route,mounted operation,mounted message,mounted mcp host,registered queue processor,scheduled job (…)— or on itscontroller,handler,resolver,gatewayorprocessorfield, the schedule’sprovider, or MCP’skindandtools, reads nothing: every edge says a unit it serves as onemountedline withhostandmethodand its address (verbandpath,field,event,tool,promptorresource,queue,trigger), and the module line at register readsmodule registered. On HTTP’s mount linemethodis now the Rust method and the HTTP method isverb, so a filter onmethod="GET"there reads nothing. -
A log filter or a dashboard on an operation line’s protocol fields reads nothing under its old word;
methodis the Rust method wherever a line says it.http.request’smethodandrouteareverbandpath.mcp.operation’smethodismcp_method, and itsoperationistool, beside a newpromptandresource.graphql.field’sroleandoperationarekindandfield, withhostandmethodbeside them;role="entity"androle="federation"readkind="query", theirhostandmethodsaying which.graphql.operation’soperation_typeiskind.subscription item withheldsayshost,method,kindandfieldwhereoperationheldsubscription ticks. OpenAPI’s duplicate warnings sayverbandconflicting_verb, and three lines naming a site saysitewhere they saidroute. OpenAPI’s lines omitting a route sayhostandmethodwhere they saidcontrollerandhandler, HTTP’s warning on a route at the fallback’s pathhostwhere it saidcontroller, and GraphQL’s unreachable resolverhostwhere it saidresolver. Spans keep their conventions’ names. -
A log filter or a dashboard keyed on a line naming a unit reads nothing under its old field: a guard’s denial says
methodand the unit’s coordinates (verbandpath,kindandfield,pathandevent, orpathand thetool,promptorresource) where it saidaddress, andws.messageandmcp.operationsaypathbeside them, asws.connect,ws.disconnect,graphql.subscriptionand every line naming a message or a socket do — under a global prefix the path a client calls, prefix included — and itsguardis the short name (AuthnGuard<JwtStrategy<Claims>>); a scheduled job’s or a lifecycle hook’s lines sayhostwhere they saidprovider; a job’s and a listener’s sayhostandmethodwhereprocessorandlistenerheldType::method;wired event listenerismounted, atinfo. -
A log filter or an alert on a withheld chain’s line finds the unit’s fields beside
error:request failedandrequest unavailablesayverbandpath, as thehttp.requestline does;graphql operation failedandunavailablesaykindand the rootfieldthe failure was met under, as thegraphql.fieldline does, whatever alias the document wrote;websocket message failedfrom.opaque()sayspathandeventas the gateway’s own always did, andmcp operation failedandunavailablesaypathand thetool,promptorresource. Each is filed once the answer goes out, not at the.opaque()call — nor atproblem_error’s on GraphQL: a failure an exception filter answers as the caller’s4xxfiles none, and a chain kept in an error a handler then discards is lost with it. -
A log filter on what the boot says reads nothing under its old word:
nestrs startingisapp starting, whoseversionis your app’s besideframework;attached module-contributed transportistransport attached; a transport readshttp,queue,scheduleoroutbox, on every line and in a refusal’s sentence, where it read its type, so aBootStep’stransportandTransportContribution::namehold that word;causereadssigint,sigterm,transport_failed,no_transport,boot_failedorclosed;log_formatreadstextorjson;max_connectionsis a number;sampleris a sampler’s name, what chose it insampler_source. A transport of yours keeps its short type name until it declares a word,fn name(). -
A log filter on a surface no guard runs at —
a gated endpoint runs no guard at its request; it denies every request,no guard runs at the /graphql request — graphql operations run unguarded— readsno guard at the requestonnest_rs::layers, withsurface,path,thenandhint; GraphQL’s sat onnest_rs::graphql, andgraphql operations gatedis gone.mounted endpointsayssurfacewhere it saidkind, addshost, and is filed once per template a surface registers, so a filter expecting one line per surface or a surface’s bare path reads the template instead. -
A log filter or an alert on a line’s value reads the operator’s word where it read a
Debugor a type path.phase="on_module_destroy"forOnModuleDestroy,action="read"forRead, a probe’skind="liveness"forLiveness,scope="request"forSome(Request),shape="bare"forBare;timeout_ms=1000fortimeout=1s, and every other duration in_mswhere it read_secs(max_connection_ms,fresh_ms,request_timeout_ms,shutdown_timeout_ms,body_read_timeout_ms,operation_timeout_ms,idle_timeout_ms), and a guard’s denialretry_after_mswhereretry_afterread seconds.idreads the key’s bare value, andallowed_hosts,columnsandscopesa joined string.entityis the table name on every line,entity="posts"whereno ambient Ability … denying all rowssaidmy_app::posts::Entity.subjectis the table or a#[subject]’s ident,eventthe type’s last segment (PostPublishedEvent),relatedthe table, andprovider,context_type,strategy,store, a boundservice, a stop’stype_nameand an unresolvedlayera short name. -
A log filter on
response masking failedmatches nothing: a wire row refusing where it is written saysa reply's row is withheld from its calleratwarn, ora wire row answered a caller it was not judged foraterror, withentity,reason,host,methodand the unit’s coordinates on every edge, andauthorization denieddoes on a field grant’s refusal, so a filter ontoolormethodfinds them. -
A log filter on a versioned route’s
mountedline underheaderormedia_typeversioning reads where the route mounts:path="/v2/users"where it read/users, as a denial and the request’s line do.versionis on the line under the URI strategy too. -
A bounded duration outside its range — a zero lease, a drain window above an hour, a body-read gap at
0, a request or message timeout past 3600 — fails the boot naming the variable and why the bound is there, whether the value came from the environment or was pinned in code (then naming the field too). A timeout past the shutdown window boots, and says so once atwarn. -
Two declarations of one thing fail the boot naming both: two
#[config]structs on one namespace (ConfigError::SharedNamespace), two imports binding one port or pinning one config, two modules attaching one transport type, two MCP imports declaring a server or opening the posture:Terminal window contested declaration: `X` is declared twice — by `A::for_root(..)` at `imports[0]` of `AppModule`, and by … -
A composition with a hole fails the boot naming it:
UnbuiltProviderErrorfor a provider listed and never built,DuplicateProviderErrorfor a type registered twice,AccessGraphErrororScopeViolationErrorfor a dependency outside the imports or of a narrower scope,LateOptionalDependencyError,ProviderCycleErrorfor a request-scoped or transient cycle,UnclaimedOverrideErrorandOverriddenDependencyErrorfor an override nothing reads,ScopedLayerErrorfor a transient layer on a job, a tick or a listener,UngatedDiscoveryErrorfor a container built by hand that a transport discovers from, and aScoped<T>or abind = Sservice whose module the app does not import. -
A wiring gap a declaration knows fails the boot naming the line to add, where 6.x booted and failed each request that reached it. A
#[crud]controller or resolver, a route or a field under#[authorize(A, bind = S)], or the service a GraphQL-exposed entity names (#[expose(service = S, graphql)]) with no unit-of-work binding namesSeaOrmDatabaseModule:Terminal window unmet dependency: `UsersController` (in module `UsersHttpModule`) depends on `dyn UnitOfWork`, which no module this app imports provides. Import exactly one unit-of-work binding: `nest_rs::seaorm::SeaOrmDatabaseModule` runs every edge's units of work over SeaORM's executor.A provider injecting
Arc<Jobs>with no queue backend namesRedisQueueModule, one injecting the pool or the default instance’sRedisConnectionwith no module opening it namesSeaOrmModuleorRedisModule, and a host or a root’sGlobalGuardsbindingThrottlerGuardwith nothing importing the port namesThrottlerModule— where 6.x told it to add a provider or seed one. A GraphQL schema serving an exposed relation whose target’s module the app does not import names the field, the entity declaring it and the module, where 6.x counted the loader atwarnand erred on every query selecting the field; so does a#[field_resolver]’s&DataLoader<L>parameter, where 6.x panicked on each. A served#[field_resolver]whose resolver the app does not reach names the field, the resolver and the module: 6.x panicked on what the resolver injects, or, with nothing injected, ran it outside every module the app imports. Import the module it names. -
A
#[field_resolver]’s&DataLoader<L>over aLoaderwritten by hand fails to compile (E0277,`L` is no loader `#[dataloader]` generated), where 6.x read what aGraphqlContextSeedseeded: only a generated loader says which module owns it, so only that one the boot can check. Step 12 has the two ways out. -
Layers. The compile refuses every name step 10’s left column lists, a guard listed by both
#[use_guards]and#[force_guards], a layer attribute an edge does not run — each with a sentence saying why — and a#[meta]value that is notSend + Sync. The boot refuses a layer a site declares that no imported module provides (UnresolvedLayerError), a global guard, pipe, interceptor or exception filter no module provides, a pool listing an authorization guard before the authentication one — in every app, workers included — and two#[meta]values of one type at one level (DuplicateMetaError). The app’s global interceptors and exception filters now run around every unit on every edge; a layer written for HTTP requests alone declaresserves.#[authorize]’s class gate runs with the guards, before any interceptor or filter a route declares, so a filter that counted its refusals sees none. A global guard a bridge used to keep off/graphqlor/mcpnow refuses there what it refuses everywhere, and an/mcpendpoint with no guard denies every request. A filter that answeredOkfor a failed unit changes what the client reads, never whether the unit rolls back. -
A 6.x job left at the root never runs: 7.0 does not read it. Finish step 18.
-
An app binding SeaORM and a queue backend over a database without
nestrs_outboxrefuses to boot:the outbox table `nestrs_outbox` is missing: run `nestrs g migration nestrs_outbox`, then `nestrs run db up`. -
A second unit-of-work binding refuses the boot naming
nest_rs::database::BACKEND_REMEDY. -
A listener running past its timeout — ten minutes unless
#[on_event(timeout = "…")]declares one, where 6.x set none — is cut inside its unit, which rolls back, so nothing it wrote stands. The bus logsevent listener failed — dispatch continues with the next listeneraterroronnest_rs::events, itserrorreadingthe listener did not end within its 600s timeout, and was cut — `#[on_event(timeout = …)]` sets it, and the next listener runs. Declare a longertimeout, at most"24h", or push a queue job. -
A job firing once, renamed without
key, is a new job: through the rolling deploy that ships the rename, the old build and the new one claim each occurrence under two identities, and both fire it. Pin the old identity withkey = "…", copied from thekeyits boot line names. -
A Redis URL ending in
#insecurefails the boot — itasks to skip certificate verification (`#insecure`), which is refused— where 6.x never spoke TLS to Redis at all. Trust the authority that signed Redis’s certificate with<PREFIX>_REDIS__TLS_CA_CERTinstead. TLS material no handshake could use fails the boot naming its variable. -
A Valkey Cluster named with
rediss://, the one scheme 6.x read, fails the boot:the Redis URL declares the … topology, but … serves the … one, naming the three schemes and the variable. Name the Cluster’s nodes withrediss-cluster://, and a Sentinel deployment’s sentinels withrediss-sentinel://— see Valkey topologies. -
A Postgres URL with an unverified
sslmode, an OAuth provider endpoint over plainhttp, a non-loopbackhttpredirect, or a loopback one outside a development or test profile, fails the boot naming its variable and the RFC. -
A Postgres server only the system’s store vouches for, beside libpq’s
PGSSLROOTCERTnaming another authority, fails the bootTLS failed — name the authority that signed its certificate in libpq's `PGSSLROOTCERT`, which this process sets, …: the variable is the root of verification, as libpq reads it. Name the right authority there, or unset it. A certificate filesslrootcert,sslcert,sslkeyor a libpq variable names that the process cannot read fails the boot at once naming where it is set, where it was retried until the connect budget ran out. -
Storage:
<PREFIX>_STORAGE__BUCKETfails the boot naming<PREFIX>_STORAGE__URL, a bucket that does not exist fails it at once, a key the store rejects fails it at once naming the credential variables, and half a credential pair fails it where 6.x paired it with a default. A client uploading through a presigned URL with another content type than the one signed, or none, is refused403by the store. -
A CORS list with
null, a path, a trailing/, a Unicode host or a forbidden method (CONNECT,TRACE,TRACK) fails the boot naming the list and the entry’s place, never the entry. A preflight for a method no route serves is refused403, and each refused cross-origin request files onewarnonnest_rs::http. A scheme the URL standard does not call special (tauri://,chrome-extension://) is compared byte for byte, its host’s case included: list it as the browser sends it. -
<PREFIX>_HTTP__TRUSTED_PROXIESwith a/0(0.0.0.0/0,::/0) or a range with address bits set past its prefix (10.0.0.1/8) fails the boot naming the entry’s place, and ranges holding between them every address of a family a caller connects from (0.0.0.0/1,128.0.0.0/1, or0.0.0.0/1,128.0.0.0/2,192.0.0.0/3, short only of multicast and reserved space) fail it naming the variable, as a list pinned in code does. Name your proxies’ own range, written from its first address; in code, atrusted_proxy!literal the type refuses does not compile. -
A listed proxy writing a forwarding header the parser cannot read — a hostname or an IPv6 zone (
%eth0) as a hop, a quote it left open — has every caller behind it read as the proxy, one throttler bucket for all, and filesforwarding header unreadable — no client is believednaming the header. Write each hop as RFC 7239 §6 spells a node (for="[2001:db8::1]:4711"). -
A listed proxy whose headers name two clients —
X-Real-IPwritten from its peer beside anX-Forwarded-Fora hop off the list wrote before it — has every caller behind it read as the proxy, and filesforwarding headers disagree about the client — neither is believed. List that hop, or have the proxy append toX-Forwarded-For(nginx’s$proxy_add_x_forwarded_for). -
A multipart client whose boundary RFC 2046 does not admit — longer than 70 characters, holding a character outside its set (
!,#,%), ending in a space, empty — or whose type namesboundarytwice, reads400withthe multipart body is malformed: …saying which, on a route readingMultipartand on/graphql, where the body was read. Browsers, curl and the common HTTP libraries write a boundary RFC 2046 admits. -
A cap or a deadline of
0—<PREFIX>_HTTP__MAX_CONCURRENT_CONNECTIONS,<PREFIX>_MCP__MAX_CONCURRENT_SESSIONS, an idle or send timeout — fails the boot naming the variable. A replica at its connection cap filesconnection cap reached; new connections wait in the listen backlogonce. Intermittent502s from a balancer are an idle deadline below its own: thetransport listeningline, atdebugonnest_rs::http, names the value inidle_timeout_ms. -
An MCP
initializepast<PREFIX>_MCP__MAX_CONCURRENT_SESSIONS— 1 024 live sessions per endpoint, where 6.x opened every one it was asked for — is refused503withRetry-After: 5and theUNAVAILABLEclass, andnest_rs::mcpfilesmcp session refused: the mount holds its maximumatwarn, naming the cap. A client opening a session per call fills it within<PREFIX>_MCP__SESSION_IDLE_TIMEOUT_SECS: reuse the session, or raise the cap. -
An HMAC secret shorter than its hash fails
JwtService::new: aJwtOptionschoosing HS384 needs 48 bytes, HS512 64. A deployment that kept the old scaffold’s public secret and sets none of its own refuses to boot withno JWT key configured, naming the variable. AnOTEL_METRIC_EXPORT_INTERVALoutside a second to an hour, or a pinnedtrace_sample_ratiooutside[0, 1], failsOpenTelemetry::initwhere 6.x kept the default. -
An app serving a resource under
OAuthResourceModulerefuses,401invalid_token, a token whoseissis not one of<PREFIX>_OAUTH__RESOURCE__AUTHORIZATION_SERVERS, compared exactly — trailing slash included — or that names none, where 6.x checked no issuer unlessISSUERwas set; and a token whoseaudis not its resource. AnISSUERnone of them names fails the boot naming both variables, and so doesALLOW_ANY_AUDIENCEbeside the module. An issuer of your own that minted every token with one shared audience has every client’s token refused by the resource servers that require their own: mint each withsign_for. -
A token request for a resource the client is not registered for — or naming none from a client registered for several, or two at once — answers
400 invalid_target. One naming a scope the client is not registered for answers400 invalid_scopewhole, never a narrower token, and one naming a grant the endpoint does not serve —password, a URN,Client_Credentials—400 unsupported_grant_type. -
A client registry the boot refuses:
<PREFIX>_OAUTH__SERVER__CLIENTSunset or empty, a client with no resource, a duplicate or empty id, an empty secret —configuration validation failed for `<PREFIX>_OAUTH__SERVER__*`, each client named by its id — which is what a deployment still setting<PREFIX>_OAUTH__CLIENTSalone meets, since nothing reads that name now. -
The demo run under the production profile: no file production reads names a client, a sign-in resource or a key, from the workspace’s root or from an app’s own directory. Once
nestrs run start <app>names its database and what else comes first, an app verifying tokens, every app but the worker, refusesno JWT key configured, andauththe client registry above andresources (<PREFIX>_SIGN_IN__RESOURCES): at_least_one_resource. Name your own on the process, or declare<PREFIX>_ENV=developmentagainst the dev container. An app of yours modelled on those files moves what authenticates anyone to its.env.developmentand.env.testthe same way. -
The demo chart with a social provider’s client id in
auth’sexistingSecret: since 0.6.0 the chart derives a provider’s redirect only from a client id it sees, insecrets,configorapps.auth.config(since 0.7.0 inauth’sextraEnvtoo, and as<KEY>_FILE), soauthrefusessocial provider `github` is linked but misconfigured, naming<PREFIX>_SOCIAL__GITHUB__REDIRECT_URL. SetSOCIAL__GITHUB__REDIRECT_URLin the chart’sconfig. -
The demo chart’s
existingSecretrefuses the install since 0.7.0, namingdefaults.existingSecret: every app has a Secret of its own,<release>-<app>, holding only what itsreadsnames, where one Secret,<release>-env, handed every app all ofsecrets.defaults.existingSecret: <yours>keeps one Secret for every app; anapps.<app>.existingSecretper app keeps each to its own keys. A key ofsecretsno app reads, a required one an app is not handed, and one an app is handed both as<KEY>and as<KEY>_FILEnow refuse the install, naming the key and the apps that read it: add a key your own module reads under that app’sreads. A tool reading<release>-envor<release>-issueras a Secret reads<release>-<app>. -
The demo chart without the hostname of
apiorliverefuses the install since 0.8.0, namingAUTHN__AUDIENCEand the app: each app verifying a token requires its own audience, derived from itshost, where the install went through and the app refused its boot. An app kept off the Ingress pins it inapps.<app>.config. -
A development-only route kept in a deployment: an app listing
DevelopmentOnlyGuardrefuses its boot unless<PREFIX>_ENVdeclaresdevelopmentortest—DevelopmentOnlyGuard guards a route only development and test serve, and <PREFIX>_ENV declares production. -
A module named
oauth:nestrs newandnestrs grefuse it, naming the family whose paths the word starts; rename it for its domain (sign_in). -
A social provider whose module the app does not import is closed: its
/social/<provider>/…routes answer404, said atdebugonly, since a provider left out on purpose is not a fault. -
A relation-gated
Ability::cananswersfalse: a service guarding a write with it refuses until the check moves toRepo::can. A subscriber stops receiving the items a relation or a hidden column alone admitted, andnest_rs::authzlogsan ability rule cannot be decided on a pushed valueonce per entity and action. -
A
Reporead that relied on seeing deleted rows compiles and returns fewer rows; read them throughwith_tombstones. -
A SeaORM builder method on a
Reposelect answersE0599,no method named query found for struct RepoSelect: it hands out no statement. A trait import left beside it warnsunused import, which-D warningsrefuses. -
Expr::custunder the scaffold’sclippy.tomlfailsnestrs run lint,use of a disallowed method, with what to write instead. A project with no such file compiles it: copy the file from a new scaffold to be told where it is written. -
A query answers
500witha condition or value handed to Repo refusedatwarnonnest_rs::orm, itsreasonfield naming why: a raw fragment in its condition closes a parenthesis, a string or an identifier it did not open, leaves one open, or holds a comment, dollar quoting or a backslash in a plain'…'string. Close what it opens, write the stringE'…', or better, bind the value (cust_with_values). A statement a log or a test reads now holds each condition in parentheses of its own. -
AbilityBuilder::buildfails, the ability guard answering500, withmalformed authorization rule: … writes text into its condition that would not stay where the scope puts itand itsreason, filed aterroronnest_rs::authz: a relation’son_conditionthat a rule’srelated(…)reads closes a parenthesis, a string or an identifier it did not open, leaves one open or holds a comment, or awhencompares an enum value whose type name holds a". Write theon_conditionwith sea-query’s typed calls and the enum as aDeriveActiveEnum. A scope’s subquery now holds theon_conditionin parentheses of its own. -
A derive expanding to a listed call fails the same way with
this error originates in the derive macro, and an#[expect]on the struct addsthis lint expectation is unfulfilled: it goes on the module holding the entity. -
A downcast of
nest_rs::database::current_executor()to the SeaORM executor compiles and answersNone: the handle a unit installs is private tonest-rs-seaorm. Run the statement throughRepo, which filters it, or a named escape whose bar it clears. -
with_abilityin a request no ability guard authorized installs nothing, so the body’sReporeads match no row, andnest_rs::ormsaysno ambient Ability outside a worker job — denying all rowsatwarn. Inside a unit holding an ability it runs the body under what both allow, so a read the caller’s rules refuse stays refused. Put the rule in theAbilityFactory; a job acting for a principal keeps itswith_ability. -
A
cannotnowhennarrows, beside a broader grant — CASL’scan(Manage, E)pluscannot(Create, E)— refuses its action at the class gate on every edge:403,forbidden, with noinsufficient_scopechallenge, andnest_rs::authzfilesauthorization deniedatwarnwithreason=class_denied. A list that answered200 [], a create that drew the database’s409or500, and a hand-written handler body now answer that403before anything runs. A denial meant for some rows alone takes a.when. -
A
cannotwhosewhenholds for every row by its shape —p.all([]),Predicate::Always, a disjunction holding one — refuses the same way, at the class gate, where its rows used to decide it. A denial meant for some rows alone reads a column in its.when. -
A site gated on
Manage—#[authorize(Manage, E)],#[public(Manage, E)],Ability::can_class(Action::Manage, ..)— means every action, and no longer readsManage’s rules alone. Acannotnowhennarrows on any one action, besidecan(Manage, E), now answers it403,forbidden, withreason=class_denied, where the request ran; acannotawhennarrows takes its rows out ofRepo::scoped(Action::Manage),Ability::canand abindunder it. Gate the body on the action it runs (#[authorize(Update, E)]), or drop the denial. Four separate grants now pass such a site, where they answered403. What it answers showsRead’s columns and rows, notManage’s: a.fieldsgrant onReadbesidecan(Manage, E).fields(..)widens the reply, acannot(Read, E)narrows it.missing_scopesnames what each refused action lacks, so a scope challenge may appear where the answer was a plain403. -
A module listing
ClientSecretBasicStrategy<P>orClientAuthenticationGuard<ClientSecretBasicStrategy<P>>besideOAuthServerModule::<P>fails the boot:duplicate provider: ClientSecretBasicStrategy<P> is registered by … and again by …. Delete the line; the module provides it. -
JwtService::expiry()no longer resolves (E0599), nor does a claims literal once its type losesexp(E0560): the signer stamps it. -
sign_handshakewith claims carrying noexpanswers aSignError, namingexpiry_in, where such a token used to fail atverify_handshake: a handshake never inherits the access-token lifetime. -
signorsign_foron claims naming no subject, theiractor_id()Noneor blank and nosubof their own, answers aSignError, where it minted an access token with nosubno verifier could attribute. So does asubthat is no string (sub: u64, RFC 7519 §4.1.2), where it minted one a verifier reading a string refuses: hold the id as a string, or under another name with#[principal(actor)]. -
A
JwtServicenaming no issuer or no audience —<PREFIX>_AUTHN__ISSUERor<PREFIX>_AUTHN__AUDIENCEunset or blank, or aJwtOptionsbuilt in code without them — fails the boot naming each it lacks, whether the app signs or only verifies, where 6.x minted tokens naming neither and verified a token naming neither (RFC 9068 §2.2, §4). UnderOAuthResourceModuleboth are read off the resource, and a service there naming noISSUERof its own boots but mints no access token:signandsign_foranswer aSignErrornaming the variable.ALLOW_ANY_AUDIENCEstands in for the audience, andsignthen answers aSignErrortoo: mint withsign_for. -
signorsign_foron claims naming noclient_id— absent,nullor blank — answers aSignErrornaming the claim, where it minted an access token naming no client, which RFC 9068 §2.2 requires. -
sign,sign_fororsign_handshakeon claims holding a registered claim of another JSON type —client_id: u64,iss: u64, anexpthat is a string or negative, anaudof numbers, anamrthat is no array of strings, ascopethat is an array or breaks RFC 6749 §3.3’s grammar — answers aSignErrornaming the claim, where it minted a token a verifier reading that claim refuses. Hold a client id as a string; writescopewithnest_rs::authn::scope::space_delimited. A registered claim serialized asnullis now left out of the token, where it went outnull. -
A signing failure answers the opaque
500, where it answered401with aBearerchallenge: a client retrying with another credential now stops, and the chain is onnest_rs::httpaterror. -
A token carrying
cnfis refused,401 invalid_token, reasonsender_constrained, where it passed as a bearer with no proof of the key it is bound to. An external issuer minting bound tokens mints this audience plain ones. -
<PREFIX>_OAUTH__SERVER__CLIENTSwith a scope outside RFC 6749 §3.3’s grammar — a space, a", an empty string — fails the boot onclients[<id>].scopes, where"a b"was granted whole when no scope was asked and refused when asked by name. List the two scopes. -
<PREFIX>_OAUTH__CLIENT__SCOPES,<PREFIX>_SOCIAL__GITHUB__SCOPESor<PREFIX>_SOCIAL__GOOGLE__SCOPESholding an entry outside RFC 6749 §3.3’s grammar —"openid email", one entry with a space, or a"— fails the boot onscopeswithnot_a_scope_token, as does anOAuthClientConfigpinned with one, where it was sent as written. Separate the scopes with commas. -
requires_scope("…")no longer compiles (E0308, expectedScope, found&str): declare the scope as aScopeconstant. -
A
.fieldsonUpdate,CreateorManagenow holds a write to its list. A write setting another column answers403,FORBIDDEN, where it wrote the column: undererrorsby the input’s field on a#[crud]operation, indetailby the table’s name throughServiceError, andRepoError::Forbidden { columns }to a service readingRepoitself.nest_rs::ormfilesaccess denied — a column the caller's grants withholdatwarn. APUTcarrying a column back as it stands passes where the caller may read it; one it may not read refuses whatever the value, so grant the read, take the column out ofinput(update), or give that caller a route of its own. A.fieldsonManageholds every action’s writes, so anUpdategrant of its own beside it widens them. A row whose grants do not permit each column answers404, as any row outside the scope. -
.fields([Headline])on a#[sea_orm(column_name = …)]column keepsheadlinein the reply, where 6.x stripped it: a client reading its absence reads the value. -
Repo::updateof an active model setting nothing answersRepoError::NotFound, a404, for a row outside the caller’sUpdatescope or a tombstone, where it handed the row back, and for a key no row holds, where it saidRecordNotFound. A service using it to read reads withRepo::find_by_id. -
cannot(..).requires_scope(..)orcannot(..).fields(..)no longer compiles (E0599,no method named requires_scope found for struct RuleSpec<'_, E, Cannot>), nor does aRuleSpec<'_, E>written for whatcannotreturns (E0308,mismatched types, expectedRuleSpec<'_, E>, foundRuleSpec<'_, E, Cannot>). -
nest_rs::database::with_request_executororwith_job_executorno longer resolves (E0425), nor does anAbilitypassed towith_ambientorcx.attach(the trait bound Ability: AmbientValue is not satisfied). Run a service test throughapp.unit(ability, || …)orapp.system_unit(|| …), and attach the caller’s ability throughAbilityGuard. -
A job unit opened inside a request —
run_unitwithExecutorScope::Job— or work a job captured and a request re-enters runs as the request: with no ability itsReporeads match no row, at the samewarn. System work runs in a queue attempt or a tick of its own. -
A stale or mangled page cursor — an
afterno page issued — is refused where 6.x served the first page: a#[crud]list answers400, its problemquery parameter `after`: not a cursor this endpoint issuedunderINVALID_ARGUMENT, and GraphQL a field error,Invalid value for argument "after", not a cursor this endpoint issued. Neither quotes the cursor; an emptyafteris still the first page. Follow theLinkheader’snext. -
A health probe or dashboard keyed on
dbordb_readyreads nothing: the key isseaorm, besideredis[:<instance>]andstorage. A readiness method namedseaorm,redisorstoragein an app that opens that resource fails the boot. -
An import of
SeaOrmHealthModulefails to compile, rustc naming the itemnest_rs::seaormno longer has, as does one ofRedisHealthModuleorStorageHealthModule. Delete the import: the module opening each resource attaches its check, andHealthModuleruns it. -
A replica out of rotation while its database, a Valkey or the store is down — where 6.x kept it serving, unless
SeaOrmHealthModulechecked the pool — is that resource’s check: an app importingHealthModulechecks every resource it or its features open (step 11). The503’serrornames it:seaorm,redis[:<instance>]orstorage. -
A log query on a renamed line or field finds nothing: the 6.x line
shutdown signal receivedisapp draining,transport listeningatinfoisapp ready,running lifecycle hookis thelifecycle.hookline, a WebSocket deadline’smessage_timeout_secsistimeout_ms,cause="framework"orcause="another_app"iscause="dependency", and an authentication line’sdetailiserror, the whole chain. -
A tool that scrapes stderr for
panicked atfinds nothing under#[nest_rs::main]: read theerrorevents onnest_rs::app, or the unit’s own line for a panic it contains. -
A secret field given a
Stringfails to compile,expected Secret<String>, found String, and one read as a stringno method named … found for struct Secret: add.into(), or read it with.expose_secret(). An#[expose]left on a secret column fails with#[expose]: `password_hash` holds a `Secret`, which never crosses the wire. -
A serde derive left on an
#[expose]d entity fails to compile at the derive:#[expose]: `Model` derives `Serialize`, which writes every column, hidden ones included, onto a wire — a reply answers `User` (`Json(User::from(&model))`): drop the derive, and the same forDeserialize, naming the entity’s inputs. Once it goes, a handler answering the row —Json(model),WsReply::reply(&model), aVec<Model>in a DTO — fails withE0277,a row crosses no wire: `fn(Model) -> User` builds what a reply answers, and a write takes the input `#[expose(input(..))]` declares: answerJson(User::from(&model))(step 9). -
A serde impl written by hand on an
#[expose]d row, or a derive above the decorator, fails withE0119,conflicting implementations of trait Serialize for type Model, its note namingAModelCrossesNoWire: the same goes forDeserialize,JsonSchema,#[output],#[input], and with thegraphqlfeature for async-graphql’sSimpleObject,InputObjectand#[Object], which write or read every column. Delete it and answer the exposed type (step 9). A blanket of your own over one of those traits reports the same beside a specific impl on the row: the row’s impl goes (step 9). -
A grant on
Readwithholding a column nonullanswers fails when the ability builds, so every request of that principal answers500with the ability guard’srules_misconfiguredline:malformed authorization rule: the grant for `Read` on `users::Entity` withholds `email` in `.fields`, which a reply cannot answer null — declare the column `#[expose(nullable)]` on `email`, or name it in `.fields`. A unit test building each role’s ability sees it first. -
A wire row kept and answered elsewhere — a cache, a row carried into another request, a publisher’s push — answers
500on HTTP,INTERNALon GraphQL, a dropped item on a subscription, and filesa wire row answered a caller it was not judged foraterroronnest_rs::authz. Build the row where it answers.
At boot, the refusals not named above, each a sentence ending on its remedy:
- Two factories waiting on each other fail the boot with
FactoryCycleError:factory cycle: … — each waits on a factory output that a member of this set … would provide. Drop one_afterdeclaration. - A module imported in a
collectalone, the shape a hand-writtenimpl Moduletakes, fails withUnregisteredModuleError:`…` was imported in a collect phase alone, so none of its providers registered. Import it throughContainerBuilder::importin its importer’sregistertoo. - A factory queued in
register, or a seed its module’s check refuses, answersContainerError::LateFactoryorContainerError::SeedRefusedfrom a container built by hand: queue it incollect, and seed a value that passes the check a read one passes. - A transport of your own stating a stop bound past a day fails with
UnboundedTransportError:a transport's stop is bounded: declare its drain window. App::initorApp::runcalled again after an init that failed answersInitFailedError,the app's init failed earlier: it does not run again: build a new app.- A resource’s budget at or past the net of a port waiting on it fails with
BudgetPastNetError:…'s budget (…) must be shorter than …'s net (…), naming the setting to lower. - One variable read by two configuration types fails with
ConfigError::ContestedVariable:`…` is read by two configuration types. Give one its own key or namespace. - A named instance reading a namespace another declaration holds fails with
ConfigError::SharedInstance:the instance `…` reads the namespace `…`, which … also claims. Rename the instance. - A
ClientTlsor other shared vocabulary under a field of another name fails withConfigError::MisnamedField,name the field `…`: its refusals name its variables by that field’s key. - A duration read through a
ConfigServicereader fails withConfigError::UnboundedDuration:… is a duration, and a duration is read through the `DurationBounds` its field names. Declare the field with#[config(bounds = …)]. - A Redis URL asking for RESP3 (
protocol=resp3) fails the boot naming the variable to remove it from: nestrs does not speak RESP3 to Redis. - A queue lease not above one and a half times the Redis budget fails the boot:
the Redis queue lease (…) must be more than one and a half times the Redis budget (…), since a renewal sent a third into the lease may wait out the whole budget. Raise the lease or lower the budget. replicas = "one"with no occurrence lock bound fails the boot naming the job: importRedisScheduleModule. A job attached by hand as aCronJobMetafails it too for akeywithoutreplicas = "one", or a one-shot declaring it, the two mistakes a decorator refuses at compile time.- Two scheduled jobs sharing one name fail the boot (
scheduled jobs share one name: …): rename one host, or fold the two methods. Two jobs firing once under one identity fail it too (scheduled jobs firing once claim under one identity: …): give each its ownkey. - A
#[process]declaration its backend cannot honour, a throttle window under a millisecond, or two methods draining one queue fail the boot, one error naming every offender at once. memory:///in a deployed or undeclared profile fails the boot:names memory, a store in this process that loses every object at a restart. Name ans3://store. An S3 setting besidememory:///fails it too (is set beside …, which names memory): unset it.- A GraphQL schema keying an entity without
GraphqlConfig::federationfails the boot:`…` keys an entity … but this schema is not configured as a subgraph. Set<PREFIX>_GRAPHQL__FEDERATION=trueand serve it behind the router it names, or drop the key. - An
McpIdentitynaming a server no#[mcp]host serves fails the boot, as do two hosts on one path declaring one prompt. HttpTransport::from_configrefuses values a transport built in code passed: a duration or aversion_headeroutside what its variable accepts, naming the variable and the field; a body-read gap at or past the request timeout files one bootwarn.- A protected resource’s URI carrying userinfo, or loopback
httpin production, fails the boot. - A refused credential or a missing database fails the boot, where the first request met it: the sentence names the resource and the variable.
At run time, what now answers differently:
- An MCP session an earlier release stored is refused: the client opens a new one. A
session stays its principal’s, and a principal naming no subject answers
403. - The app’s interceptors and exception filters now run around every job, tick, listener
call, GraphQL root field, MCP operation and WebSocket message, and the class gate runs
before a message’s pipes. One written for a request reads the edge from
cx.edge(). - A
Resultrenamed on import or behind an alias fails as aResultdoes, on the line and to the client, where its error reached the client as data and its line filedok. /graphql/anythinganswers404, and the graphql-ws handshake’sHEADanswers400. Point a client at/graphqlitself.- A
Path<T>signature mistake answers500, where it answered400: a route template’s parameters and the handler’s type are a programmer’s, never a client’s. - A statement past 15 s is cancelled by Postgres, answering
503with its wait. A long report raises<PREFIX>_SEAORM__STATEMENT_TIMEOUT_SECS, or runs as a job with its owntimeout. - The OAuth client refuses a plain
httpendpoint, and an answer past 64 KiB fails as the provider’s. requiredScopes, and a challenge’sscope, name the narrowest grant’s scopes alone: a client reading the whole list reads that one.- A fall-back day fires more under a zone that repeats the hour: read a daily job’s
#[cron]beside the zone. - A suite logs what its console allows:
with_test_telemetrykept it towarn, and a project scaffolded before setsRUST_LOG=warnin.env.test, asnestrs newnow writes.
At build, what your own lines meet:
- A
Resultalet _ =discarded in your own code isclippy::let_underscore_must_use’s, once the workspace denies it (step 1). runtime-tokio-rustlson asea-ormline of yours compilesringagain, beside the dependency policy’s ban: takeruntime-tokio, with sqlx’stls-rustls-aws-lc-rs, asnest-rs-seaormdoes.
At compile time, each decorator’s own grammar. Every sentence below is pinned in
crates/nest-rs-macro-hygiene/tests/integration/diagnostics/, one fixture per refusal, by
folder; what a 6.1 project most often meets:
- Any impl-half decorator (
#[routes],#[operations],#[messages],#[tools],#[processor],#[scheduled],#[listeners],#[indicators],#[hooks]) written on a struct, on a trait impl, or with arguments; a method taking&mut selforselfby value, or generic; a method declaring two roles or one role twice; two methods claiming one route, field, event, tool or prompt, whether spelled apart or under two truecfgs;#[use_guards]on the block rather than the struct beside#[controller],#[resolver],#[gateway]or#[mcp]. Each names the form it accepts. - A host with no caller (
#[processor],#[scheduled],#[listeners],#[indicators],#[hooks]) on a request-scoped or transient provider, or one stating no singleton:runs on a provider built once for the app. Its layers:#[use_guards],#[force_guards]or aversionthere has no caller, and is refused naming why.#[meta]twice with one type refuses every site. #[controller],#[gateway],#[mcp],#[resolver]: a missingpath, a path that is no mount path, a 6.x:param, a version that is no path segment or listed twice, or aversionon an edge with none to select (#[resolver],#[mcp],#[gateway]takes one).- A route: a path that is no template (
route_path_is_not_a_template), a parameter named two ways, a catch-all not last, a pattern on a parameter, two verbs on one method, one route spelled two ways or twice across a shared version, aversionthe controller does not declare,#[http_code]with no status, a shaper’s parameter left unread, or a handler parameter that is no extractor, whose sentence says what reads one. #[api]: a key it does not take, adeprecatedthat is no RFC 3339 full-date, anerrorstatus outside 4xx and 5xx, aresponse_content_typethat is no media type, amultipartbeside aJsonbody, and any response decorator on an#[sse]route.#[crud]: a key, op orpaginateit does not take, an emptyops, anapifor an op it does not generate, a service the host does not inject or spelled as its field, an op the service does not offer (`NotesService` offers no create), or a parameterised prefix.- A posture (
#[authorize],#[public]): twice, both at once, of the wrong shape, an unknown key, orbindnaming another entity, no resource service, noAuthorized<A, E>parameter or more than one route parameter;id_argoff GraphQL;unmaskedon any edge; a type that is no#[subject]; an#[sse]route naming an entity. - A guard bound where it declares no
GuardForfor that edge’s view:`HttpOnlyGuard` does not declare that it checks `GraphqlView` units; one writingcheck_httpalone is rustc’sE0046.#[use_pipes]on a GraphQL operation, a tool, a connection hook or a processor is refused naming where that edge takes its pipe. #[entity]and#[subscription]: an entity with no key, a posture missing, arguments, or a#[graphql(...)]of its own; a subscription whoseResultis spelled another way;#[graphql(entity)]beside a#[query]; a&Contextthat is not first; a foreign error through?.#[tool],#[prompt],#[resource]: no description, or a blank one; a tool with no result; a resource with no template or description, one with an RFC 6570 operator, a variable no parameter takes, a parameter no variable names, two templates;#[resources]twice or with an argument; a server identity on a host, which goes inMcpIdentity. A host written by hand meets rmcp’s own: an empty#[tool_router], which takes#[tool_router(allow_empty)].#[subscribe_message],#[on_connect]: an event that is no string literal, a hook repeated, a hook returning a value, a reply that does not serialize under#[authorize], and any layer or#[meta]on a connection hook.#[queue],#[process]:#[queue]on anything but a unit struct, nonameorjob, a name outside the rule;#[process]with no queue, a queue that is no marker, a job that is not the queue’s, keys outside a list,concurrencyorthrottlebelow one, atimeoutpast"24h",transactionalwithout a bool, aCheckpointon a transactional method (a Checkpoint<_> parameter needs transactional = false), a return that is noResult.#[every],#[cron],#[after]: a duration with no unit, or signed; a cron step shortcut (5/5) or no cron at all; atzthe IANA database lacks;retries, since a tick’s retry is the next occurrence; akeythat is no job key or withoutreplicas = "one"; two triggers on one method.#[on_event]: a job’s key (retries), atimeoutof zero, a return other than()orResult<(), E>.#[config]: nonamespace, a tuple struct, a field holding__or naming a unit (window_secs), aDurationwith no bounds, bounds no range of that type holds, a field read two ways, a struct’s key on a field and a field’s on the struct.#[expose],#[sea_orm]: a tuple struct or an enum, nonameor one that is no identifier, aSecretexposed, a hidden column with no placeholder, a hidden key, adefaulton a key or a stamped column, serde on theModel,soft_deletewith nodeleted_at,timestampswith no columns, a relation with no service, orfromandvianaming no column.#[module]: a key other thanimportsandproviders, generics, a provider listed twice or beside itsdynbinding, or adynbinding of a request-scoped or transient provider.#[injectable],#[inject],#[input],#[output],#[wire_enum],#[instance],#[subject],#[derive(PrincipalIdentity)],#[nest_rs::main]: anArcfield with no#[inject]; an instance with fields, generics, a reserved word or the nameUnnamed; a subject with fields, generics or arguments, or a rule that denies or narrows it (has no rows to deny or narrow); a claims type with noactor, or two;mainon a sync function.
Reference
Section titled “Reference”crates/nest-rs-config/src/unclaimed.rs— the boot’s report of a variable nothing reads, andtests/integration/unclaimed.rsbeside it.demo/crates/features/src/audio/service.rsanddemo/crates/features/src/chat/ws/gateway.rs— the 7.0 lines of steps 5 and 13, as the demo writes them.crates/nest-rs-queue/src/jobs.rs—push,push_with,push_many,push_many_withand the receipt;crates/nest-rs-macro-hygiene/tests/integration/diagnostics/queue/— each#[queue]and#[process]refusal, pinned.crates/nest-rs-redis/src/error.rs— the boot’s refusals: an#insecureURL, TLS that cannot work.crates/nest-rs-macro-hygiene/tests/integration/diagnostics/— every decorator’s refusal, worded as the compiler prints it.
Going further
Section titled “Going further”- Changelog 7.0 — why each change was made, grouped by what it makes true.
- Upgrading queues from 6.x — draining a queue’s 6.x jobs.
- Execution context — what every layer reads, on every edge.
- Env-var reference — every variable 7.0 reads.
- Delivery on Redis — where a 7.0 queue keeps what, and what it guarantees.
- Semver policy — what every 7.x release keeps from here on.