/autumn:autumn-webfrom autumn
Builds, debugs, documents, and upgrades Rust web applications using the autumn-web framework. Covers route/model/repository/job/webhook/admin macros, AppBuilder setup, Maud + htmx server-rendered UI, Diesel async Postgres, and migration guides for 0.11.x.
Ships in autumn. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Repository: https://github.com/autumn-foundation/autumn
Branch: trunk-dev
Latest release: 0.11.0 | Edition: 2024 | MSRV: 1.97.0
Version identity trip wire: the workspace on trunk-dev is versioned
0.11.0, and v0.11.0 is the current release line — autumn-web = "0.11",
cargo install autumn-cli --version 0.11.0. Features below carry the release
they arrived in — (0.11.0) is absent from 0.10.x and earlier,
(0.10.0) is absent from 0.9.x and earlier,
(0.9.0) is absent from 0.8.x and earlier, (0.8.0) is absent from 0.7.x
and earlier, (0.7.0) is absent from 0.6.x and earlier, and (0.6.0) is
absent from 0.5.x: if an app pins an older line, check
CHANGELOG.md before using them. Unmarked features
predate 0.6.0. An app moving up from 0.10.x follows
docs/migrations/0.11.0.md; one moving up
from 0.9.x follows docs/migrations/0.10.0.md
and then the 0.11.0 guide. 0.11.0 needs Rust 1.97.0. Run autumn upgrade
first.
autumn-web is a Spring Boot-style web framework for Rust, built on Axum. It assembles Axum, Diesel, Maud, htmx, Tailwind, Tokio, tracing, and production defaults into a convention-over-configuration stack with proc-macro ergonomics.
This file is the quick operating guide. Load the adjacent reference files only when their details matter:
docs/guide/index.md - the complete guide catalog: every page under
docs/guide/, grouped by task, each entry naming the question that page
answers. Start here when the topic you need is not covered by this file or
the references below, rather than guessing a filename — the index is gated
by cargo xtask check docs-guide-index, so it lists every guide page that
exists and nothing that does not.references/api-reference.md - release-line API map, proc macros,
feature flags, AppBuilder methods, config env names, and dependency versions.references/examples.md - official 0.11.0 example patterns for minimal apps,
CRUD, production-ish jobs, Redis channels, S3 storage plugins, and signed
webhooks. Use this before generating full app code.docs/guide/accessibility.md - accessible-by-construction UI. Prefer the
typed autumn_web::a11y primitives (Img / Button / Link / MenuItem
plus the labeled-typestate form controls TextField / TextArea / Select
(+ SelectOption) / Checkbox / FileField / RadioGroup
(+ RadioOption)) over raw <img> / <button> / <input> / <textarea> /
<select> in html! — the accessible name (alt
text, button label, field label) is a required constructor argument (a form
control cannot render until .label() / .aria_label() / .labelled_by()
supplies one), so a missing one is a compile error, not a runtime audit miss.
The form controls also carry validation/ARIA setters (.required(),
.aria_required(), .aria_invalid(), .described_by(), per-type
min/max/length) plus a .hx(name, value) escape hatch for arbitrary hx-*
attributes. Treat autumn a11y verify as an advisory/best-effort CI net, not
a guarantee (its route attribution reads #[cfg(feature)] against the
default features; add --features x / --all-features to match your build) — the typed primitives are the compile-time proof (0.6.0,
#1706). See skills/autumn-web/references/api-reference.md for the full
setter surface. To check rendered HTML from a test, shell out to autumn check --a11y --html "<markup>" and assert on the exit code (0 = no
Critical/Serious violation); there is no library import for the checker.
Pass a whole DOCUMENT: html-has-lang, bypass and landmark-one-main
run on every input, so a bare fragment fails on the missing page shell.
Wrapping it as <html lang="en"><body><main>…</main></body></html> settles
all three (a <main> first in <body> needs no skip link). --html
carries the markup in argv, which the OS caps (~128 KiB per argument on
Linux, ~32 KiB per command line on Windows), so check a large page with
--url against a served app instead — past the limit the checker never
starts and no audit runs.use autumn_cli::…autumn-cli ships a binary target only — no src/lib.rs, no [lib], so
cargo metadata reports bin plus tests and nothing else. pub inside it is
visible only within that binary, and no path into it resolves from another
crate however it is spelled. cargo add autumn-cli still succeeds, because the
crate does publish a binary, which is what makes this worth stating: every
other signal says the import is fine.
So anything the CLI does is reached by RUNNING it (std::process::Command, or
a shell step in CI), never by importing it. The library crates to import from
are autumn-web and the plugin crates (autumn-billing, autumn-storage-s3,
autumn-cache-redis, autumn-search, autumn-admin-plugin,
autumn-media-plugin, autumn-edge, autumn-schema-core, autumn-macros).
scripts/check-docs-symbols.sh fails any reader-facing page that writes such a
path, so a generated snippet carrying one will not land.
Autumn deliberately lets you drop to raw Axum routers and raw Diesel queries.
That is a last resort, not a starting point. Before hand-rolling any of
the patterns below, check this table and the matching docs/guide/*.md page —
the framework almost certainly already generates or ships it:
| Temptation (do NOT hand-roll) | Autumn-native answer |
|---|---|
Status-transition validation written by hand in before_create/before_update hooks or handlers (if old == "draft" && new == "published" match blocks) | #[state_machine(transitions(...))] on the model field — generated can_transition_{field}_to / transition_{field}_to enforce the graph. See "Model state machines" below and docs/guide/state-machines.md |
Raw axum::Router routes and handlers, manual .route("/x", get(...)) | #[get]/#[post]/#[put]/#[patch]/#[delete] + routes![...], .scoped(prefix, layer, routes) for groups. .merge()/.nest() exist for the rare escape hatch only |
| Raw Diesel queries for CRUD, lookups, pagination, or bulk writes | #[repository]-generated methods: find_by_id, find_all, save, update, delete_by_id, derived find_by_*, page(&PageRequest), cursor_page(&CursorRequest), bulk save_many/update_many/delete_many/upsert_many. See docs/guide/repositories.md, docs/guide/pagination.md |
| Manual per-item queries in a loop (N+1) or hand-written JOINs to fetch associations | #[belongs_to]/#[has_many]/#[has_one] + repo.preload(records, Model::preload()...) (0.6.0) |
| Hand-rolled auth, session, or token checks in handler bodies | #[secured] / #[secured("role")], #[authorize], repository policy =/scope =; #[secured(scopes = [...])] for service tokens (0.6.0) |
| A punishingly low global rate limit to protect one abuse-prone endpoint (login, search, export) | #[throttle(limit = 5, per = "1m", key = "ip")] sits alongside #[get]/#[post]; #[throttle("login")] reads [security.rate_limit.named.login] from config (0.6.0, issue #1350, see docs/guide/rate-limiting.md) |
Hand-assembled <form> markup with manual value re-fill and error display | autumn_web::form::form_for(&changeset, action, method) + the #[model]-derived FormModel (0.6.0) renders the whole form — CSRF, _method override, one pre-filled control per column, inline errors, submit — in one call; see "Whole-form rendering" below. Compose the per-field helpers only when its escape hatches don't fit: form_tag, method_input, text_input (published); number_input, datetime_input, date_input, checkbox_input, select_input + Changeset 422 re-render (0.6.0). For a hint, required, placeholder/autocomplete/data-*/hx-*, use the *_with helper + FieldOptions (or FormFor::field_options) — never hand-write the input to add one attribute |
find_all() + a loop (or raw Diesel LIMIT/OFFSET paging) to sweep a whole table in a task/job/backfill | repo.find_in_batches(n) / repo.find_each(n) (0.6.0) — bounded-memory primary-key keyset iteration. See "Generated repository surface" below and docs/guide/pagination.md |
Ad-hoc tokio::spawn / background threads for deferred work | #[job] (+ retries, backends, uniqueness/concurrency caps), #[scheduled] for recurring, #[task] for operator CLI work, app.background_task(name, capability, ..) (0.11.0, #3545) for a long-running loop placed by role (#3545) |
A hand-written #[scheduled] fn + batched DELETE/UPDATE to expire old sessions, drafts, or one-time codes | #[repository(Model, retention(after = "30d", basis = created_at))] (0.7.0, issue #1342) — batched, soft-delete-aware, fleet-coordinated sweep with zero SQL; autumn retention --dry-run to validate first. See docs/guide/retention-sweeps.md |
A cron job (or nothing at all) trimming autumn_jobs, autumn_job_tracking, autumn_experiment_assignments, or a JSONL audit archive | [retention] in autumn.toml (0.8.0, issue #1605) — one window per framework-owned dataset, enforced by a fleet-coordinated in-process sweep; autumn db retention --dry-run reports the effective policy and eligible rows. Sweeps run on Postgres and SQLite. See docs/guide/data-retention.md |
A hand-written SQL count of autumn_experiment_assignments per variant, eyeballed against the weights, to decide whether an A/B test's results can be trusted | autumn experiments srm <name> — chi-square sample ratio mismatch check against the split the weights predict, overrides excluded, counting only assignments since the weights were last set. Exits 3 on a mismatch; --json, --alpha. See docs/guide/experiments.md |
| A hand-written script that copies production data and masks PII for staging, on Postgres or SQLite | autumn db scrub (--check, --dry-run, --artifact, --output). A sqlite:// target or .sqlite backup scrubs in one transaction, then VACUUMs. An unclassified column aborts the run; declare columns in scrub.toml. --sample is Postgres-only. See docs/guide/data-scrubbing.md |
A custom_setup hook or raw PRAGMA mmap_size / PRAGMA cache_size to speed up reads on a large SQLite file | [database] mmap_size (bytes) and cache_size_kib (KiB) (0.11.0, #3571), both 0 = off; [database.fleet] has its own pair. Env AUTUMN_DATABASE__MMAP_SIZE, ..._CACHE_SIZE_KIB. mmap halves random and range reads on a large, read-heavy file, does nothing for small fleet files, and turns an I/O error into SIGBUS. See docs/guide/sqlite-in-production.md ("Memory-mapped reads and the page cache") |
| A hand-written GDPR export job that zips CSV/JSON a user cannot open, verify, or import again | GdprRegistry::capsule(CapsuleModel::new(table, subject_column).belongs_to(..)) + autumn data capsule export --subject <id> --out <dir> (issue #1811) — one signed directory with records, a manifest.json, blobs, and an offline HTML viewer; autumn data capsule import verifies every file, then imports with no loss of data. Use .exclude(column) for secrets. See docs/guide/data-capsules.md |
| Hand-written memoization or cache-aside code | #[cached] on functions; cache::get_or_compute / get_or_compute_with for stampede-safe read-through fills (0.6.0); .stale_if_error(window) serves the last value when a fill fails |
Calling cache.invalidate(key) by hand after a repository write | #[repository(Model, invalidates(cached_fn))]: each generated write drops the read after it commits (#3056). Async code uses Cache::invalidate_async, which returns the error |
| Hand-written transaction retry loops for serialization failures | Db::tx(...); Db::tx_with(TxOptions::serializable(), ...) auto-retries 40001 (0.6.0) |
Db taken before a body extractor (Form/Json/Multipart) in the same handler — pins a pooled connection for as long as the client takes to send the body | LazyDb in the same argument spot; call .checkout().await? after the body extractor runs — for Form/Json that means right at handler entry, but Multipart doesn't buffer anything during extraction, so checkout must wait until every field this handler needs has been read from the next_field() loop, not before it (issue #2264) |
Reading /actuator/metrics db_queries["<route> SELECT"] as a slow SELECT — the Db extractor writes its connection hold time there (checkout to release, all work in the hold), also on routes that only write | db_connection_holds["<route>"] (0.11.0, #3579) for the hold; db_queries for statements timed with run_instrumented. The Db write to "<route> SELECT" is deprecated and stops next release (issue #3579). A long hold with fast statements is work outside the database: take LazyDb and check out late. See docs/guide/metrics.md |
| Hand-rolled HMAC verification for Stripe/GitHub/Slack callbacks | SignedWebhook extractor + [webhooks.<name>] config |
| Hand-rolled pager markup (page-number windows, prev/next links) | pagination_nav(&page, &PagerOptions::new("/posts")) / cursor_pagination_nav (0.6.0) |
| Hand-rolled cross-module notifications (calling every reaction inline) | #[event] + #[listener] typed event bus, .listeners(listeners![...]) (0.6.0) |
| Hand-rolled cards, tabs, modals, delete-confirm dialogs, method-override links | autumn_web::widgets: card/stat_card, tabs, modal/confirm_action, link_to/button_to + ui::WIDGETS_CSS_PATH stylesheet (0.6.0) |
Hand-built file-download responses (manual Content-Disposition/Content-Type/Content-Length headers, byte-buffered blob reads) | autumn_web::download::Download — from_bytes / from_stream / from_async_read / from_blob(&store, key).await? + .filename(...) / .content_type(...) / .inline(); RFC 5987 filenames, injection-safe, streams blobs without buffering (0.6.0) |
Hand-parsed Range headers / manual 206 Partial Content / Content-Range / 416 for seekable media or resumable downloads | autumn_web::range (resolve + partial_bytes_response) and Download::into_response_ranged(&headers).await — RFC 7233 single-range parsing, multi-range single-range collapse, If-Range via .etag(..)/.last_modified(..), blob slices via BlobStore::get_range (no whole-object buffering) (0.6.0) |
Shelling out to wkhtmltopdf/headless Chrome, or hand-rolling a PDF library, to turn a view into a downloadable invoice/receipt/report | autumn_web::pdf::Pdf (pdf Cargo feature) — Pdf::from_markup(markup) / Pdf::from_html(html) + .filename(...) / .inline(); renders headings/paragraphs/tables/lists/bold/italic with the PDF base-14 fonts, no system browser or embedded fonts required. Test with TestResponse::assert_pdf_contains(&self, &str). See docs/guide/pdf-downloads.md (0.7.0) |
Hand-written RSS/Atom XML strings for a /feed.xml or podcast/blog feed | feed::Feed::atom(..) / feed::Feed::rss(..) + feed::FeedEntry — builds the XML, implements IntoResponse with the right application/atom+xml/application/rss+xml type, XML-escapes text, and Feed::conditional(&headers) reuses the etag layer for 304s (0.6.0). See docs/guide/conditional-get.md |
A hand-rolled AtomicU64 + a MetricsSource impl (or a whole second prometheus/metrics crate exporter) just to count something in a handler | autumn_web::metrics — metrics::counter("checkout_completed_total").with_label("status", "paid").increment(1), plus gauge, histogram and timer(..).start() (a guard that records on drop, so early ? returns and panics are covered) / time / time_async. Registers itself on first use and lands on the stock /actuator/prometheus and /actuator/metrics (app key) with zero AppBuilder wiring; caps cardinality (100 labeled series/instrument, 256 instruments, 8 labels/series by default) instead of leaking series (0.7.0, issue #1378); those three are the [metrics] section — max_series_per_metric / max_instruments / max_labels_per_series, plus AUTUMN_METRICS__* — so an app with a genuinely larger label space raises them rather than losing series, while the name/value/help-length caps stay fixed. Lowering a cap never evicts a retained series (that would reset a counter); an out-of-range value fails the boot naming the key. describe_* and set_histogram_buckets do not register anything, so startup calls work in either order; gauges and histograms take usize/u64/i64 directly (set(queue.len())). MetricsSource is still the answer when a subsystem already owns the numbers. See docs/guide/metrics.md |
Hand-timing handlers with Instant::now() to bill tenants, or a cron job that checks a carbon/price API before it runs heavy work | [cost] enabled = true meters CPU time, allocated bytes (with an AllocationProbe) and DB queries per request, job run and scheduled tick, by tenant: Server-Timing cost-cpu/cost-db, the autumn_cost_*_total{tenant} metrics, autumn_cost_work_*_total{kind}, GET /actuator/cost (sensitive; jobs.shift.ratio is the share of deferrable CPU that ran after the window). #[job(deferrable)] / #[scheduled(..., deferrable)] wait while CostSignal is above [cost] defer_threshold, then run; never dropped. Set the signal with CostSignal::set or the autumn_cost_signal runtime-config key (ConfigRegistry::define_cost_signal). Jobs defer on every jobs backend. See docs/guide/cost.md (issue #1720) |
| Reproducing a production 500 by copying the request into a test and guessing at the database state it saw | [failure_capture] enabled = true writes a redacted failure capsule (request + PostgreSQL wire traffic + clock readings + outcome, one JSON file) for every caught panic/5xx; autumn replay <capsule> re-runs it offline against an in-process stub DB — exit 0 reproduced / 1 mismatch / 2 refused. A capsule also carries every framework effect the run produced — outbound HTTP (webhooks included), job enqueues, cache reads/writes, mail, the resolved tenant and every random draw — and replay serves each from the capsule: no socket is opened, no job is queued, no mail is delivered, and a minted UUID/session id/CSRF token reappears byte-for-byte. A failure inside a job records a job-scoped capsule that autumn replay dispatches. Capsules are production data: read the security section of docs/guide/failure-capsules.md before enabling (0.7.0, #1598; 0.8.0, #1634) |
| Triaging the same production bug twice because the first fix had no test pinning it | autumn capsule test <capsule> converts a capsule into a committed regression test: it copies the capsule's bytes verbatim into tests/capsules/ (so whatever redaction removed stays removed), generates a #[tokio::test] beside it, registers both in tests/integration/mod.rs, and scaffolds a capsule_support::router hook once. The test drives the same replay engine autumn replay does and runs under plain cargo test with zero live dependencies — no network, DB, queue or Docker. autumn capsule verify replays the whole committed corpus, which doubles as an upgrade gate: run it against a new Autumn before deploying that version. Job capsules are refused here (no request to drive) — replay those with autumn replay. See docs/guide/failure-capsules.md (0.8.0, #1634) |
Proving a retry path survives "the 3rd DB checkout fails" or "the 2nd send_invoice execution fails" with a real-clock test that can only hope for the timing, or with Chaos rates that never reproduce the exact failure | autumn_web::sim::FaultPlan — an authored, seed-deterministic fault scenario attached with TestApp::with_fault_plan(plan): FaultPlan::from_seed(seed).fail_db_checkout(3).fail_job("send_invoice", 2) fails exactly those effects through the existing interceptor seams (no app code changes), only_between(from, to) gates faults on the injected clock, random_*_faults(n, 1..=k) picks ordinals from the seed. client.fault_outcome().await returns a serializable FaultOutcome (fired / suppressed / unfired / server_errors via reporting / final_state); to_json_string() is byte-identical on every replay of a seed under #[sim_test]. Drain jobs with Sim::run_to_idle (not perform_enqueued_jobs, which bypasses intercept_execute). See docs/guide/simulation-testing.md → "Authored fault scenarios" (#1680) |
A #[sim_test] that calls a real downstream service, hopes for a timing race, or reads Timestamp::now() / Instant::now() in code with no clock in scope | Sim::net(SimNet::new().host("payments", router).latency(..).drop_rate(..)) serves outbound http_client calls in-process with seeded latency, drops and partition/heal; Sim::interleave / Sim::spawn reorder ready work from the seed; sim::crash_at(i, op) drops an op at any await; time::ambient_now() / ambient_instant() follow the running Sim. See docs/guide/simulation-testing.md (#2967) |
| Testing job, scheduler or lock coordination with one app, or with two real processes and sleeps | Sim::mount_replica("a", app) / mount_replica("b", app) on one sim clock and one SqliteSubstrate; per-replica clocks (Replica::named("b").clock_ahead(d), Sim::step_replica_clock), per-replica DB faults (Sim::db_link(name): lose_session, mid_query_errors, commit_ambiguity), kill_replica / restart_replica, and Sim::run_for(d) to move time. See docs/guide/simulation-testing.md → "Multiple replicas" (#3067) |
Hand-assembled Cache-Control header strings on a handler | etag::cache_for(Duration) → CacheControl; attach as a tuple (cache_for(dur).public(), html!{…}) or .wrap(resp). Chain public/private, max_age, s_maxage, stale_while_revalidate, no_store, no_cache, must_revalidate, immutable; header_value() renders a deterministic value. Defaults to private (a secured page can't be silently made public); composes with fresh_when — the directives ride the 200 and the preserved 304 (0.6.0, issue #1344). See docs/guide/conditional-get.md |
When none of these fit, dropping to raw Axum (.merge()/.nest()/.layer())
or raw Diesel (&mut *db with diesel_async) is supported and fine — but only
after checking this table and docs/guide/.
| Concept | Name |
|---|---|
| Main library crate on crates.io | autumn-web |
| Rust import path | autumn_web:: |
| Workspace member directory | crates/autumn-web/ |
| CLI crate | autumn-cli |
| CLI binary | autumn |
| Proc macro crate | autumn-macros |
| Admin plugin crate | autumn-admin-plugin |
| S3 storage plugin crate | autumn-storage-s3 |
| Redis cache plugin crate | autumn-cache-redis |
| Search plugin crate | autumn-search |
| Billing plugin crate | autumn-billing |
| Main entry macro | #[autumn_web::main], not #[autumn::main] |
The name autumn is the CLI binary, not the framework crate. In code, import
from autumn_web::prelude::*.
Renaming the autumn-web dependency in Cargo.toml (web = { package = "autumn-web" }) — e.g. mid-upgrade, to depend on two versions in one crate —
just works: every macro resolves the real crate name automatically. For the
rare case where a crate hosts two differently-keyed copies at once (automatic
detection is then ambiguous), pass an explicit override to any attribute
macro: #[get("/x", crate = "autumn_web_05")].
my-app/
├── src/
│ ├── main.rs # AppBuilder, migrations, routes, jobs, tasks, plugins
│ ├── models.rs # Diesel models or #[model]
│ ├── schema.rs # Diesel table! definitions
│ ├── routes/ # #[get], #[post], #[ws], #[static_get] handlers
│ ├── jobs.rs # #[job] request-triggered background work
│ └── tasks.rs # #[scheduled] and #[task] operational work
├── migrations/
├── static/
├── Cargo.toml
├── autumn.toml
└── autumn-dev.toml # legacy profile file; [profile.dev] also works
Never hand-create a directory under
migrations/. Runautumn generate migration <Name>(orautumn schema diff --write-migration) and put your SQL in theup.sql/down.sqlit creates — including when you are writing every line of that SQL yourself. The generator's job is picking the version.App, framework and plugin migrations share one version space, keyed on the 14-digit prefix, so a hand-typed
20260831000000collides with whatever anyone else authored that day and one of the two silently never runs. The generator mints a fullYYYYMMDDHHMMSSfrom the clock. CI rejects a000000time component, a version that isn't a real UTC timestamp, and any duplicate (scripts/check-migration-versions.sh).
Declarative schema (
autumn schema). On a#[model(managed)]model,autumn schema diff --write-migrationderives the migration from the model and the snapshot. To rename, put#[renamed_from("old_name")]on the field, or on the model after#[model]. The diff then emitsALTER TABLE ... RENAME, not a drop plus an add. To diff against what the migrations really make, pass--dev-url <dev server URL>(or setAUTUMN_DEV_URL).--write-migrationalso writes the model'sdiesel::table!block insrc/schema.rs: do not edit a managed block by hand. To adopt a model, addmanaged, then runautumn schema diff --write-migration.autumn schema doctorreports a stalesrc/schema.rsblock (schema-rs-drift) and an unmanaged model that differs from its table (unmanaged-drift). For a referential action, write#[references(table = "users", on_delete = "cascade")](alsoon_update; valuescascade,restrict,set_null,set_default,no_action).set_nullandset_defaultneed anOption<_>field. The diff refuses a changed action on an existing foreign key. If the database already has the action, declare it on the model. Seedocs/guide/declarative-schema.md.
Keep every Diesel
table!and#[model]at 32 columns or fewer. A 33rd column in one declaration forces diesel's64-column-tablesfeature, and Cargo turns it on for the whole build: every crate that uses diesel then compiles slower and needs more memory (one crate measured 1.16 GB / 1m18s at 32, 2.92 GB / 2m04s at 64 and 9.95 GB / 8m16s at 128). The cap is per declaration, not per database table: declare a wide table in halves, the second with#[sql_name = "<table>"], and put each#[model(table = …)]on one half. EveryNOT NULLcolumn without a default goes in the half you insert through.autumn buildwarns about a wide declaration but does not fail.autumn schema widthlists them and exits non-zero. Seedocs/guide/table-width.md.
[package]
name = "my-app"
version = "0.1.0"
edition = "2024"
[dependencies]
autumn-web = { version = "0.11", features = ["db", "htmx", "maud"] }
diesel = { version = "2", features = ["postgres"] }
diesel-async = { version = "0.10", features = ["postgres"] }
diesel_migrations = "2"
maud = { version = "0.27", features = ["axum"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
validator = { version = "0.21", features = ["derive"] }
Use pq-sys = { version = "0.7", features = ["bundled_without_openssl"] }
when avoiding a system libpq install.
Dates and times are jiff values that autumn_web::time re-exports: add no
date crate and leave diesel's chrono feature off. A #[model] field is
Timestamp (TIMESTAMPTZ), civil::DateTime (TIMESTAMP), civil::Date
(DATE) or civil::Time (TIME), or an Option of one; a chrono type
there is a compile error whose hint names the jiff type. Read "now" from the
Clock extractor (clock.now()) or autumn_web::time::ambient_now(), never
Timestamp::now(). A hand-written Diesel query binds a jiff value through
autumn_web::db::AsSqlTime (posts::created_at.lt(cutoff.as_sql_time())) or
the SqlTimestamp / SqlDateTime / SqlDate / SqlTime wrappers; a
hand-derived Queryable field takes
#[diesel(deserialize_as = autumn_web::db::SqlDateTime)] (and so on).
For a reddit-clone-style app with live feeds, file uploads, and blob variants:
autumn-web = { version = "0.11", features = [
"mail", # transactional email + mailer previews
"ws", # WebSocket routes, SSE, broadcast channels
"presence", # Presence extractor for online-user tracking
"storage", # BlobStore + Blob columns + signed URLs
"multipart", # multipart/form-data file uploads
"redis", # Redis sessions, channels, and job backend
"variants", # blob.variant(...) image transformation
] }
Defaults: maud, htmx, tailwind, db, cache-moka.
| Feature | Purpose |
|---|---|
ws | WebSocket routes, SSE helpers, local/Redis broadcast channels |
flash | Flash messages |
multipart | Multipart uploads |
redis | Redis sessions, channels, jobs, webhook replay, and integration points |
oauth2 | OAuth2/OIDC helpers and autumn generate auth --oauth scaffolding; implies jwt |
jwt | Default-on. JWT verification (jsonwebtoken): the jwt tenancy source and the OIDC id_token check |
push | Default-on. Web Push (autumn_web::push, WebPush, [push]) over p256 |
openapi | OpenAPI route metadata and spec generation |
mcp | Project typed JSON endpoints as MCP tools; implies openapi |
webmcp | Routes (#[api_doc(webmcp)] + mount_webmcp()) and forms (webmcp::form_tool) as tools for the agent in the user's browser; implies mcp and htmx. Guide: docs/guide/webmcp.md |
markdown | Markdown rendering with frontmatter and static-site support, plus the safe user-submitted rich-text path (render_user_content, rich_text_area) — see rich text |
constela | Parse, validate and server-render Constela documents — the constrained JSON UI language — so an app can serve an interface a language model generated; implies maud, see generated UI |
telemetry-otlp | OpenTelemetry OTLP export |
test-support | Testcontainers-backed TestApp, TestClient, and TestDb |
i18n | Locale extractor, compile-time checked translations, and opt-in locale-prefixed routing |
storage | BlobStore, local storage, Blob columns, signed URLs |
mail | Transactional email, mailer macros, previews, deferred delivery |
seed | SeedContext for seed binaries |
system-info | Optional system information in actuator surfaces |
presence | Per-topic membership tracking with join/leave events; implies ws |
offline-sync | Offline-first local SQLite store plus a background sync engine |
collab | #[collaborative] text fields merged by an in-tree CRDT, with live sessions over the channel/presence seams — see collaboration |
For S3 storage add autumn-storage-s3 = "0.11"; storage-s3 is no longer an
autumn-web feature. For a shared Redis cache add autumn-cache-redis = "0.11".
For keyword + vector search with lifecycle-synced indexes add autumn-search.
mod jobs;
mod routes;
mod schema;
mod tasks;
use autumn_web::migrate::{embed_migrations, EmbeddedMigrations};
use autumn_web::prelude::*;
const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
#[autumn_web::main]
async fn main() {
autumn_web::app()
.migrations(MIGRATIONS)
.routes(routes![routes::index, routes::create_post])
.tasks(tasks![tasks::refresh_rankings])
.jobs(jobs![jobs::send_welcome_email])
.run()
.await;
}
Use .one_off_tasks(one_off_tasks![...]) for #[task] handlers invoked by
autumn task <name>.
#[autumn_web::main] takes optional arguments that tune the tokio runtime it
builds — flavor ("multi_thread", the default, or "current_thread"),
worker_threads, max_blocking_threads, thread_name, thread_stack_size,
thread_keep_alive = "30s", and configure = path::to::fn, a
fn(&mut tokio::runtime::Builder) run after the others as the escape hatch for
Builder methods the list doesn't name (0.8.0). Numeric arguments take
expressions, not only literals. Reach for them only with a measurement in hand:
with no arguments the runtime is tokio's defaults, and the job runner,
scheduled tasks, and mailer share it, so an undersized worker count throttles
those too. An unknown, repeated, or zero-valued argument — or worker_threads
under flavor = "current_thread", where it would do nothing — is a compile
error. See docs/guide/getting-started.md "Tuning the Tokio runtime".
| Method | Purpose |
|---|---|
.routes(routes![...]) | Register route handlers |
.static_routes(static_routes![...]) | Register #[static_get] routes for autumn build |
.tasks(tasks![...]) | Register scheduled #[scheduled] work |
.jobs(jobs![...]) | Register request-triggered #[job] work |
.one_off_tasks(one_off_tasks![...]) | Register operational #[task] commands |
.migrations(MIGRATIONS) | Register embedded Diesel migrations |
.migrations_for(MigrationScope::Control | Shards, MIGRATIONS) | Register a set for the control database only, or for the shards and fleet files only. Do not run autumn migrate on such an app; use AUTUMN_MIGRATE=1 |
.plugin_migrations(name, MIGRATIONS) | Register a plugin's embedded Diesel migrations (named; version collisions with other sources auto-resolve) |
.plugin(plugin) / .plugins((...)) | Install first- or third-party plugins |
.plugin_assets(&ASSETS) | Serve a plugin crate's JS/CSS/fonts (PluginAssets, from plugin_assets!("ns") or PluginAssets::from_files) at content-hashed immutable URLs under /static/_plugins/<ns>/, with SRI; call it from Plugin::build. Never hand-roll a fixed-URL asset route in a plugin (see docs/guide/plugin-assets.md) |
.openapi(config) | Configure OpenAPI generation |
.policy::<R, _>(policy) / .scope::<R, _>(scope) | Register repository API authorization |
.scoped(prefix, layer, routes) | Mount a scoped route group |
.merge(router) / .nest(path, router) | Attach raw Axum routers |
.layer(layer) | Add Tower middleware |
.error_pages(renderer) / .exception_filter(filter) | Customize error rendering |
.with_config_loader(loader) | Replace TOML + env config loading |
.with_pool_provider(provider) | Replace database pool creation |
.with_session_store(store) | Replace sessions |
.with_channels_backend(backend) | Replace broadcast channels |
.with_blob_store(store) | Install a file storage backend |
.with_cache_backend(cache) | Install a cache backend |
.with_mail_delivery_queue(queue) | Install durable deferred mail |
.with_mail_suppression_store(store) | Install a durable bounce/complaint suppression backend (0.6.0; in-memory default auto-wired otherwise) |
.with_audit_sink(sink) | Install structured audit sink |
.listeners(listeners![...]) | Register #[listener] event listeners (0.6.0) |
.static_gate(layer) | Middleware that also guards #[static_get] pre-render (0.6.0; has_static_gate::<L>(), get_static_gate_types(), TestApp::static_gate mirror it) |
.with_shard_router(router) | Install a shard router for [[database.shards]] (0.6.0) |
.seo_source(source) | Register a SitemapSource for dynamic /sitemap.xml entries (0.7.0) |
.run() | Launch the server |
#[get("/posts")]
async fn list(db: Db) -> AutumnResult<Markup> { /* ... */ }
#[get("/posts/{id}")]
async fn show(Path(id): Path<i64>, db: Db) -> AutumnResult<Markup> { /* ... */ }
#[post("/posts")]
#[secured]
async fn create(db: Db, Valid(Form(input)): Valid<Form<CreatePost>>) -> AutumnResult<Markup> {
/* ... */
}
#[patch("/posts/{id}")]
#[secured]
async fn patch(Path(id): Path<i64>, db: Db) -> AutumnResult<Markup> { /* ... */ }
#[delete("/posts/{id}")]
#[secured]
async fn delete_post(Path(id): Path<i64>, db: Db) -> AutumnResult<Markup> { /* ... */ }
#[static_get("/about")]
async fn about() -> Markup { html! { h1 { "About" } } }
#[ws("/socket")]
async fn ws() -> impl autumn_web::ws::WsHandler {
|mut socket: autumn_web::ws::WebSocket| async move {
while let Some(Ok(msg)) = socket.recv().await {
if let autumn_web::ws::Message::Text(text) = msg {
socket.send(autumn_web::ws::Message::Text(text)).await.ok();
}
}
}
}
Route functions are collected with routes![...]. Static routes also need
static_routes![...] so autumn build can pre-render them.
Declare the Content-Type on a #[static_get] route that is not HTML
(0.8.0, #1832). autumn build records the type each handler's response
declares into dist/manifest.json, and the static-first middleware serves that
value verbatim — it no longer guesses from the route slug, which it had to do
because every non-root route is stored as <route>/index.html. So the handler's
own header is the whole contract:
#[static_get("/sitemap.xml")]
async fn sitemap() -> impl IntoResponse {
([(header::CONTENT_TYPE, "application/xml")], build_sitemap())
}
#[static_get("/feed")] // extensionless — no extension to infer from
async fn feed() -> impl IntoResponse {
([(header::CONTENT_TYPE, "application/rss+xml")], build_feed())
}
Autumn records the type you declare. axum attaches one to every response, but
for String (text/plain; charset=utf-8) and Vec<u8>
(application/octet-stream) it comes from the return type, not from you — so on
a route whose own extension says otherwise (/theme.css, /logo.png) those two
exact values are replaced by the extension type (recorded, so ISR still guards
the route). That stops a -> String stylesheet from being served as plain text and dropped by nosniff.
The two are indistinguishable in the response. To keep one on such a route,
declare it on the attribute:
#[static_get("/logo.png", content_type = "application/octet-stream")].
That type is recorded and served as written, and it also covers routes whose
type is hard to set through IntoResponse. It applies to the pre-rendered page
only. To force a download prefer Content-Disposition: attachment. Extensions outside Autumn's
asset table (.pdf, .zip) are unaffected.
Return Markup (or Html<String>) for HTML pages: on an extensionless route a
handler returning a bare String declares text/plain; charset=utf-8, which is
what will now be served.
A dist/ built before this release records nothing and keeps its previous derived
type until the next autumn build. Such a dist/ also has no ISR type guard on
/theme.css-style routes until you rebuild. ISR refuses a regeneration whose handler
declares a different type than the manifest recorded, so a stale-but-correctly
-typed page is served instead of fresh bytes under the wrong header — re-run
autumn build after changing a route's type.
Route-level SEO defaults (issue #1182, 0.7.0): declare
per-page meta tag values once on the route with a seo(...) argument instead of
rebuilding a SeoMeta in every handler. SeoMeta is an extractor, so a handler
that takes one receives a builder pre-populated with the declared values:
use autumn_web::seo::SeoMeta;
#[get("/about", seo(title = "About • My Blog", description = "Learn about us"))]
async fn about(seo: SeoMeta) -> Markup { html! { head { (seo.render()) } } }
// Static default on the attribute, dynamic fields filled in by the handler.
// The builder is consuming, so the handler's value wins for the keys it
// touches while the untouched attribute keys survive.
#[get("/posts/{slug}", seo(og_type = "article"))]
async fn show(Path(slug): Path<String>, seo: SeoMeta, db: Db) -> AutumnResult<Markup> {
let post = Post::find_by_slug(&slug, db).await?;
let seo = seo.title(format!("{} • Blog", post.title));
Ok(layout_with_seo(seo, html! { /* ... */ }))
}
Keys mirror the SeoMeta builder: title, description, canonical,
og_title, og_description, og_image, og_type, og_url, twitter_card,
twitter_title, twitter_description, twitter_image, robots. Values must
be string literals; an unknown or repeated key is a compile error. #[static_get]
accepts the same argument, so pre-rendered pages carry the tags. The extractor
never fails — on a route without seo(...) it yields an empty builder. Note the
attribute supplies values, not markup: the handler still emits them, normally
via seo.render() inside the layout's <head>.
sitemap.xml and robots.txt (0.7.0): set [seo] base_url = "https://example.com" in autumn.toml and the framework mounts GET /robots.txt and GET /sitemap.xml. robots.txt defaults by profile
(dev/test → Disallow: /, prod → Allow: /); override with [seo.robots] allow_all, add lines with additional_rules, and pin the Sitemap: URL with
sitemap_url (otherwise derived from base_url). The sitemap gets one entry
per concrete #[static_get] path for free; every other URL comes from a
SitemapSource registered with .seo_source(...):
use autumn_web::seo::{SitemapEntry, SitemapSource};
impl SitemapSource for PostSitemap {
fn entries(&self) -> Pin<Box<dyn Future<Output = Vec<SitemapEntry>> + Send + '_>> {
Box::pin(async {
vec![SitemapEntry::new("https://example.com/posts/hello")
.lastmod("2026-05-01")
.changefreq(autumn_web::seo::SitemapChangefreq::Weekly)]
})
}
}
Traps: entries() is awaited once, while the router builds, and the body is
cached — the sitemap is a start-up snapshot, so an app needing live entries must
register its own /sitemap.xml route (the framework detects the collision, warns,
and mounts neither of its own SEO routes). A source cannot use the Db extractor
(no AppState yet) — build a pool with autumn_web::db::create_pool(&config.database).
seo(robots = "noindex") drops a route from the sitemap only for #[static_get]
paths the framework derived itself; SitemapSource entries are never filtered, so
omit the URL from the source instead. sitemap_xml truncates past 50,000 URLs.
autumn build writes both files into dist/. Guide: docs/guide/seo.md; runnable
example: examples/reddit-clone (src/seo.rs, autumn.toml).
Schema.org JSON-LD (unreleased): build structured data with
autumn_web::json_ld::JsonLd instead of writing a <script> by hand.
JsonLd::new("Recipe") is a top-level node (with @context),
JsonLd::node("Person") a nested one; .set(name, value) takes any
Serialize (jiff dates write ISO 8601, null removes the property),
.set_opt skips None, JsonLd::graph([...]) shares one @context.
(node) in html! (or .render()) writes the <script type="application/ld+json"> element with <, >, & escaped, so a user
value cannot close the script; to_json_unescaped() is the opt-out for non-HTML
output. SeoMeta::new().json_ld(node) renders it after the meta tags. For a
resource, autumn generate scaffold Recipe --schema-org Recipe (no fields →
the type's Google-required and recommended properties become the fields) writes
a json_ld(row) fn the show view renders; columns bind by name
(date_published → datePublished, offers_price → offers.price),
--schema-org-map cost=offers.price binds the rest. autumn schema-org show <Type> lists properties; autumn schema-org audit <URL|FILE|DIR> [--strict]
checks pages (exit 1 on errors). Guide: docs/guide/schema-org.md.
Agent readiness (AEO, on by default): [aeo] in autumn.toml. No code:
Accept: text/markdown on an HTML page returns Markdown (Vary: Accept); the
homepage sends agent Link headers; the router fallback serves /robots.txt
(AI crawler groups + Content-Signal), /llms.txt, the agent skills index,
the ARD manifest, and, when the app has them, the MCP server card, the RFC 9727
API catalog, OAuth metadata, and /auth.md. An app route at the same path
wins. Add (autumn_web::aeo::webmcp::head_tags(None, csrf_token)) to the layout <head>
for WebMCP. Register skills with .agent_skill(AgentSkill::parse(..)?). Price
a route with [[aeo.paid_routes]] + [aeo.x402] (x402; MPP x-payment-info
in /openapi.json). Sign outbound calls with
RequestBuilder::sign_web_bot_auth. autumn aeo dns prints DNS-AID records.
Traps: set [seo] base_url in prod (else documents use the request Host and
are no-store); [aeo] enabled = false turns it all off and restores the
/robots.txt 404. Guide: docs/guide/aeo.md.
Locale-prefixed routing (issue #1251, 0.7.0): set
[i18n] locale_prefix_enabled = true in autumn.toml (default false) and
every route registered via routes![...] becomes reachable under
/{locale}/... for each supported_locales entry — zero duplicated route
definitions. An unknown {locale} 404s; a bare, non-prefixed path
308-redirects to the negotiated locale's prefixed path, preserving the query
string; the URL segment outranks cookie/session/Accept-Language for the
existing Locale extractor (no handler changes). [i18n] locale_prefix_exclude = ["/api", "/actuator"] keeps machine routes
unprefixed. Use locale_switcher(path, locale.tag(), supported_locales) (and
the lower-level localized_path(path, locale)) from
autumn_web::widgets to render a path-preserving language switcher, and
SeoMeta::hreflang_alternates(locale_alternates(base_url, path, default_locale, supported_locales)) to emit hreflang <link> tags for the
current page's localized variants.
Duplicate-route preflight (issue #1012, 0.6.0): two
handlers that resolve to the same (method, path) after .scoped(...) prefix
resolution — including #[repository]-generated API routes — fail app build
with RouterBuildError::DuplicateUserRoute { method, path, existing, incoming }
BEFORE any router mounts, instead of the previous axum::MethodRouter::merge
startup panic. Distinct methods on the same path (GET /admin + POST /admin)
still merge cleanly. Opaque .merge(...)/.nest(...) routers can't be
introspected — a non-empty opaque table emits a tracing::warn!
("check skipped") rather than a false pass. See
docs/guide/getting-started.md "Route collision diagnostics".
markdown)MarkdownRegistry parses .md files with +++ TOML frontmatter (title
required; description/order default to ""/0) and pairs with
#[static_get] so one handler serves live requests in dev and pre-renders in
autumn build. Build it once in a OnceLock from from_embedded(&[MarkdownSource { slug, content: include_str!(...) }]) or from_dir(path) (non-recursive);
pages sort by (order, slug).
async fn doc_params(_router: axum::Router) -> Vec<StaticParams> {
docs().static_params() // one entry per page, keyed "slug"
}
#[static_get("/docs/{slug}", params = doc_params)]
async fn show(Path(slug): Path<String>) -> AutumnResult<Markup> {
let page = docs().get(&slug).ok_or_else(AutumnError::not_found)?;
let out = render(&page.body, RenderOptions::default());
Ok(layout(&page.frontmatter.title, html! { (PreEscaped(&out.html)) }))
}
static_params() keys every entry "slug". If the route names its parameter
anything else — #[static_get("/docs/{page}", …)] — use
static_params_for("page") (0.7.0, issue #743); a mismatched
key leaves {page} unsubstituted and the SSG build panics on the invalid URI.
render returns { html, toc } and injects heading anchors. Anchors are
document-unique: each heading keeps the slug its own text produces, and only
repeats are suffixed -1, -2, … A suffix never takes a slug another heading
owns by name, so ## Example / ## Example / ## Example 1 yields example,
example-2, example-1 — deep links stay put. Headings with no alphanumeric
characters get no id at all.
render is for trusted, build-time content only — it applies no URL-scheme
allowlist. For anything a request body carried in, use render_user_content
(see rich text). The framework ships no docs
theme; compose out.html/out.toc into your own Maud layout. Worked example:
examples/wiki (src/routes/docs.rs + content/*.md).
constela)To serve an interface a model wrote, do not ask it for HTML — that is RCE
with extra steps. Ask it for a Constela
document: a constrained JSON UI language with no way to spell a function call or
an event handler. autumn_web::constela parses it, validates it, and renders it
to Markup.
use autumn_web::constela::{Document, Limits, RenderContext};
let document = Document::parse(&generated_json, &Limits::default())?; // validates too
let ctx = RenderContext { state: document.initial_state(), ..Default::default() };
let ui = document.render(&ctx)?; // ui.body is Markup; ui.portals/title/meta too
Document::parse is the only way in besides from_program, and both validate,
so holding a Document proves the checks ran. Failure returns
ConstelaError; err.to_json() is a [{path, code, message}] array naming
every fault at once — feed it straight back to the generator as a repair
prompt rather than retrying blind. A ConstelaError surfaces as 422.
Safety is an allowlist, not a denylist (constela::policy): tags, attributes
(every on* rejected, style absent), and URL schemes, with computed URLs
re-checked at render time and all output escaped by construction. Element ids
are rewritten with RenderContext::id_prefix (c- by default) so a generated
fragment cannot clobber the host page — give each fragment its own prefix when a
page embeds several. Same-document fragment links are rewritten to match
(href="#x" → href="#c-x"), so in-fragment navigation keeps working.
There is no client runtime and no generated JavaScript. Interactivity is
server-side over htmx: event bindings render as data-constela-on-{event}, and
document.dispatch(action, &mut state, &payload)? runs the pure state steps
(set, update, setPath, if) against state your app owns. Browser-side
steps come back on Dispatched::effects rather than being performed — running a
model-authored fetch server-side would be SSRF by construction, so your app
decides against its own allowlist. Dispatch stops at the first effect
(Dispatched::suspended_at says where): an effect can bind a result later
steps read, and the server has no value to bind, so running on would write
null over good state.
Bound untrusted input with Limits (document: bytes/depth/nodes) and
RenderLimits (expansion: depth/nodes/max_each_items/max_output_bytes).
max_output_bytes covers the body plus portals and what a single expression
may build; max_depth also caps the shape of state on every mutation, since
state persists between dispatches. See
generated UI.
Autumn uses Diesel + diesel-async for Postgres. Primary keys are i64 /
BIGSERIAL; do not use UUIDs as primary keys. Add UUIDs as separate columns
when external correlation needs them.
// #[model] and #[repository] are NOT in prelude — use qualified paths:
#[autumn_web::model(table = "posts")]
#[derive(Validate)]
pub struct Post {
pub id: i64,
#[validate(length(min = 1, max = 500))]
pub title: String,
pub body: String,
}
Repository-generated APIs in production must either declare a policy or be explicitly acknowledged in config:
#[autumn_web::repository(Post, api = "/api/posts", policy = PostPolicy, scope = PostScope)]
pub trait PostRepository {}
[security]
allow_unauthorized_repository_api = true # only when intentional
Declare #[belongs_to] / #[has_many] / #[has_one] on a #[model] for
batched eager loading — no N+1, no lazy loading (un-preloaded access returns
typed NotLoaded, never issues SQL):
#[autumn_web::model]
#[belongs_to(User, fk = author_id)]
#[has_many(Comment)]
#[has_many(Tag, through = post_tags)] // many-to-many join table
pub struct Post {
#[id]
pub id: i64,
pub author_id: i64,
pub title: String,
}
let posts = repo.find_all().await?;
let posts = repo.preload(posts, Post::preload().author().comments().tags()).await?;
for post in &posts {
let author = post.author()?; // Result<Option<&Preloaded<User>>, NotLoaded>
let comments = post.comments()?; // Result<&[Preloaded<Comment>], NotLoaded>
let tags = post.tags()?; // Result<&[Arc<Preloaded<Tag>>], NotLoaded>
}
through = <join_table> on #[has_many] declares a many-to-many
association: join columns default to {source}_id / {target}_id
(fk = ... / target_fk = ... to override), the macro emits the join
table's diesel::table! itself (only a migration with a composite primary
key on both columns is needed — no schema.rs entry), and the repository
gets add_{singular} / remove_{singular} / set_{plural} mutation
helpers, each idempotent:
repo.add_tag(post_id, tag_id).await?; // ON CONFLICT DO NOTHING
repo.remove_tag(post_id, tag_id).await?; // no-op if unlinked
repo.set_tags(post_id, &tag_ids).await?; // replace-all, one transaction
See examples/reddit-clone (Post ↔ Tag via post_tags) for a full
worked example, and docs/adr/0008-associations-and-eager-loading.md for
the design.
Never hand-roll a votes/likes table. #[votable(by = <Reactor>)] on a
#[model] declares a (reactor, target)-unique edge table plus a
denormalised aggregate column on the target (0.7.0, #1362):
#[autumn_web::model]
#[votable(by = User, aggregate = sum)] // or: aggregate = count, name = like
// — always BELOW #[model]
pub struct Post {
#[id]
pub id: i64, // must be i64
pub score: i64, // the aggregate column, must be i64
}
aggregate = sum (default) → edge value SMALLINT, target score = SUM(value); aggregate = count → no value column, target {name}_count = COUNT(*). Defaults: name = vote, table = pluralize(name), reactor_fk = {snake(by)}_id, target_fk = {snake(Model)}_id, value_column = value,
column = score / {name}_count — each overridable. At most one #[votable]
per model. The edge table is the app's migration to write, and its composite
UNIQUE (reactor_fk, target_fk) is load-bearing (it is the ON CONFLICT
arbiter), as is a CHECK on the value column — react() does not validate
value, so never bind it from a request. The aggregate column must be BIGINT NOT NULL DEFAULT 0; both FKs should be BIGINT NOT NULL (a nullable target FK
is tolerated — the unique constraint then covers only the non-NULL rows,
which are exactly the ones react() writes).
The model emits a {Model}Reactions trait blanket-implemented for that
model's repository — import it as _, no repository attribute needed:
use crate::models::PostReactions as _;
let r = posts.react(user_id, post_id, 1).await?; // count mode: no `value` arg
r.value; // Option<i16> — this reactor's reaction AFTER the call
r.aggregate; // i64 — the newly persisted score, exact as of commit
r.outcome; // ReactionOutcome::{Inserted, Flipped, Removed}
let mine: Option<i16> = posts.reaction_of(user_id, post_id).await?;
react() is a race-safe toggle: same value again removes the edge, a
different value flips it, a new one inserts it — and the aggregate is
recomputed from ground truth and persisted in the same transaction under a
FOR NO KEY UPDATE lock on the target row, so concurrent reactions converge to
at most one edge per pair and a reader never sees edge/aggregate disagreement.
A toggle is not idempotent — never blindly retry a timed-out call.
Soft-deleted targets are NotFound. reaction_of() is a read and is
replica-eligible (no read-your-writes pin — re-render from the Reaction the
write returned). Like the m2m helpers, react() takes its own pooled
connection — never hold a Db extractor across the call, or the handler needs
two connections at once and deadlocks at pool-size concurrency. Pair it with
the reaction_controls widget (see the widgets section), threading the CSRF
token so the no-JS form POST works. See docs/guide/votable.md and examples/reddit-clone
(src/routes/votes.rs).
Never hand-roll a comments table. #[commentable] on a #[model] is
Autumn's fifth association kind — the polymorphic one (0.7.0, #1367). belongs_to/has_many/has_one/through pin the child
to one parent table; this does not:
#[autumn_web::model]
#[commentable(by = User, author_name = username)] // always BELOW #[model]
pub struct Post {
#[id]
pub id: i64, // must be i64
#[default]
pub comment_count: i64, // the counter column, must be i64
}
One comments(commentable_type, commentable_id, parent_id, author_id, body, created_at, deleted_at) table serves EVERY commentable model — adding comments
to a second model is that attribute plus a comment_count column, nothing
else. Defaults: type_name = <Rust type name>, table = comments,
counter_cache = comment_count (or false), max_depth = 5 (top level is
depth 0), max_body = 10000 bytes; author_name is unset by default (the
framework will not guess a column, and a scaffolded User carries an email).
Renaming the struct changes type_name and orphans existing rows — pin it
first. autumn generate scaffold post title:string comments:commentable
emits the table (once per project), the column, and the attribute. If the
project already has a plain comments table (for example, a scaffolded
Comment resource), the command stops, writes no file, and names the missing
columns. Rename or drop that table in a migration, point its model elsewhere
(#[model(table = "...")]) or remove it, then run it again.
The model emits a {Model}Comments trait blanket-implemented for that model's
repository — import it as _:
use crate::models::PostComments as _;
let c = posts.add_comment(post_id, author_id, "first!", None).await?;
let r = posts.add_comment(post_id, author_id, "…", Some(c.id)).await?; // reply
let thread: Vec<CommentNode> = posts.comment_thread(post_id).await?; // nested
let removed: usize = posts.delete_comment(post_id, c.id).await?; // + subtree
let live: i64 = posts.recompute_comment_count(post_id).await?; // drift repair
comment_thread is ONE query whatever the depth (nested in Rust, stable
(created_at, id) order, soft-delete aware). add_comment probes and
row-locks the parent first — commentable_id has no foreign key, so that
probe IS the referential check: an unknown/soft-deleted/foreign-tenant parent
is 404, a reply_to on a different record or past max_depth is 422, and
comment_count moves via the counter-cache primitive in the same
transaction. delete_comment is idempotent and decrements by the rows it
actually removed. With soft_delete = false it refuses (422) a subtree that
has a reply on another record. Like react(), these take their own pooled
connection — never hold a Db extractor across the call.
Mount the routes ONCE for the whole app; the registry dispatches on the type segment, so a third commentable model needs no route:
.nest("/comments", autumn_web::commentable::router(Default::default()))
// A nest is opaque to `autumn routes audit`; declare its two routes, or the audit fails:
.declare_plugin_routes(autumn_web::commentable::route_infos("/comments"))
// GET/POST /comments/{commentable_type}/{parent_id}
The router authorizes the tenant, never the record — an app with private or
role-gated records MUST set CommentsConfig::authorize(|access| ...), or skip
the router and call the helpers from its own authorized handlers. Build a host
page's own thread with commentable::thread_dom_id/thread_action, or the
router's re-render lands on a different element and every htmx swap after the
first one misses.
Render with the no-JS comment_thread widget (see the widgets section),
threading the CSRF token and return_to. See docs/guide/commentable.md and
examples/reddit-clone (Post and Subreddit, zero comment routes).
Never hand-write count + 1 on a parent. counter_cache on a child's
#[belongs_to] maintains a denormalised {child}_count column on the parent
(0.7.0, #1325):
#[autumn_web::model]
#[belongs_to(Post, counter_cache)] // -> posts.comment_count
pub struct Comment {
#[id]
pub id: i64,
pub post_id: i64,
}
The child's repository then maintains it on save, update, delete_by_id,
restore, purge, every bulk variant, and dependent(...) cascades — inside
the same transaction as the row mutation, with a single atomic UPDATE posts SET comment_count = comment_count + $1. Never a read-modify-write, so N
concurrent inserts yield exactly N. Soft-deleting decrements (the count reflects
live rows) and restore puts it back; reassigning the foreign key moves the
count from the old parent to the new one; a leg whose FK did not change issues
no statement at all.
The column defaults to {snake(child)}_count — singular, matching
#[votable(aggregate = count)] — and is overridable with counter_cache = "<column>". counter_cache_tenant = "<column>" confines every delta to the
caller's tenant (both tables must carry that column); without it no tenant
predicate is emitted. parent_pk = "<column>" names the parent's primary-key
column when it is not id (a renamed #[id] or #[diesel(column_name)]) —
the child cannot see the parent's fields, so it is never inferred (#2662).
#[belongs_to(Post, references = "<column>")] names that key once for the
leg (0.10.0, #3033): the preload loader, counter cache and derivations inherit it, and
a conflicting parent_pk is a compile error. A #[model] may use any
primary-key column; #[repository] still assumes id. parent_pk is a
belongs_to option only — on a has_many, on
a through = join table, with a non-identifier column, with two legs resolving
onto one parent column, or on a composite #[id], it is a directed compile
error.
The column is the app's migration to write (ALTER TABLE posts ADD COLUMN comment_count BIGINT NOT NULL DEFAULT 0 — NOT NULL DEFAULT 0 is load-bearing,
since NULL + 1 is NULL), or autumn generate scaffold … --belongs-to Post --counter-cache emits it. Every counter-cached repository also gains
recompute_counter_caches() / recompute_counter_caches_for(parent_id) — an
idempotent rebuild from the source of truth, which is both the backfill for a
table adopting the column and the repair for drift. Applications that insert
with raw Diesel can opt in with
counter_cache_after_insert_by_id(conn, Comment::counter_caches(), id). Two
paths are not yet maintained: a derived delete_by_<field> and
find_or_create_by_<field> — recompute is the remedy. See
docs/guide/counter-cache.md.
For a filtered or weighted count, use #[derivation] on the child, below
#[model] (0.8.0, #1769): #[derivation(Post, column = "published_comment_count", filter = published)], or #[derivation(Post, column = "visible_score", transform = sum(score), filter = published && score > 0)].
It is a superset of counter_cache (which is the unfiltered case) and rides the
same mutation paths and same-transaction, atomic set-based SQL, including bulk
paths, soft delete/restore, cascades, re-parenting and a filter flip on an
unchanged parent. The filter grammar is field, !field, field OP <int|bool| string literal>, field.is_some()/is_none(), a && b and parentheses over
bool/integer/String fields and their Option forms; each filter is lowered
to both Rust and SQL, and string ordering comparisons and float literals are
compile errors. Other keys, each at most once: fk, parent_table (for a
parent that overrides its table), parent_pk (for a parent whose primary key
is not id, #2662), tenant, name. The parent column is the
app's migration (BIGINT NOT NULL DEFAULT 0); the _autumn_derivations state
table ships as a framework migration and is applied automatically. Each
derivation is content-addressed, so a changed filter enqueues a resumable,
idempotent backfill at boot (run_backfill, BackfillOptions; each batch locks
its state row, so replicas take turns), and GET /actuator/derivations
(sensitive-gated) reports hashes, backfill state, checkpoint and drift (capped
at DRIFT_SCAN_LIMIT, drift_error per derivation, unregistered for a
leftover state row), with recompute(conn, name) as the repair. A duplicate
parent column or derivation name stops the boot. See
docs/guide/derivations.md.
Deleting a parent can cascade to its children in one transaction — declare
dependent(...) on the parent's #[repository] instead of hand-writing the
child cleanup (0.6.0):
#[autumn_web::repository(Post,
dependent(CommentRepository, fk = "post_id", on_delete = destroy))]
pub trait PostRepository {}
on_delete = destroy (soft-delete-aware, fires each child's hooks; since
0.6.0 this recurses into each child's own dependent, cascading
into grandchildren — see the recursive/bulk/model-side note below) |
delete_all (bulk delete, no child hooks) | nullify (set the FK null) |
restrict (probe for referencing rows before mutating; errors cannot delete: dependent N row(s) … if any still exist). The generated delete_by_id loads and
locks the parent, applies every declared action, then deletes the parent — all in
a single transaction (Part of #1369). See docs/guide/repositories.md.
Since 0.6.0 the cascade is recursive and bulk-aware, and can be declared on the model instead of the repository (0.6.0, issues #1738, #1739, #1740):
destroy now recurses — each destroyed child runs
its OWN dependent(...) before its row is removed, so a Post -> Comment -> Reply graph clears Reply rows too, all in one transaction. A self- or
mutually-referential graph terminates via a (table, id) cycle guard rather
than looping; delete_all stays single-level by design (issue #1739).delete_many. The generated delete_many runs the same
restrict/destroy/delete_all/nullify cascade per affected parent inside its
transaction — restrict probes first (a 409 rolls the whole batch back) — so
bulk-deleting parents no longer orphans or FK-errors dependent children
(issues #1740, #1787).#[has_many(Comment, dependent = destroy)] (or
on_delete = destroy). The repository codegen consults this at run time (via
a generated Model::dependents()) when no repository-side dependent(...) is
present; the repository attribute wins when both are declared. Ships for
destroy, delete_all, nullify, and restrict, grandchild recursion and
the delete_many bulk path included. When both a repository dependent(...)
and a model-side #[has_many(..., dependent=...)] are declared the repository
attribute still wins, but a debug-only tracing::warn! (emitted in
debug_assertions builds) now surfaces the silently-inert model-side
declaration instead of dropping it without a trace (issue #1788).
dependent/on_delete on a through = <join_table> association is a compile
error (issue #1738).See docs/guide/repositories.md.
#[state_machine]Never hand-roll status-transition validation. Declare valid transitions on the model field; the macro generates the transition table and enforcement:
#[autumn_web::model]
pub struct Order {
#[id]
pub id: i64,
pub amount: i64,
#[state_machine(transitions(
pending -> processing,
processing -> shipped: "can_ship", // quoted guard method name
processing -> cancelled,
shipped -> delivered,
))]
pub status: String,
}
impl Order {
fn can_ship(&self) -> bool { self.amount > 0 } // guard: &self -> bool
}
For a field named status this generates on the struct:
| Item | Signature |
|---|---|
can_transition_status_to | (&self, target: &str) -> bool — edge exists and guards pass |
transition_status_to | (&self, target: &str) -> AutumnResult<String> — Ok(target) or a 400 bad_request error |
__AUTUMN_SM_STATUS_TRANSITIONS | &'static [(&'static str, &'static str, Option<&'static str>)] — (from, to, guard) edge list for UI/API metadata |
Rules: String fields only; state and guard names are plain identifiers
(in_progress, not in-progress); guards are quoted names of &self -> bool
methods on the model; multiple #[state_machine] fields per model are fine
(each gets its own {field}-named methods).
The idiomatic enforcement point is a repository before_update hook — this
replaces any hand-written status match block:
async fn before_update(
&self,
_ctx: &mut MutationContext,
draft: &mut UpdateDraft<Order>,
) -> AutumnResult<()> {
if draft.after.status != draft.before.status {
// Guards must see the proposed content, but the edge lookup needs
// the *current* status — clone after, restore the before-status:
let mut proposed = draft.after.clone();
proposed.status = draft.before.status.clone();
proposed.transition_status_to(&draft.after.status)?;
}
Ok(())
}
Instead of inline transitions(...), a field can reference a reusable
#[lifecycle] enum — #[state_machine(lifecycle = OrderState)] — whose typed
edges become the field's transition table (#1911/#1916). #[lifecycle] proves
the graph sound at compile time (#1675): referenced-state existence, a terminal
with no exit, reachability from the initial state, and that every reachable
non-terminal state can reach a terminal one. autumn lifecycle check re-proves
the same over a whole project without a build and exits non-zero when unsound;
autumn lifecycle diagram emits a Graphviz DOT or Mermaid stateDiagram-v2
per lifecycle.
See docs/guide/state-machines.md and examples/wiki (Page model,
draft → published → archived).
#[repository] generates far more than CRUD — reach for these before writing
raw Diesel:
| Method / attr key | Purpose |
|---|---|
find_by_id, find_all, count, exists_by_id, save, update, delete_by_id | Core CRUD |
page(&PageRequest) | Offset pagination (?page=N&size=M, clamped, never 400) |
cursor_page(&CursorRequest) + cursor_key = field (opt. cursor_key_type =) | Keyset pagination for feeds/large tables; cursor_key must be non-nullable |
save_many, save_many_skip_invalid, update_many, delete_many, upsert_many | Bulk ops, hook-aware, auto-chunked under the 65,535-param ceiling; upsert_many is a compile error on hooked repositories |
with_lock | SELECT ... FOR UPDATE row locking in a transaction |
primary_reads (attr) / on_primary() | Pin reads to primary; read-your-writes after a save |
boundary = B (attr) | Run as the Postgres role of boundary B; implies primary_reads; not with sharded |
soft_delete, tenant_scoped (attrs), across_tenants() | Soft deletion and tenant scoping |
hooks = MyHooks (attr) | before_/after_create/update/delete + after_*_commit lifecycle hooks with MutationContext |
from_shard(&ShardedDb), with_pool_untracked(pool) | (0.6.0) shard-scoped construction. with_pool_untracked is the 0.6.0 rename of with_pool; 0.5.x repositories had no pool constructor at all. An app carrying the older with_pool name is migrated by autumn upgrade --apply (codemod 0.6.0-repository-with-pool-untracked, issue #1629) rather than by hand |
find_in_batches(batch_size), find_each(batch_size) | (0.6.0) Bounded-memory whole-table iteration via a primary-key keyset cursor (WHERE id > last ORDER BY id ASC LIMIT batch_size — never LIMIT/OFFSET), generated on every repository. find_in_batches returns a FindInBatches handle — drive with while let Some(chunk) = b.next_batch().await?; find_each returns FindEach yielding one model per next().await?. Inherits soft-delete filtering, tenant scoping, and read routing like find_all; errors are retryable (cursor advances only on success; Ok(None) always means completion); batch_size == 0 errors instead of spinning; batch_size is not clamped to MAX_PAGE_SIZE; sharded repos reject cross-shard across_tenants() iteration (iterate per shard via from_shard). Handle types: autumn_web::batches::{FindInBatches, FindEach, BatchSource} (not in the prelude). See "Batched iteration" in docs/guide/pagination.md |
find_or_create_by_<field>[_and_<field>...](<field>, &new) | (0.6.0) Race-safe get-or-insert; declare fn find_or_create_by_slug(slug: String); (lookup fields only) to generate an inherent find_or_create_by_slug(&self, slug: String, new: &NewModel) -> AutumnResult<(Model, bool)>. Reads on the read path first (tenant/soft-delete aware, canonicalizing a #[normalize] lookup column), else normalizes and validates the payload (#2586 — an existing row still wins over a rejected one, re-checked on the primary) and inserts on the primary with ON CONFLICT DO NOTHING — under concurrency exactly one row is created, exactly one caller sees created == true, and no 23505 escapes. before_/after_create + commit hooks fire only on the created path; works on hooked repos (unlike upsert_many). Requires a unique constraint on the lookup column(s) (_or_ is rejected). See "Race-safe get-or-insert" in docs/guide/repositories.md |
ledgered = true / ledgered(valid_time = "col", schema_version = N, upcast = path) (attr) | (0.8.0, issue #1699) Makes the entity bitemporal and tamper-evident: every insert, update and soft-delete appends an immutable, hash-chained revision carrying a full row snapshot to _autumn_ledger_revisions. Adds ledger_as_of(id, at), ledger_as_of_at(id, LedgerAsOf), ledger_diff(id, from, to), ledger_revisions(id), ledger_revisions_page(id, page), ledger_verify(id), ledger_head(id), ledger_high_water(id) and ledger_pin(id) (both at once, from one snapshot — what an audit posture pins outside the database). Implies versioned = true and requires soft_delete (a hard DELETE would erase the row the ledger reconstructs); purge is not generated, and #[version_history(sensitive = [...])] / no_versioned_record_impl are compile errors. See "Ledgered entities" below |
retention(after = "30d", basis = created_at) / retention(purge_deleted_after = "90d") (attr) | (0.7.0) Declarative data-retention: reach for this instead of hand-writing a #[scheduled] cleanup fn for expiring sessions, drafts, one-time codes, or other transient rows. Compiles to a batched (batch_size, default 500), cursor-paginated sweep auto-registered with fleet coordination — no tasks![...] entry needed. On a soft_delete repository, after soft-deletes (never re-touching an already-deleted row) and purge_deleted_after hard-purges (re-checking deleted_at at delete time so a concurrent restore() survives); without soft_delete, after hard-deletes. Sweeps run across all tenants on a tenant_scoped repository (no per-tenant opt-out) and are not supported on sharded repositories (compile error). autumn retention --dry-run [--model NAME] reports rows-that-would-be-swept without deleting. Emits retention_sweep_rows_total / retention_sweep_duration_seconds metrics + a structured log line per run. See docs/guide/retention-sweeps.md |
Read routing: with database.replica_url set, all generated reads use the
replica automatically; writes always hit the primary. See
docs/guide/repositories.md and docs/guide/pagination.md.
Reach for this when an entity's past is part of the product: regulated records, anything an auditor will ask about, anything you may need to undo.
#[repository(Invoice, soft_delete, ledgered = true)]
pub trait InvoiceRepository {}
let then = repo.ledger_as_of(id, last_tuesday).await?; // Option<Invoice>
let delta = repo.ledger_diff(id, last_tuesday, now).await?;
let proof = repo.ledger_verify(id).await?; // LedgerVerification
The marker is the only per-model change — do not hand-write revision
bookkeeping. ledgered implies versioned, so every write path version history
already covers (hand-written handlers, generated api = "…" endpoints, #[job]
/ #[mailer], bulk saves, upserts, find_or_create_by, dependent cascades)
appends a revision automatically.
What to know when writing app code against it:
dependent(.., on_delete = delete_all | nullify) into a ledgered
child, #[votable] / #[commentable] / has_many(through) writes into a
ledgered table, and writes from an unledgered repository on the same table
fail with LedgerError::OutOfBandWrite. A model factory panics. For a
dependent, use on_delete = destroy. For the other paths, write through the
ledgered repository.delete_by_* on a ledgered repository (compile error): it
records no revision. Find the records. Then call delete_by_id or
delete_many.String. A ledgered tenant_scoped repository with
tenant_id: Option<String> does not compile, and an update that changes
tenant_id fails with LedgerError::TenantChange.ledger_revisions_page(id, LedgerPageRequest) reads the
chain in keyset pages. ledger_verify pages internally.soft_delete is mandatory and purge does not exist. delete_by_id
records a delete revision; restore records the undelete. Both keep the
ledger and the table in agreement.deleted_at exactly as against the table.Option<T> or #[serde(default)] covers an added
field. For a rename or a retype, set
ledgered(schema_version = 2, upcast = path). The function
fn(from_version: u32, &mut serde_json::Value) -> Result<(), String> converts
an older snapshot (issue #2326). The version is stored in each new snapshot as
"$schema_version", inside the hash. A failing function is
SnapshotSchemaMismatch, not tamper evidence. ledger_verify converts the
head before its live-row check. For a head older than the model's version it
compares only the columns both shapes have, so raise schema_version when you
add a column. A head at the current version is compared strictly.recorded_at is transaction time; valid_from defaults to
it, or comes from your own column via ledgered(valid_time = "effective_at")
(Timestamp / civil::DateTime / Option of either). Query both with
LedgerAsOf::{transaction, valid, bitemporal} via ledger_as_of_at. Both
bounds filter; the newest surviving revision wins.ledger_verify is the audit answer. Beyond the hash chain it
cross-checks a per-record high-water mark kept outside the deletable
revision rows (_autumn_ledger_high_water, issue #2323) and the live row. A
deleted revision therefore leaves a permanent MissingRevision gap rather
than a window an ordinary write closes, a wholly erased chain is
distinguishable from a row that predates ledgering, and tampering with the
mark itself reports HighWaterBehind / HighWaterMismatch /
HighWaterMissing. A write that reached the table without appending a
revision is still LiveStateMismatch. Appends refuse when the mark and
the chain are in a state no framework path produces, so traffic cannot launder
evidence away. Pin ledger_head(id).hash outside the database to catch a
wholesale rewrite — the hashing rule is open source, so in-database evidence
cannot cover that.clock_timestamp() /
strftime(…, 'now')), clamped so it is non-decreasing along a chain by
construction; RecordedAtRegression reports a chain where it is not.across_tenants() and cross-shard
ledger reads are rejected (a chain is per (tenant, record)); read inside a
tenant scope.SELECT (chain head, high-water mark and the
database clock together) plus the revision INSERT and the mark's upsert per
write inside the same transaction — a fourth statement on a delete — per row
on bulk paths, and a full row snapshot per revision. Don't ledger a high-churn
table by reflex._autumn_ledger_revisions and _autumn_ledger_high_water arrive with
autumn migrate (Postgres and SQLite); migrate before rolling out the binary.
See docs/guide/ledgered-entities.md.
A #[repository(api = "/api/posts")] list endpoint returns a page envelope, and
create/update handlers validate the decoded payload before touching the DB:
GET /api/posts?page=1&size=20 returns
{ content: [...], page, size, total_elements, total_pages, has_next, has_previous } (page is 1-based, default 1; size clamped). Custom
handlers can use filter.page() / filter.size() / filter.limit() /
filter.offset().#[validate(...)] rules first; on failure the handler returns 422 Problem
Details with a per-field errors map instead of inserting. Models without a
Validate derive compile to a no-op via the autoref MaybeValidate
specialization (no migration burden), and this applies to plain and
policy-backed handlers (#1237, #1253). See docs/guide/pagination.md.api = "..." feature: save, save_many,
save_many_skip_invalid and the create half of find_or_create_by_* run
them after #[normalize] and before before_create. A GraphQL resolver, a
#[task] or an admin action gets the same 422. Not covered:
Model::factory().create() (and so autumn seed), a hand-written
repository, raw diesel::insert_into, and upsert_many. Update paths are
unchanged — see "Partial-update validation" below. A #[validate] rule on a
column that before_create populates now rejects every insert, because the
rules run first.On a repository with hooks = ..., a PATCH/PUT update now validates the
effective merged model — the existing row ∪ the patch, after normalization —
not only the patch struct's own fields. #[model] derives validator::Validate
on the read model (gated on has_validation, symmetric with the New*/Update*
models) and keeps the full #[validate(...)] set there; the generated
from_patch validates the reconstructed concrete model before returning the
draft, running before before_update (mirroring create, where validation runs
before before_create). Because the merged model's fields are concrete T
rather than Patch<T>, validators that cannot be expressed on Patch<T> — ip
on Option fields and does_not_contain (E0119 trait-coherence walls under
validator 0.20), plus the cross-field custom/must_match/nested (no
single-field Patch<T> trait) — are now enforced on update, returning the same
422 field-error map as create.
This covers every update path that builds a draft via from_patch (hooked
repositories and their --api handlers). The blind __to_changeset update paths
(plain/api/policy repositories without hooks) still run only the patch-struct
validators (follow-up: issue #1801). The Patch<T> per-field impls and the
UpdateModel denylist are unchanged, so this is backward compatible (issue
#1778). See docs/guide/repositories.md.
#[validate(nested)] hazard (issue #1751): validator_derive's nested
codegen calls a field's value with a bare .validate(), which collides with
this crate's own ValidateExt (also named validate, blanket-implemented for
every Validate type and re-exported from autumn_web::prelude) whenever the
struct's own defining module ALSO imports the prelude (or ValidateExt
directly) — a cryptic E0034: multiple applicable items in scope pointing
into the derive expansion, on create as much as on update, and on #[model]
structs as much as hand-rolled ones. It doesn't matter what a downstream
handler module imports — only the struct's own module's imports matter. Avoid
it by keeping a #[validate(nested)] struct's module free of the prelude/
ValidateExt import (use fully-qualified Db/etc. paths there instead), or by
replacing nested with #[validate(custom(...))] calling the nested value's
validator::Validate::validate explicitly.
Db::tx(f) runs a READ COMMITTED transaction. Since
0.6.0, Db::tx_with(opts, f) adds isolation levels and automatic
retry of serialization failures (SQLSTATE 40001) with capped exponential
backoff:
use autumn_web::db::{TxOptions, IsolationLevel};
let opts = TxOptions::serializable() // or ::repeatable_read(), ::read_committed()
.read_only()
.max_attempts(8); // serializable()/repeatable_read() default to 5
db.tx_with(opts, |conn| async move { /* &mut AsyncPgConnection */ }.scope_boxed()).await?;
On SQLite, a write-heavy closure (read-modify-write, queue claims, outbox
inserts) should use Db::tx_immediate(f) (0.8.0, #2885): it begins
BEGIN IMMEDIATE, so a concurrent writer on a file database waits on
busy_timeout instead of failing with SQLITE_BUSY_SNAPSHOT. On a
cache=shared target it only stops writers from all reading before they
upgrade; any writer can still fail at once with SQLITE_LOCKED (no queueing, no
guaranteed winner), so retry with backoff — or use a WAL-mode file database.
TxOptions::default() is identical to Db::tx. See
docs/guide/transactions.md and docs/guide/hooks-and-transactions.md.
Do not hand-roll a money type or a ledger. autumn_web::money has both.
Not to be confused with autumn_web::ledger (ledgered = true above), which
records the history of a row; this one records money.
Money<C> is an amount in one currency, held as an i64 count of minor units.
The currency is a type parameter, so Money<Usd> and Money<Eur> do not add.
Never use f64 for money, and never reach for +/- here — there are no
operator impls, because an operator cannot report an overflow:
use autumn_web::money::{Money, Rounding, Usd};
let fee = Money::<Usd>::from_minor(250); // $2.50
let tip = Money::<Usd>::from_major(1)?; // $1.00
let total = fee.checked_add(tip)?; // checked_sub/neg/abs/mul, try_sum
// Rounding is always named; `from_decimal_exact` refuses to round at all.
let price = Money::<Usd>::from_decimal(decimal, Rounding::HalfEven)?;
// Splits lose nothing: the parts always sum back to the whole.
let parts = total.split(3)?; // or .allocate(&[70, 20, 10])
AnyMoney is the runtime-tagged form for a stored row, and rejects a currency
mismatch at run time. Render with number_to_currency(m.to_decimal()).
The ledger is append-only and double-entry. A transaction is a set of postings; a debit is positive, a credit is negative, and a balance is the sum of an account's postings:
use autumn_web::money::ledger::{self, Account, IdempotencyKey, Posting, Transaction};
// Once, at boot. `disallow_negative()` is the one policy flag.
ledger::ensure_account(conn, Account::new("platform:cash", Usd::currency())).await?;
let postings = vec![
Posting::debit("platform:cash", amount),
Posting::credit("platform:revenue", amount),
];
// Idempotent by construction: the key is the money, so a retry collapses.
let key = IdempotencyKey::derive("order:9911", &postings);
let outcome = db.tx(|conn| async move {
// ... the application rows this charge justifies ...
ledger::post(conn, &Transaction::new(key, postings)).await.map_err(AutumnError::from)
}.scope_boxed()).await?;
outcome.is_replayed(); // true when the money had already moved
Rules that matter:
post must run inside Db::tx. A bare connection is refused with
LedgerError::NotInTransaction; the locks and the balance check mean nothing
outside one, and the tables are append-only so a partial write cannot be
repaired. Posting twice in one transaction needs Db::tx_with (deadlock
retry).post refuses an unbalanced transaction before its first INSERT, plus
mixed currencies, a one-sided transaction, a zero line, a negative amount, a
currency the account does not hold, and a balance that would leave i64.LedgerError::KeyReuse (409), never a
silent replay of the wrong result.ledger::balance(conn, id) reads the balance the account row stores. A
trigger keeps it, so the cost does not increase with the history.
ledger::trial_balance(conn) returns every currency's total, each of which
must be zero — run it from a scheduled job or a health check.
ledger::balance_drift(conn) returns each account whose stored balance is
not the sum of its postings; it must be empty. It reads every posting, so
run it from a scheduled job only._autumn_money_*) ship in Autumn's own migration set, in the
control database. Nothing to add to the app's migrations/. They are
append-only by trigger — UPDATE, DELETE, TRUNCATE and an SQLite
INSERT OR REPLACE all abort. An account's currency is fixed the same way;
only allow_negative and balance_minor change. The SQLite half uses
BEFORE INSERT guards on the row keys, because SQLite skips DELETE
triggers for the row a REPLACE removes and the pragma that changes that
would alter every application trigger's recursion semantics.post never half-writes: it writes the postings before their
transaction row behind a deferred foreign key, so the ledger ends up with
nothing or one complete transaction. Which one is not knowable from the
cancellation, so re-post the same idempotency key to settle it. Simpler still:
do not race post against a timeout.Out of scope in this slice: FX conversion, provider reconciliation, and a
payment-provider client. See docs/guide/money.md.
#[get("/dashboard")]
#[secured]
async fn dashboard(session: Session) -> AutumnResult<Markup> { /* ... */ }
#[get("/admin")]
#[secured("admin")]
async fn admin_panel() -> AutumnResult<Markup> { /* ... */ }
// Record-level auth on repository-generated REST endpoints:
#[autumn_web::repository(Post, api = "/api/posts", policy = PostPolicy, scope = PostScope)]
pub trait PostRepository {}
// Manual handler: load the record first, then check inline.
// #[authorize] is used by the repository macro; for manual handlers
// the pattern is explicit ownership checks in the body:
#[post("/posts/{id}")]
#[secured]
async fn update_post(Path(id): Path<i64>, mut db: Db, session: Session) -> AutumnResult<Markup> {
// session.get() returns Option<String>; parse to i64
let user_id: i64 = session.get("user_id").await
.ok_or_else(|| AutumnError::unauthorized_msg("Login required"))?
.parse()
.map_err(|_| AutumnError::bad_request_msg("Invalid session"))?;
let post = find_post(&mut *db, id).await?;
if post.user_id != user_id {
return Err(AutumnError::forbidden_msg("not your post"));
}
/* ... */
Ok(html! { "updated" })
}
(0.6.0) Scoped service tokens: mint named,
optionally-expiring API tokens carrying flat scopes via IssueTokenSpec +
issue_scoped_api_token; gate handlers with
#[secured(scopes = ["posts:write"])] (no session required — default-deny,
403 when missing) or #[secured("admin", scopes = [...])] for both; check in
policies with PolicyContext::has_scope/has_any_scope/has_all_scopes; manage
with autumn token issue <principal> --name ... --scope ... / list /
rotate / revoke — all four ship in 0.7.0. list and rotate arrived in
0.6.0; a 0.5.x CLI has only issue / revoke.
Active session management ships with autumn generate auth (0.5.0):
a {user}_sessions row per login, generated sessions(),
revoke_session(id), revoke_other_sessions(...), revoke_all_sessions()
methods, an /account/sessions Maud + htmx page, and [auth.sessions]
config (incl. revoke_on_credential_change, default on).
In prod / production, configure a stable signing secret or startup fails:
export AUTUMN_SECURITY__SIGNING_SECRET="$(openssl rand -hex 32)"
For rotation, set [security.signing_secret].previous_secrets until old
cookies, CSRF tokens, flash state, and signed storage URLs expire.
"Log in as this user" without breaking the audit trail. Never hand-roll it
with session.insert("user_id", target) — that makes every subsequent version
row and audit event claim the customer did it.
autumn_web::auth::impersonation::begin_impersonation(&state, &session, target)
swaps the session's effective user and records the real admin separately
under a reserved impersonator_id key, so #[secured] / RequireAuth /
PolicyContext see the impersonated user while the ambient current actor
(Current::actor, which seeds #[repository(versioned)] rows and audit
events) stays the real impersonator. end_impersonation(&state, &session)
reverts. impersonator_id(&state, &session) is the separate accessor;
impersonation_state(&state, &session) returns both ids, and the
Impersonation extractor is the handler-side form. Register the gate with
AppBuilder::impersonation_gate(...).
Default-deny: it needs an ImpersonationGate in AppState —
ImpersonationGate::allow_roles(["admin"]), or ::custom(policy) with an
ImpersonationPolicy (the seam for tenancy checks and for
target_role, which resolves the impersonated session's role server-side;
never accept a role from request input). Missing gate or a refusal is 403.
Both edges rotate the session id and write auth.impersonation.begin /
.end audit events carrying {impersonator_id, target_id}; a begin is refused
when the audit write fails or when no audit sink is installed at all — wire
AppBuilder::with_audit_sink(...) before enabling it. The operator's step-up
claim is stashed and dropped for the duration (so a #[step_up] action cannot
be run on the target's account on the operator's re-auth) and restored on
revert; the record is bound to the user it names and to the session
generation that created it, so a login (which rotates the session id) retires
it — a forgotten impersonation cannot be inherited by the next user, not even by
the impersonated customer signing in as themselves. Call
impersonation::clear(&session) from any login flow to drop it outright. No nesting (409), no self-impersonation, and
the admin's own step-up claim is preserved rather than refreshed.
For the UI, AdminPlugin::with_impersonation(gate) mounts
POST {prefix}/impersonate (behind the role gate + the ImpersonationGate)
and POST {prefix}/impersonate/stop — deliberately outside the role gate, so
an operator impersonating a non-admin is never trapped — and renders a
persistent "Viewing as … — Stop impersonating" banner on every admin page. Put
the same banner in the app's own layout with
autumn_admin_plugin::impersonation_banner_for(&state, &session, "/admin", csrf_token, csrf_form_field) plus IMPERSONATION_BANNER_CSS. Session-based
auth only. See docs/guide/authentication.md and docs/guide/admin.md.
autumn new scaffolds a cookie-consent banner and a real consent gate by
default — no third-party tracker, no JS. autumn_web::consent::Consent is an
extractor read straight off the request's Cookie header (no middleware
dependency); consent.allows("analytics", POLICY_VERSION) is the actual
enforcement gate (returns false for every category except "necessary"
until a decision is recorded under the current policy version).
accept_all_cookie / reject_non_essential_cookie / expire_consent_cookie
build the Set-Cookie value recording categories + policy version +
timestamp. inject_consent_banner (behind the maud feature; mirrors the
dev-mode live-reload injector) auto-splices the banner into every HTML
response — no change to the shared layout() signature is needed. Takes the
CSRF cookie name and form-field name as explicit parameters
(DEFAULT_CSRF_COOKIE_NAME / DEFAULT_CSRF_FORM_FIELD when unconfigured)
rather than reading them off request/response state, since CsrfLayer always
sits inner to user layers. Skips injection entirely for an internal autumn build / ISR render (static_gen::RenderDeadlineExempt) rather than baking
the banner into the static file written to dist/. Bump the scaffolded
CONSENT_POLICY_VERSION constant to invalidate prior consent and re-show the
banner. Strictly-necessary cookies (session, CSRF) are never routed through
the gate.
Version/audit writes are auto-attributed to the current actor — no per-call
plumbing. The log-context middleware opens an empty actor scope per request; set
the authenticated user once and every VersionEntry.actor (via
MutationContext::actor) records it:
use autumn_web::current::Current;
Current::set_actor(format!("user:{user_id}")); // ambient, task-local, request-scoped
// any repository mutation in this request now records this actor on its VersionEntry
For jobs and the scheduler (no request scope), set a process-wide default with
Current::set_default_actor(...), or run a bounded scope via
autumn_web::current::with_actor(actor, async { ... }). Unset → actor is
recorded as "system" — the _autumn_version_history.actor column is NOT NULL DEFAULT 'system' and the generated code falls back to VersionEntry::SYSTEM_ACTOR
(#1383). See docs/guide/version-history.md.
#[edge] routes — host-resolved identity (0.8.0, feature edge)An #[edge] capsule never sees cookies, session ids, signing keys or store
credentials. The host resolves identity before the capsule runs and passes
only normalized claims: EdgeIdentity { user_id: EdgeUserId, roles: Vec<EdgeRole> }
(re-exported from autumn_web::edge_support), taken as a handler extractor.
EdgeIdentity is also in autumn_edge::prelude. A handler taking it must
declare #[edge(needs(identity))] (a build error otherwise); a request without
host-verified claims then falls through to origin before dispatch, so no
extractor or handler code runs.
#[get("/me")]
#[edge(needs(identity))]
pub async fn whoami(identity: EdgeIdentity) -> String {
identity.user_id().as_str().to_owned()
}
Install the source with AppBuilder::with_edge_identity_provider(provider).
The first-party one is SessionIdentityProvider::new(store, AuthSessionProjector::new("user_id"), cookie_name, signing_keys):
it reuses SessionLayer's cookie and signing-key verification, so it accepts
exactly what the session middleware accepts. A custom EdgeIdentityProvider
returns Ok(Some(_)) only after authoritative verification, Ok(None) for a
missing/invalid credential, and a typed error for store/network failure (also a
fall-through). Revocation needs an authoritative store — never back it with an
opportunistic cache. See docs/guide/edge.md and ADR-0005.
OAuth2/OIDC social login has shipped since the 0.5.0 line. Do not repeat the stale
changelog claim that it was reverted; the revert was followed by a reapply and
review fixes. Prefer the current tree and docs/guide/oauth.md over that old
summary line.
autumn generate auth User --oauth github,google
The generator creates src/routes/oauth.rs, an oauth_identities migration,
login buttons, and [auth.oauth2.<provider>] config stubs. The flow uses
PKCE S256, state validation, OIDC nonce validation, and provider presets for
GitHub, Google, and Microsoft. OAuth support stays behind the oauth2 feature.
Autumn 0.4.0 added SignedWebhook for Stripe, GitHub, Slack, and generic
HMAC callbacks. The extractor verifies the exact raw body bytes and replay key
before handler logic runs. Timestamp freshness is provider-specific: Stripe
(signature t= field) and Slack (X-Slack-Request-Timestamp) validate staleness
automatically; GitHub and generic-HMAC providers only check the body signature
unless you add timestamp_header to the [webhooks.<name>] config block
explicitly.
#[post("/webhooks/stripe")]
async fn stripe(webhook: SignedWebhook) -> AutumnResult<Json<serde_json::Value>> {
let event: serde_json::Value = webhook
.json()
.map_err(|err| AutumnError::bad_request_msg(format!("invalid JSON: {err}")))?;
Ok(Json(serde_json::json!({
"accepted": true,
"provider": webhook.provider(),
"delivery_id": webhook.delivery_id(),
"event_type": webhook.event_type(),
"event": event,
})))
}
Production replay protection should use Redis:
[security.webhooks.replay]
backend = "redis"
[security.webhooks.replay.redis]
url = "redis://redis:6379/0"
key_prefix = "myapp:webhooks:replay"
autumn generate webhook <provider> <Name> (0.7.0, #1366)
scaffolds the whole endpoint: the #[post] handler over SignedWebhook, an
event-type dispatch skeleton, the [[security.webhooks.endpoints]] config
(secret_env, replay protection on — CSRF/submit-token/CAPTCHA exemptions are
derived from that block by the framework, so none are written), and tests
asserting 200/400/401/409 for valid/missing/wrong-signature/replayed
deliveries. Presets: stripe, github, slack, generic.
Read docs/guide/signed-webhooks.md and examples/signed-webhooks/.
Everything above is webhooks arriving in. For the other direction — letting
your own users/customers register an endpoint and dispatching signed events to
it — use autumn_web::webhook_outbound: WebhookSubscription (their endpoint,
signing secret and subscribed topics), a pluggable OutboundWebhookHandler, and
WebhookOutboundManager off AppState. The
autumn_webhook_delivery job signs and POSTs it with retries and deactivation;
dead-letter inspection and replay live under /actuator/webhooks/*.
Two things to get right when generating this code:
OutboundWebhookPlugin::new(store) takes one as
a required argument. InMemoryOutboundWebhookHandler ships with the framework
but is process-local AND unbounded — subscriptions and delivery logs vanish
on restart, are not shared across replicas, and are held in plain hash maps
with no cap or eviction. A retry replaces its log row rather than adding one
(same id, attempt advanced in place), so growth is per DISPATCH, not per
attempt — and nothing ever evicts, so memory grows with dispatch volume for
the lifetime of the process. It is for tests and local development; any
long-running app needs a durable shared implementation of the trait. (OutboundWebhookStore /
InMemoryOutboundWebhookStore are compatibility aliases; prefer the
…Handler names in new code.)dispatch() is not transactional. It writes a delivery-log row per
subscription and then enqueues the job; no transaction spans the pluggable
store and the queue, so a crash between the two leaves a logged event that was
never enqueued. Do not present it to a user as an outbox guarantee, and do not
write a reconciler over the log table to claim one: a successful enqueue
writes no marker, so an enqueued row is indistinguishable from one whose
process died first, and a sweeper can only duplicate or drop. Implementing the
trait does not fix it either — OutboundWebhookHandler is storage-only and the
enqueue happens after it returns, so no impl can make the two atomic. If an app
needs a stronger guarantee, do NOT invent an exactly-once design here — the
answer depends on the job backend, the handler, and how the app sequences its
own transaction against dispatch(). Tell the user the constraints and let
them decide:
Ok from dispatch() is not durability. The default
jobs.backend = "local" queue is in-process and non-durable, so a crash
loses it; durable delivery needs postgres/redis jobs AND a durable
OutboundWebhookHandler.Autumn-Signature header's t= is recomputed per attempt but is
neither unique nor stable — it is a whole-second ambient_now().as_second()
and nothing guarantees two attempts differ. Every backend uses full
jitter (issue #3054), so the first retry can come 0-1000 ms later and the
same second yields a byte-identical signature. (Do not enumerate
the headers — under telemetry-otlp the shared client also injects W3C
traceparent/tracestate.) Receiver-side deduplication needs an ID the
app mints into the payload itself.dispatch() is
neither at-least-once nor at-most-once. Idempotency buys protection from
duplicates, not from loss.
An enqueue that fails is the one handled case —
marked is_dlq and replayable — but only on the default enqueue path. With a
WebhookDelegateExt installed, dispatch() calls the delegate instead of
enqueuing and a delegate error is returned without marking the row, so a
failed delegated delivery never reaches the DLQ.Do not
hand-roll outbound delivery with a bare HTTP client — the user-supplied
destination URL is an SSRF sink (docs/security/2026-09-03-webhook-ssrf/), and
the subsystem is where that is handled. Read
docs/guide/outbound-webhooks.md.
Gmail strips <style> in many contexts and Outlook (Word engine) ignores
<head>/<style> and most external CSS, so email authored with a stylesheet
arrives unstyled. The decades-old fix is to inline CSS onto elements at send
time. Autumn does this for you (issue #1254).
<style> block + classes, then opt in — either per message
or per environment:
// Per message (wins over the config default in both directions):
Mail::builder()
.to(to).subject("Welcome")
.html(r#"<style>.btn{color:#fff;background:#06c}</style><a class="btn">Go</a>"#)
.inline_css(true) // ← rewrites .btn onto the <a> as style="…" at send
.build()?
# Per environment — default it on for every mailer:
[mail]
inline_css = true
MailBuilder::inline_css(true|false) always beats
the mail.inline_css default (inline_css(false) opts one message out of an
environment that defaults on). Default is off — existing apps are
unaffected until they opt in.@media/pseudo-class rules stay in a
retained <style> block; text parts and bodies with no <style> pass through
unchanged; inlining is idempotent (running it twice equals once).MailError::CssInline is surfaced rather than delivering
malformed HTML.autumn generate mailer scaffolds this end to end (a <style> template + a
mailer that calls .inline_css(true)).Autumn detects delivery failure (inbound bounce/complaint webhooks) and
acts on it: Mailer::send() consults a bounce/complaint suppression list
before transport and skips addresses that hard-bounced or complained. This
protects sender reputation (re-sending to a hard bounce is what gets a domain
throttled by Gmail/Microsoft/SES). Distinct from recipient-initiated
List-Unsubscribe (#[mailer(list_unsubscribe)]): that is a user opt-out;
this is provider-reported failure.
Zero-config: an in-memory SuppressionStore is auto-wired; the loop works
out of the box on a single instance. For multi-instance deploys register the
durable Postgres backend (shared across replicas):
use autumn_web::mail::suppression::PgSuppressionStore;
App::builder().with_mail_suppression_store(PgSuppressionStore::new(pool))
You must create the
mail_suppressionstable yourself —PgSuppressionStoreships no migration (same convention as the List-Unsubscribemail_unsubscribesstore, whose table is written byautumn generate mailer --list-unsubscribe). Add a migration with:CREATE TABLE mail_suppressions ( address TEXT PRIMARY KEY, reason TEXT NOT NULL, suppressed_at TIMESTAMPTZ NOT NULL DEFAULT now() );Without it, every send errors on the suppression lookup.
Close the loop — receive provider bounce webhook → suppress → later send
is skipped. The inbound handler and the Mailer must consult the same
store. with_mail_suppression_store takes a store by value and wraps it in
a fresh handle internally, so build one InMemorySuppressionStore and
hand out .clone()s of it — the clone shares the same Arc<Mutex<…>> state
(inbound handlers are plain fn pointers, so stash a handle in a OnceLock).
The receiving half needs the non-default inbound-mail feature on top of
mail — record_inbound and InboundMailRouter are both behind it, while
the store and with_mail_suppression_store above are not:
autumn-web = { version = "0.11", features = ["mail", "inbound-mail"] }
use std::sync::OnceLock;
use autumn_web::mail::suppression::{
record_inbound, InMemorySuppressionStore, SuppressionStoreHandle,
};
static SUPPRESSION: OnceLock<SuppressionStoreHandle> = OnceLock::new();
// ONE store; clones share the same underlying state.
let store = InMemorySuppressionStore::new();
SUPPRESSION
.set(SuppressionStoreHandle::new(store.clone())) // inbound side
.ok();
let app = App::builder().with_mail_suppression_store(store); // Mailer side — same state
// Inbound router: the provided handler records the bounce.
InboundMailRouter::new()
.endpoint(InboundMailEndpointConfig::mailgun("/mail/inbound", signing_key))
.on_bounce(|email| Box::pin(async move {
record_inbound(SUPPRESSION.get().unwrap().inner().as_ref(), &email).await?;
Ok(())
}));
A bounce suppresses the provider-reported email.bounced_address
(SuppressionReason::HardBounce). Afterwards mailer.send(mail_to("[email protected]"))
returns Err(MailError::AllRecipientsSuppressed) (zero transport calls) while
[email protected] still delivers.
on_spamis an inbound spam verdict, not an outbound complaint. autumn'son_spamfires on a provider-side inbound spam flag (X-Mailgun-Sflag: Yes) — it carries no outbound complainant address, andemail.tothere is your app's own inbound address. Sorecord_inbounddeliberately suppresses nothing for a bare spam verdict (it logs instead), and never suppressesemail.to. Only a genuine FBL complaint that populatesInboundEmail::complained_addresssuppresses that complainant (SuppressionReason::Complaint). Wire a real feedback-loop source to that field before routing complaints here.
Webhook authentication. A Mailgun endpoint accepts each signed token once (Mailgun signs
timestamp || token, not the message). A repeat gets200and is not dispatched; a failed dispatch releases the token for the retry. The set is in memory, per process. To post unsigned SNS fixtures in a test, callInboundMailRouter::dangerously_skip_sns_verification()on that router. Do not set the deprecated, process-wideinbound_mail::SKIP_SNS_VERIFICATION.
Observability: every skip logs outcome = "skipped_suppressed" and bumps
suppression::suppressed_skips() — a suppressed drop is never silent.
Critical mail bypass: Mail::builder().….ignore_suppression() delivers
even to a suppressed address (password resets, MFA codes, security alerts).
Escape hatch: store.unsuppress(addr) removes an address (e.g. the
recipient fixed their mailbox); store.suppress(addr, SuppressionReason::Manual)
adds one by hand.
A first-class per-recipient notification store with read/unread state — do not
hand-roll a notifications table, model, and unread-count queries. Scaffold with
autumn generate notifications (backend-aware migration + feed routes + smoke
test), then use the Notifications extractor (in the prelude, surfaced like
Session):
use autumn_web::prelude::*;
#[post("/comments")]
async fn create_comment(notifications: Notifications) -> AutumnResult<&'static str> {
notifications
.notify(recipient_id, "comment.created", serde_json::json!({"post": 42}))
.await?;
Ok("ok")
}
notify(recipient_id, kind, payload); list(recipient_id, &ListQuery, &PageRequest) -> Page<Notification> (?filter[unread]=true,
?filter[kind]=…, ?sort=created_at|id, newest-first default);
unread_count(recipient_id); idempotent mark_read(id) /
mark_read_for(recipient_id, id) / mark_all_read(recipient_id). In
user-facing handlers use mark_read_for — it refuses to touch other
recipients' rows.SessionStore): a store registered via
AppBuilder::with_notification_store(...) → DbNotificationStore when a DB
pool is configured (needs the generated notifications table) →
MemoryNotificationStore (process-local; what TestApp without a DB uses,
so generated smoke tests need no database).ws feature): notify_with_push(...) persists then
publishes the notification JSON on Notifications::topic(recipient_id)
("notifications:{id}") — best-effort, a channel failure never fails the
notify. In the subscribing WS/SSE handler, derive the topic from the
authenticated user (Auth/session), never a client-supplied id — topics
are guessable and carry the full payload; use subscribe_authorized /
sse::stream_authorized for channel-level enforcement.tenant_id (the resolved tenant, "" when none).
Feeds, counts and topic() are per tenant. Jobs wrap calls in
tenancy::with_tenant. Push subscriptions also store tenant_id.docs/guide/notifications.md. Out of scope by design: bell widget,
email/SMS channels, preferences/digests, cross-recipient fan-out.autumn_web::push delivers to a subscribed browser even when the app is
closed — the leg neither the in-app feed nor channels can cover. The
developer writes zero crypto: VAPID signing (RFC 8292) and payload
encryption (RFC 8291) are the framework's.
VapidKey::generate() once (offline) → [push] private_key/subject in autumn.toml → autumn generate pwa (which mounts
autumn_web::push::router(), emits the SW push/notificationclick
handlers and the client subscribe snippet, and scaffolds the
push_subscriptions migration). Then push.send(user_id, &PushMessage::new(title, body).url(target)).WebPush is an extractor (like Session/Db/Notifications):
send, send_many, subscribe, unsubscribe, vapid_public_key.
send_many serves up to four principals at once and finishes every one
before it returns an error. For a pinned outbound request to a host with
several checked addresses, use RequestBuilder::pin_to_addrs. Do not loop
over pin_to: a loop can send a POST body twice.PushPrincipal accepts both id shapes — i64 (as the notification feed
uses) and &str/String (as auth tokens carry) — so composing with #1148
needs no conversion.with_push_subscription_store(...)
→ DbPushSubscriptionStore (the generated push_subscriptions table) →
MemoryPushSubscriptionStore. endpoint is UNIQUE and the identity: a
re-subscribe updates the row, and a re-subscribe under a different principal
MOVES it (shared device, second user signs in).notify(...) write (durable record),
then push.send(...) best-effort and log a failure — the same posture
notify_with_push takes with its channel broadcast. Never let a push failure
fail the notification write.[push] private_key fails the BOOT;
send with no key is PushError::NotConfigured raised before dispatch;
GET /push/vapid-public-key answers 503 when unconfigured.report.pruned); 5xx/429/
transport errors are counted in report.failed and LEFT in place — pruning
on a transient failure would unsubscribe everyone during an outage.https with a non-loopback domain host (IP literals
refused). The built-in routes resolve the principal server-side and 401 when
they cannot; unsubscribe is scoped to the caller.RecordingPushTransport captures requests (assert endpoint,
headers, encrypted body) and .responding_with(endpoint, 410) drives the
pruning path. Wire it with TestApp::with_web_push(...).docs/guide/web-push.md. Out of scope by design: native mobile push
(APNs/FCM), notification actions/images/badges, preferences/quiet hours.Use built-in jobs and tasks before reaching for a workflow engine:
| Tool | Use for |
|---|---|
#[scheduled] + .tasks() | Recurring app-local work; Postgres coordination is available for replicas |
#[job] + .jobs() | Request-triggered background work with retries and local/Redis backends |
#[task] + .one_off_tasks() | Operator-invoked CLI work via autumn task |
| Autumn Harvest | Durable multi-step workflows, activity retries, timers, and dedicated runners |
Autumn Harvest is a shipped, separate engine
(autumn-foundation/autumn-harvest,
wired in with autumn-harvest-plugin), not a roadmap item. Do not propose
workflow primitives for Autumn core: no #[workflow]/#[step] macros,
step-checkpoint tables, durable sleep inside a handler, signals, compensation,
or "run B after A" job dependencies. The test from
docs/adr/0016-durable-workflows-live-in-harvest.md: if the framework must
remember where inside the work it got to, it is Harvest's; otherwise it can
be a job feature. Jobs stay one unit of work, retried from the top (at least
once on the durable backends; local and enqueue_after_commit can lose a
job on a crash).
autumn-admin-plugin includes /admin/jobs for inspecting, retrying,
discarding, and canceling framework jobs. GET /actuator/jobs exposes
lower-level counters.
Job attributes beyond name/max_attempts/backoff_ms (0.5.0):
#[job(unique)] dedupes on an args hash, unique_by = "field",
unique_window = "running"|"pending", unique_for_ms = N (debounce),
concurrency = N + concurrency_key = "field" caps simultaneous runs. A
coalesced enqueue is a no-op Ok(()).
Claim leases and timeouts (0.9.0, #3051): durable workers renew each
claim every third of the visibility timeout. While renewals succeed, a long job
does not run on a second worker. If the claim is lost, the worker stops the
handler. With #[job(timeout = "30s")] (or jobs.default_timeout_ms; 0 = no
limit), a run that takes longer fails and retries. Spawned work checks
JobContext::is_cancelled() / lease_lost() or awaits cancelled(). Redis
claim deadlines use Redis TIME.
(0.6.0) jobs additions:
#[job(queue = "critical")]; drain order via
[jobs] queues = ["critical", "default", "low"] (strict priority) or a
[jobs.queues] weight table (weighted, starvation-free). No queue →
"default". See docs/guide/jobs.md.job::enqueue_tracked / enqueue_tracked_for (and
generated {Job}::enqueue_tracked companions) return a TrackedJobHandle
with a public token; #[job] accepts an optional third JobContext arg
(async fn(AppState, Args, JobContext)) with set_progress(pct, msg) /
set_result(json) / set_user_error(msg); poll GET /_autumn/jobs/{token}
(JSON or self-polling htmx fragment). Config: jobs.tracking.ttl_secs
(default 24h), jobs.tracking.route_enabled.#[job(version = N, upgrade = upgrade_fn)]. Autumn wraps the args in an
{ "__autumn_schema_version": N, "args": … } envelope; the upgrade hook
(fn(u32, serde_json::Value) -> Result<Value, E>) runs only for older stored
payloads, so a rolling deploy drains the old queue instead of dead-lettering.
A job with no version is stored raw (zero behaviour change). Helpers:
autumn_web::payload_version::{split_version, wrap} (Closes #1205). See
docs/guide/jobs.md.(0.6.0) Events & listeners — a typed domain event bus so one action
can fan out without inline coupling: #[event] on a struct, publish via the
Events extractor (events.publish(UserSignedUp { .. }).await?), react with
#[listener(UserSignedUp)] (sync, in-request) or
#[listener(UserSignedUp, durable, max_attempts = 5)] (jobs-backed), and
register with .listeners(listeners![...]). Do not also list durable
listeners in jobs![...]. See docs/guide/events.md.
Event wire contracts (0.11.0): #[event(name = "contact.updated", version = 2)] sets
the topic (contact.updated.v2) and derives WireShape (do not derive it
again). A #[listener] that reads a field the event does not send fails the
build. Put #[event_consumer(E)] on an outbox topic handler for the same
check. #[event(opaque)] turns the check off for a payload WireShape
refuses. autumn contracts check covers events across releases.
Send an event to another Autumn service with an outbox destination
(0.11.0), not a hand-written HTTP call. The producer sets [outbox.destinations.<name>]
(url, signing_secret = "${VAR}", topics) and writes the event with
outbox.write(conn, aggregate, Event::NAME, &event) in its transaction. Each
topic must be an #[event(name = "...")], or the boot fails. The receiver
sets [outbox.inbox] (enabled, the same signing_secret) and handles the
topic with a #[listener]; it serves POST /_autumn/inbox, drops copies
with Inbox::seen, and returns 503 for a topic it does not know yet, which
the producer relay sends again. Both apps need outbox.enabled = true. See
docs/guide/outbox.md.
For "run this exactly once across replicas right now" work (nightly cleanup,
cache warming, one-shot backfills, "send the daily digest once"), use
autumn_web::lock::Lock (re-exported from the prelude) instead of hand-rolling
pg_try_advisory_lock raw SQL. It is the same Postgres advisory-lock machinery
that already gates migrations and ISR. (#[scheduled] uses a tick table.)
Build: Lock::from_state(&state, "name")? (primary pool) or
Lock::new(pool, "name"). Names hash to a stable, namespaced 64-bit key via
distributed_lock_key (a "autumn:lock:v1" domain prefix keeps app keys out
of the scheduler/migration/ISR/repository keyspaces).
Acquire: try_lock() → Option<LockGuard> (non-blocking, None when held
elsewhere); lock() blocks; lock_timeout(dur) blocks with a typed
LockError::Timeout.
Run-and-release closures: for run-once-across-replicas work (must not run
twice) use try_with(f) → Option<T> — the winner runs the closure, every
other replica gets None and skips (check ran.is_none()). The blocking
with(f) / with_timeout(dur, f) instead serialize a mutually-exclusive
section: they block until the holder releases and then run the closure, so
every waiter eventually runs — they are not a run-once primitive. The lock
auto-releases when the section ends — normal return, early ?, or panic — and
the lock-bearing connection is never recycled to the pool while held, so it
cannot leak.
Non-goals: not fair (no FIFO), not a lease (no heartbeat — use the scheduler
for long-lived leader election), not row-level (use with_lock), Postgres
only — under the sqlite feature from_state refuses rather than pretending
to hold a lock (see below).
Lock is mutual exclusion for efficiency, not correctness. When overlap
corrupts data, use LeaseLock (Postgres only): each grant gets a strictly
larger FencingToken, the lease renews in the background, and
lease_lost() signals loss. try_with(|lease| ..) passes the Lease and
stops the closure on loss (LockError::LeaseLost). Check the token at the
resource: UPDATE .. SET fencing_token = $t WHERE .. AND fencing_token <= $t.
Behind a transaction-mode pooler (PgBouncer, RDS Proxy), session advisory
locks (Lock, migrations) are not safe; LeaseLock and the Postgres scheduler
(a tick row since #3052) work.
See docs/guide/distributed-locks.md,
docs/adr/0010-app-facing-distributed-lock.md and
docs/adr/0015-fencing-lease-lock.md.
Some subsystems are Postgres-only by construction: they open a
diesel::PgConnection and issue pg_notify / pg_advisory_xact_lock / jsonb
SQL. Autumn never picks an implementation for you, so wire them
backend-conditionally rather than assuming Postgres.
PgFlagStore / PgExperimentStore / PgConfigStore:
from_database_config(&config.database) returns None unless the configured
primary names Postgres. .expect() on it fails at BOOT on a sqlite://
target — pick InMemoryFlagStore / InMemoryConfigStore on that arm instead.PgFlagStore reads an in-memory snapshot and never connects on a Tokio
worker (issue #3063). Run PgFlagStore::spawn_poll_listener so replicas see
changes (they poll; there is no LISTEN). Before its first load, get on a
runtime returns an error: call refresh() before you seed flags, and seed
only on Ok(None). A store error serves last-known values; set a fallback
with FeatureFlagService::with_default and register it with
AppBuilder::with_flag_service.PgExperimentStore works the same way (issue #3262): get reads a snapshot
and never connects on a Tokio worker. In async handlers, call
Experiments::assign_async (or ExperimentService::assign_async), not
assign: the per-actor lookups still connect, and assign_async runs them
on the blocking pool.DatabaseConfig::effective_primary_postgres_url() is the screen to branch on
(effective_primary_url() returns the target whatever backend it names).Lock::from_state returns LockError::PoolUnavailable under the sqlite
feature: SQLite has no cross-connection advisory lock. Single-host mutual
exclusion is a Mutex.PostgresIsrCoordinator takes a Pool<AsyncPgConnection>, which a SQLite
build's state cannot produce — use the in-process coordinator.docs/guide/sqlite-in-production.md carries a support-matrix row per
subsystem; docs/guide/feature-flags.md shows the branching shape.
When advising a plugin author, start here. Autumn declares which
plugin-facing APIs are stable and which are experimental, and a plugin declares
which autumn-web versions it supports.
The registry is autumn_web::plugin_contract::PLUGIN_SURFACES; the rendered
table lives in docs/plugins.md.
stable follows STABILITY.md's SemVer promise and a
break ships with a migration-guide Plugin authors section; experimental
(today: AppBuilder::with_edge_kv, autumn_edge::host) may change in any
release, patch included.
A plugin declares its range by implementing Plugin::contract — optional, and
None (the default) keeps today's behaviour exactly:
fn contract(&self) -> Option<PluginContract> {
Some(
PluginContract::new(env!("CARGO_PKG_NAME"))
.plugin_version(env!("CARGO_PKG_VERSION"))
.autumn_web("0.11") // Cargo requirement: "0.11", ">=0.10, <0.12", "=0.11.1"
.uses_experimental("AppBuilder::with_edge_kv"), // only if you actually do
)
}
Three things to know before advising on it:
cargo update -p <plugin>, or pin
autumn-web = "<declared>"). An unparseable requirement only warns at
runtime — but autumn plugin-check fails on it, which is where the author
sees it.autumn plugin-check gained two checks, and one of them is a break for
existing plugins. plugin-contract fails when the plugin under check
declares no usable range — the plugin still compiles and runs unchanged, but
its CI goes red until Plugin::contract is implemented. experimental-surface
reports what it declares, failing only on a name that does not resolve to
an experimental entry in the registry. Both skip against a host binary built
before the contract existed; --deny-experimental fails closed in that case
rather than becoming a no-op. autumn generate plugin scaffolds the contract,
so new plugins are green out of the box.--plugin-name resolves against either identity. A contract names the
crate; route attribution keys on Plugin::name(), which defaults to
std::any::type_name. The CLI matches both, so neither choice hides a plugin
from the check.AUTUMN_PLUGIN_CONTRACT=warn, which downgrades it to a WARN. Reach for it
when a plugin's declared range is merely stale; the fix still belongs in the
plugin.autumn-plugin-reference
calls every declared stable surface and is built by the plugin-contract CI
job, so a stable-surface break is a red check on the PR that causes it. Do
not add a registry entry without a matching call site there —
scripts/check-plugin-surface.sh fails on it, and on a docs/plugins.md
table that has drifted from the registry.autumn plugin add (0.8.0, issue #1606)Reach for this instead of hand-editing Cargo.toml and the builder chain.
One command adds the dependency at a version compatible with the app's
autumn-web, mounts the plugin in the autumn_web::app() chain, and prints
the post-install steps (config keys, follow-up generators):
autumn plugin list # name, description, compatible version
autumn plugin list --json --offline # machine-readable; skip the crates.io lookup
autumn plugin add autumn-admin-plugin # dependency + mount + next steps
autumn plugin add autumn-cache-redis --dry-run
list reads the curated plugin index first (issue #1625), then crates.io.
The index lists the six first-party crates (autumn-admin-plugin,
autumn-billing, autumn-cache-redis, autumn-media-plugin, autumn-search,
autumn-storage-s3) and reviewed community crates. Each listing shows its
trust class (full trust: native code, or a sandboxed capability manifest),
its #1601 tier ([EXPERIMENTAL API] when it uses experimental surface), and
its last autumn plugin-check result. A crates.io autumn-plugin-<name>
result with no listing is shown under "Unlisted" and marked
[unlisted: not verified]. add prints the same trust review before it
changes a file. It installs a listed community crate at its verified version,
pinned with =, so --offline works. It refuses a listing flagged by
re-verification. For a sandboxed listing it changes no file and exits 2 with
manual steps. Advise users to prefer a listed plugin. An unlisted one has no
verified range and no conformance result.
Authors submit a listing by pull request: crates/autumn-cli/plugin-index/README.md.
Four behaviours worth knowing before advising on it:
add reports "already installed" and changes
nothing. It also detects a mount written by hand behind a use import, so
it will not splice a second, default-constructed mount over a configured one.autumn-web fails naming both versions, with the app
byte-identical. First-party plugins ship in lockstep with autumn-web and
the CLI, so the version installed is the CLI's — an app on an older line
needs the matching CLI, or autumn upgrade.autumn_web::app() chain
cannot be found unambiguously inside async fn main — a builder factored
into a helper, a one-line chain, two candidate lines — it writes nothing
and prints the dependency line and mount snippet on stderr, exiting 2. It
never leaves an app that does not compile.<Name>Plugin mount is
derived from the naming convention and printed, not spliced: nothing outside
that crate can verify it exposes one.It writes no features = [...] onto the app's autumn-web dependency — each
plugin crate already carries the features its mount needs and Cargo unifies
them. autumn plugin-check is the separate, author-facing conformance gate;
autumn generate plugin scaffolds a new plugin crate.
The lifecycle runs both ways, and a plugin can be wired at scaffold time:
autumn new my-app --with autumn-admin-plugin --with autumn-search # repeatable
autumn plugin remove autumn-admin-plugin
autumn plugin remove autumn-media-plugin --dry-run # every consequence, no writes
autumn plugin remove autumn-media-plugin --drop-data --yes # destructive, opt-in
remove is the exact reverse of add and refuses in the same spirit:
--drop-data reverts them in one transaction, printing the statements and
confirming before any file is written; a non-interactive stdin without
--yes is a refusal, never an assumed yes.name = "…" line.src/,
tests/, benches/, examples/ or build.rs that kept it.add: removing what is not installed says so and
changes nothing.0 removed or nothing to do, 1 refused, 2 nothing was
changed automatically (apply the printed lines by hand), 3 --dry-run
found something a real run would change.autumn new --with resolves and version-checks every name before the
scaffold writes a byte, so a typo leaves no half-built project. autumn doctor
reports leftovers as plugin_residue — see the doctor skill.
For local or pluggable file storage:
autumn-web = { version = "0.11", features = ["storage", "multipart"] }
autumn-storage-s3 = "0.11" # when storage.backend = "s3"
let store = autumn_storage_s3::S3BlobStore::from_config(&config.storage.s3)
.await
.expect("S3 store");
autumn_web::app().with_blob_store(store).run().await;
For keyword and vector search with an index that stays in sync:
autumn-search = "0.11"
#[autumn_web::model]
#[searchable(language = "english")]
pub struct Article {
#[id] pub id: i64,
#[searchable(weight = "A")] pub title: String,
#[searchable(weight = "B", embed)] pub body: String, // embed => vector search
}
// `#[repository(hooks = ...)]` takes a plain type NAME, so alias the generic.
type ArticleSearchHooks =
autumn_search::SearchSyncHooks<Article, NewArticle, UpdateArticle>;
#[autumn_web::repository(Article, hooks = ArticleSearchHooks, commit_hooks = true)]
pub trait ArticleRepository {}
autumn_web::app()
.plugin(
autumn_search::SearchPlugin::new()
.postgres()
.embedder(std::sync::Arc::new(MyEmbedder))
.index::<Article>(),
)
.run()
.await;
// In a handler: the plugin installs the client as an AppState extension.
let search = state.extension::<autumn_search::SearchClient>().expect("SearchPlugin");
let page = search.search::<Article>("rust web", &page_req).await?; // ranked Page
let hits = search.similar::<Article>("how do I add auth?", 5).await?; // k-NN
autumn search reindex [--index NAME] [--purge] rebuilds an index. See
docs/guide/search.md.
For shared Redis cache:
autumn-web = { version = "0.11", features = ["redis"] }
autumn-cache-redis = "0.11"
autumn_web::app()
.plugin(autumn_cache_redis::RedisCachePlugin::new())
.run()
.await;
(0.6.0) Cache stampede protection — do not hand-roll cache-aside
fills: cache::get_or_compute(cache, key, Some(ttl), fill) runs fill once
per process for concurrent callers; get_or_compute_with +
GetOrComputeOptions::new().distributed_fill_lock(true) (Redis lock) and
.stale_while_revalidate(grace) add cross-replica single-fill and
serve-stale; cache::jittered_ttl(base, fraction) de-synchronizes mass
expiry. A failed fill never poisons the key. See
docs/guide/cache-stampede.md.
(0.6.0) Upload content-type validation — multipart uploads are
validated by magic bytes, not the spoofable client Content-Type. The
Multipart extractor sniffs the real type (sniff_content_type) whenever an
allowed_content_types allow-list is configured or strict mode is on. Reject
spoofs with:
[security.upload]
reject_on_content_type_mismatch = true # declared-vs-sniffed mismatch (or an
# unsniffable declared-binary) → rejected
(env AUTUMN_SECURITY__UPLOAD__REJECT_ON_CONTENT_TYPE_MISMATCH) (#1354).
Core widgets need only maud. Four families are default-on features
(0.10.0, #3408): widgets-search (active search, autocomplete), widgets-social
(reactions, comment thread, infinite feed, the #[commentable] router),
widgets-workflow (transition controls, bulk actions) and widgets-charts.
With default-features = false, name each family the app uses. Paths stay
autumn_web::widgets::* (docs/guide/widget-styling.md).
Trunk-dev ships framework view widgets — prefer these over hand-rolled Maud for the common cases:
| Helper | Purpose |
|---|---|
link_to(label, href) / link_to_with(..., &LinkToOptions) | Escaped GET anchors; auto rel="noopener" on target="_blank" |
button_to(label, href, Method, csrf_token) / button_to_with | Single-button form for state-changing actions; CSRF is a required arg; non-GET emits hidden _method override |
card(&body, &CardConfig::new().title("...")) / stat_card(label, value, link) | Titled panels and metric tiles (autumn_web::widgets, prelude re-export) |
sparkline(&points) / bar_chart(&series) / line_chart(&series) (+ _with(&ChartConfig)) | Server-rendered, accessible, zero-JS SVG charts from &[(&str, f64)] (/_stories gallery). bar_chart anchors bars at zero; ChartConfig::new().title(...).min(...).max(...) sets an axis override / accessible name (#1231) |
tabs(id, Some(active) | None, &[(id, label, markup)]) | Tab switcher: :target CSS with JS off; APG arrow keys with autumn-widgets.js (docs/guide/tabs.md, docs/guide/keyboard.md) |
popover(label, &content, &PopoverConfig::new(id).side(..).align(..)) / dropdown_menu(label, &[MenuEntry::link/action/separator/group(..).destructive()], &PopoverConfig::new(id)) | Native popover + command/commandfor + CSS anchor positioning (flips at the edge); dropdown_menu is an APG menu button (role=menu, button_to items with CSRF work with JS off, arrow keys/typeahead need autumn-widgets.js). NavMenu uses the same markup (0.10.0, #3402, docs/guide/popover-and-menu.md) |
accordion(&[(title, markup)], &AccordionConfig::new(name)) / collapsible(summary, &markup) / collapsible_with(.., &CollapsibleConfig) | No-JS disclosure on native <details> (0.10.0, #3401). Exclusive by default (shared name); .multiple() lets items open on their own; .open(i), .level(HeadingLevel), .class(), .attrs(). Titles are escaped; Enter/Space on <summary> are native (docs/guide/accordion.md) |
modal(id, title, &body, &ModalConfig) / confirm_action(...) | Native <dialog> confirm for destructive actions — replaces hx-confirm/window.confirm() |
drawer(id, title, &body, &DrawerConfig) / drawer_trigger(...) | Edge <dialog> (left/right/top/bottom), modal or not; DialogSize and close_button(label) also on ModalConfig (docs/guide/drawer.md) |
badge(label, BadgeVariant::for_label(status)) / status_tag(label) | Semantic status pill; BadgeVariant = Neutral/Info/Success/Warning/Danger, for_label picks a deterministic color; badge_with/BadgeConfig set title/aria-label. Composes inside a data_table cell |
avatar(name, &AvatarConfig::new().image(url).size(AvatarSize::Small)) | Person chip: <img> (lazy, square, name alt) or a deterministic colored-initials fallback — never a broken image, no JS, no external call |
alert(AlertVariant::Info, body) / alert_with(..., &AlertConfig::new().title("...").icon(true).dismissible(true)) | Inline callout / empty-state / error box; role per variant, optional title + inline-SVG icon + no-JS dismiss. error_summary(&changeset) renders an Error alert of all field errors (or None when valid); each entry links to #field and the summary takes focus |
flash_messages(&flash.consume().await) (autumn_web::flash) | Accessible flash banners: per-severity role/aria-live, autumn-flash--<level> classes, empty slice renders nothing; flash_messages_with adds a no-JS dismiss |
pagination_nav(&page, &PagerOptions::new("/posts")) / cursor_pagination_nav | Accessible, filter-preserving, htmx-opt-in pager from a Page/CursorPage (prelude re-export) |
toast(message, variant) / toast_region(DEFAULT_TOAST_REGION_ID) / toast_in(region_id, ...) / toast_with(message, variant, &ToastConfig) | Transient htmx action feedback: drop toast_region once in the layout, then return toast(...) next to your swapped fragment — it appends into the region OOB (hx-swap-oob="beforeend:#toast-region"). CSS auto-dismiss (no <script>); hover/focus pauses it; ToastConfig sets duration, persistent, region, close_label. A close button (shown by autumn-widgets.js; hidden without JS) removes the toast; the region is popover="manual" so it sits above modals; variant reuses AlertVariant. toast_region is a persistent aria-live="polite" region — non-error toasts inherit its politeness (no own role/aria-live); Error announces assertively via its own role="alert" |
tooltip(id, text, |tip| html! { button aria-describedby=(tip) {…} }) / tooltip_with(id, text, &TooltipConfig::new().placement(TooltipPlacement::Bottom), …) | Accessible tooltip (0.10.0, #3404). The closure gets the text id: put it in aria-describedby (or aria-labelledby for an icon-only trigger). Text only — use a popover for links or buttons; never use title as a tooltip. CSS shows it on hover and keyboard focus and places it with anchor positioning; Escape hides it (keyboard core data-autumn-dismiss="escape"); a hover bridge keeps it open (WCAG 1.4.13). On Chromium the runtime adds interestfor + popover="hint" (docs/guide/tooltip.md) |
button(label, &ButtonConfig::new().variant(ButtonVariant::Secondary).size(ButtonSize::Small).icon(svg)) / button_group(label, &[buttons]) | Styled <button> (0.10.0, #3406): Primary/Secondary/Ghost/Destructive/Link, .submit(), .icon_only() (label stays as hidden name), .disabled(), .attrs(&[("hx-post", url)]) (passes through as given; widget-owned names win). .loading() = static aria-busy="true" + disabled + spinner; .loading_on_request() = data-autumn-busy: busy during its own request (it sends it, submits the form, or hx-indicator names it); the runtime sets aria-busy on it and the swap target and clears it on loadend. Use hx-sync="this:drop" against double clicks, not hx-disabled-elt (focus loss). Classes also style link_to_with/button_to_with. button_group is a named role="group" (docs/guide/display-widgets.md) |
spinner(label) / skeleton(SkeletonShape::Line) (+ _with, .indicator(id)) | role="status" spinner with hidden label (reduced motion: fades, no turn); aria-hidden line/block/circle skeleton (.count(n)). .indicator(id) adds autumn-indicator: hidden until .htmx-request (a spinner keeps its role="status" root and hides its content) — point hx-indicator="#id" at it (no htmx inline style needed) |
progress(label, Some(v), max) / meter(label, v, min..=max) (+ _with) | Native <progress>/<meter> with aria-label; values clamped, None/NaN progress = indeterminate; MeterConfig::low/high/optimum, .visible_label(), .value_text("3 of 8") (also aria-valuetext) |
separator() / kbd("Esc") / kbd_combo(&["Ctrl", "K"]) / empty_state(title, body, Some(&action)) / avatar_group(label, &avatars) | <hr> (vertical = role="separator", decorative = role="none"); nested <kbd>; empty state with heading (EmptyStateConfig::level/icon); overlapping avatars with +N (AvatarGroupConfig::max counts the +N item, default 5; .total(n), .more_label("{count} more")). FieldOptions::auto_grow() / a11y::TextArea::auto_grow() = field-sizing: content textarea |
infinite_feed(items, next_cursor, &FeedConfig) / feed_page(items, next_cursor, &FeedConfig) | htmx infinite-scroll / "Load more" feed from a CursorPage: single hx-get sentinel carries the cursor and appends the next page in place (no reload, no duplicate rows). FeedMode::{Reveal,Button}; progressive <a href> fallback. feed_page is the append fragment a handler returns for each page (page.next_cursor.as_deref()) |
bulk_actions_form(&BulkActionsConfig, csrf_token, csrf_field, submit_token, submit_field, content) / bulk_select_checkbox(id, &cfg) / bulk_actions_toolbar(&cfg) | No-JS bulk-select + "Delete selected" over a list (#1312): wrap the list in bulk_actions_form (a POST form carrying the hidden CSRF and one-time submit-token fields plus the submit button), and put one bulk_select_checkbox — name="ids", aria-label="Select row <id>" — in each row's first cell. Keep page furniture ("New …" link, search box) outside the form. Always pass the submit-token pair on a destructive form: a tokenless request passes through SubmitTokenLayer unguarded, so a double-click would re-run the whole batch. BulkActionsConfig::new(action) + .field_name(..)/.submit_label(..)/.select_label(..). The toolbar emits no confirmation prompt: inline onclick confirms are blocked by the default script-src 'self' CSP, and confirm_action submits its own form so it cannot carry the selection — to confirm a batch, post it to an interstitial page that lists the rows and asks for a second submit. autumn generate scaffold wires all of this automatically |
comment_thread(&cfg, &CommentView::from_thread(&nodes)) / CommentThread::new(dom_id, action) | The view half of #[commentable] (#1367): nested <ol> comment thread with a <details>-disclosed inline reply form on every node. Ordinary <form method="post"> (works with scripting off) that also carries hx-post/hx-target/hx-swap="outerHTML" to swap the thread in place. Thread .csrf_token(...) and .return_to(path) for the no-JS round trip, .max_depth(n) so the UI never offers a reply the write path would 422, .read_only(Some(prompt)) for a signed-out visitor |
active_search(id, label, &ActiveSearchConfig) / active_search_empty_state(msg) | Search box whose results appear as the user types — htmx-driven, server-rendered Maud fragments; you author no JavaScript, but the page must load htmx. The handler returns the results fragment; active_search_empty_state is the no-matches body. Emits a <noscript> GET-form fallback (docs/guide/active-search-and-autocomplete.md) |
autocomplete_input(id, label, &AutocompleteConfig) / autocomplete_option(value, label) / autocomplete_empty_state(msg) | Typeahead/autocomplete picker for choosing a related record and storing its ID — the companion to active_search when the user must pick one row rather than browse matches. Selection and input sync need the shipped autumn-widgets.js runtime (<script src="/static/js/autumn-widgets.js" defer>, no inline JS, CSP-compatible) on top of htmx; include it once in the layout or the picker will not select. Its <noscript> fallback is a bare <select>, NOT a form like active_search's — it has to sit inside the surrounding application form to submit (docs/guide/active-search-and-autocomplete.md) |
AutocompleteConfig::multiple() (+ .free_text(), .selected(..)) / autocomplete_input_for(&changeset, id, label, &config) / autocomplete_create_option(value, label) | Tags / multi-select (0.10.0, issue #3410): each pick is a removable chip with one hidden name=value input, so bind a #[serde(default)] Vec<T> field — repeated keys decode into it. Use autocomplete_input_for on a 422 re-render: the changeset is the source of the chips and its field errors show. Return autocomplete_create_option after the matches for a "create new" entry; with free_text(), Enter adds the typed text. Validate and de-duplicate new values on the server. Needs autumn-widgets.js; the no-JS fallback is a <select multiple> that shows only fallback_options (docs/guide/active-search-and-autocomplete.md) |
storage::form_helper::direct_upload_field(name, presign_url, &DirectUploadConfig::new().label(..).accept(..).multiple(..)) / direct_upload_input(name, presign_url, accept) | Direct-to-storage file field (feature storage, 0.10.0, #3411). With autumn-widgets.js it POSTs {filename, content_type, size} to your presign route (CSRF token from <meta name="csrf-token">), reads {url, method, headers, key}, sends the file with a progress bar (drag and drop works) and adds a hidden name=key field. The form carries only keys: check each key's prefix, then call complete_direct_upload. Without JS it is a plain file input in a multipart/form-data form. Has a visible <label> and live status and error regions (docs/guide/storage.md) |
local_datetime(dt, &tz) (autumn_web::time_zone) | Render a Timestamp in a user's IANA zone. Pair with the TimeZone extractor (resolves the requesting user's zone; it derefs to a jiff::tz::TimeZone, which is Clone, not Copy, so pass &tz) and set_time_zone_in_session / parse_iana; take "now" from the Clock extractor rather than Timestamp::now() so rendering stays test-injectable (docs/guide/time-zones.md) |
wizard_progress(&ctx, step).await / wizard_progress_from_steps(&[WizardProgressStep]) (autumn_web::wizard) | Accessible step-progress <nav> (aria-current="step", "Step N of M"). wizard_progress reads step states from the session; wizard_progress_from_steps is the sync form for steps you already have (0.10.0, #3398). The /_stories gallery shows it with pagination, flash and the a11y primitives |
WidgetPack::new("pack").extend(stories).assets(&ASSETS) + app.widget_pack(pack) (autumn_web::widget_pack) | Ship widgets as a plugin crate (0.10.0, #3400). Contract: Render, &FieldOptions passthrough, public tokens only (no raw colors, no setting --primary), autumn-<pack>-* classes, keyboard core data-* + autumn:init (no own arrow-key JS), CSP-safe, one story per widget with slug <pack>-…. with_story_gallery now ADDS (plugin galleries start from StoryGallery::new()). Non-input widgets write their root with widget_pack::element(tag, attrs, &FieldOptions, body). Form inputs: impl FieldRenderer + FieldContext::control (radios: grouped() + group_item), then custom_input_with(&cs, …) or form_for(..).override_field(f, FieldControl::custom(R)). Check with plugin_conformance::widgets::run_widget_conformance and (feature system-tests) browser::run_widget_browser_conformance(&pack, &axe_src) (docs/guide/widget-packs.md) |
autumn_web::ui::WIDGETS_CSS / WIDGETS_CSS_PATH | One shipped stylesheet backing every autumn-* widget class — link href=(WIDGETS_CSS_PATH) instead of copying widget CSS into input.css. Accent now follows var(--primary) (violet), not the old hardcoded indigo (docs/guide/widget-styling.md) |
theme_toggle(&ThemeToggleConfig::new(theme).csrf(token, "_csrf")) + ui::theme::{Theme, Density, router} | Dark mode (0.10.0, #3396). Tokens are light-dark(): the OS selects the scheme, data-theme="light|dark" overrides it, data-density="compact|comfortable|spacious" scales --space-*. Theme is an extractor for the autumn.theme cookie — render html data-theme=[theme.data_theme()] in the layout. .merge(ui::theme::router()) mounts the no-JS POST /_autumn/theme; autumn-widgets.js applies it in place. Classes are autumn-alert--<v>, autumn-badge--<v>, autumn-wizard-* (no unprefixed alert/badge/wizard-*). Text on a --primary/--danger fill uses --on-primary/--on-danger, never white (docs/guide/widget-styling.md) |
autumn_ui::{Document, fixture::{Catalogue, Fixture, Method, MockRequest}, tokens, theme} | The design layer as its own crate (crates/autumn-ui, ADR 0054). It depends on maud only, so put an app's layouts and components in a sibling <app>-ui crate that depends on autumn-ui, not autumn-web: it rebuilds in seconds. Markup is a pure function of a view model: the handler loads, checks permissions and builds the model, then calls in. Name assets by served path and resolve them through AssetUrls. Catalogue lists Fixture::page/Fixture::fragment mocks (one per state: empty, redacted, read-only) and Mock routes ({id} segments, req.param("q")) that answer hx-* requests with no backend. autumn_web::ui::{tokens, theme} re-export it; tokens::inspect::contrast checks WCAG on a re-theme. autumn_ui::concat_const! joins const CSS at compile time |
StoryGallery::builtin().catalogue(app_ui::catalogue()) | Show a UI crate's autumn-ui fixtures in /_stories: slug ui-<id>, fixture group and title, the shell's stylesheets linked on each gallery page, /_stories/{slug}/page renders the fixture in the catalogue's shell (a page fixture is only linked, not inlined). Mock routes are not mounted. Render UI crate markup in a handler with autumn_web::assets::Fingerprinted as the AssetUrls (content-hashed URLs). See docs/guide/stories.md |
autumn_ui::widgets, autumn_ui::links | Widgets as pure maud functions a UI crate can call with no autumn-web dependency: layout (card, modal, drawer, tabs, button, ...), feedback (alert, toast, progress, meter, confirm_action, error_summary over (field, &[String]) pairs), property_list, data_table (+ SortDir), badge, avatar, avatar_group, kbd, and with widgets-charts sparkline/bar_chart/line_chart. navigation (nav_bar, breadcrumb, theme_toggle, dropdown_menu, ...), with widgets-search active_search/autocomplete_input (autocomplete_input_with_values takes submitted values), with widgets-social reaction_controls/comment_thread/infinite_feed, with widgets-workflow transition_controls/bulk_actions_form. autumn_ui::links has link_to, button_to and method_input; a method is impl AsRef<str> (a string or http::Method). autumn_ui::csrf has CsrfToken/CsrfFormField (extractors with the axum feature). autumn-web re-exports them at autumn_web::widgets, autumn_web::links and autumn_web::security (SortDir also at autumn_web::pagination; there error_summary and autocomplete_input_for take a &Changeset). CommentView::from_thread and CommentThread::from_spec are methods of the prelude traits CommentViewFromThread/CommentThreadFromSpec (ADR 0054 amendments 5 to 8) |
autumn_ui::widgets_css | The widget CSS: WIDGETS_CSS (tokens + core + enabled families), WIDGETS_COMPONENT_CSS, WIDGETS_CSS_PATH. autumn-web re-exports them as autumn_web::ui::*; its widgets-* features turn on autumn-ui's features of the same name. Edit widget rules in crates/autumn-ui/src/widgets.css and widgets/<family>.css |
autumn_ui::preview::Preview (feature preview), autumn_ui::scripts | Preview a UI crate's Catalogue with no database or app build: Preview::new(catalogue).static_dir("../static").plugin_assets("motion", dir).csp(policy).bind("127.0.0.1:7878")?.run(). It serves / (fixture index), /_autumn/ui/fixtures/{id}, real htmx and the CSRF helper at their /static/js/ paths, the tokens and every widget family's CSS (autumn_ui::widgets_css::WIDGETS_CSS_ALL) at /static/css/autumn-widgets.css, the app's static/ tree (custom JS wins over a framework file), plugin assets at /static/_plugins/{ns}/, mock routes for every other request, the app's CSP on every response, and live reload. scripts holds the htmx, SSE, idiomorph, CSRF and live-reload JS autumn-web serves, and DEFAULT_CSP. A UI crate's binary calls autumn_ui::preview::run(catalogue()), which reads the AUTUMN_UI_* settings autumn dev --ui sets. See docs/guide/ui-preview.md |
form_for (0.6.0)#[model] derives autumn_web::form::FormModel (one FormField per
NewX-editable column: humanized label, type-appropriate FieldControl,
required = non-Option), and form_for renders the entire <form> from a
Changeset in one call — opening tag with CSRF and hidden _method override
(same audited path as form_tag), pre-filled controls with inline per-field
errors, and a submit button. Import from autumn_web::form (not in the
prelude):
use autumn_web::form::{form_for, FieldControl};
// changeset: Changeset<Post> — blank for `new`, error-carrying on 422 re-render
let markup = form_for(&changeset, "/posts", "post") // non-GET/POST method emits hidden _method
.csrf(&csrf_token) // .csrf_field_name(...) overrides "_csrf"
.exclude("internal_notes")
.override_field("status", FieldControl::Select {
options: vec![("draft".into(), "Draft".into()), ("published".into(), "Published".into())],
}) // last call wins per field
.override_label("body", "Content")
.submit_label("Publish") // default "Save"
.render();
Derived control mapping: strings/Uuid/unknown types → Text (promote enums
via .override_field), integers → Number (step 1), floats/Decimal →
Number (step any), bool → Checkbox (nullable bool → tri-state
Select), civil::Date → Date, civil::Time → Time,
civil::DateTime/Timestamp/ZonedDateTime → DateTime (a Timestamp
reads the offsetless datetime-local value as UTC, a ZonedDateTime in the
server's zone). The jiff types come from autumn_web::time; a bare Date,
Time or DateTime must be jiff's civil type. Any
FieldControl::File field (or .multipart()) makes render() emit
enctype="multipart/form-data".
Round-trip contracts are handled by the #[model]-generated NewX: unchecked
checkboxes decode as false (#[serde(default)] — checkbox_input emits no
hidden false fallback), and datetime-local submissions decode via the
deserialize_datetime_local_utc[_option] /
deserialize_datetime_local_local[_option] /
deserialize_naive_datetime_local[_option] helpers (which also still accept
RFC 3339 JSON bodies). Serde-renamed columns pre-fill correctly via
FormField::value_name (set automatically by the derive; hand-written
FormModel impls use FormField::new(...).with_value_name(...)). Trunk-dev
autumn generate scaffold views render through a single shared
{snake}_form_for helper built on this (except --live-validation, which
keeps per-field htmx emission).
For master-detail (has-many) forms saved atomically — an order plus its
line items in one submit — use autumn_web::nested_form (0.6.0, #1915) instead of hand-wiring indexed field names: implement
NestedChild on the child new-model, render the child rows with
inputs_for(&nested, &InputsForOptions, |row| …) (add/remove rows + a
destroy_checkbox for deletes) off a NestedChangesetForm<Parent, Child>, and
decode the flat submission back into parent + children with
decode_nested_urlencoded, so the parent and its children validate and persist
as one transaction.
Multi-value fields and file parts (issue #3394). Don't hand-parse repeated
keys (a parse_bulk_ids-style helper over the raw body). A repeated key fills a
Vec<T>, HashSet<T> or Option<Vec<T>> field of a ChangesetForm /
NestedChangesetForm target, so checkbox groups, <select multiple> and tag
inputs decode directly. Give the field #[serde(default)] so "none checked"
decodes as empty, and #[serde(alias = "ids[]")] to accept the bracketed
spelling (brackets are part of the key). A repeated key on a single-value field
is a 422 naming the field, never "last value wins". A blank element of a typed
list (ids=) is dropped. For a raw Bytes body, form::from_urlencoded::<T>
applies the same rules and returns a FormDecodeError (status() is 422 or
400). Changeset::field_values(field) re-renders every element of a sequence
field; in a nested row, row.values(sub) does the same. On a multipart/form-data body, file parts reach the handler through
form.file(name), form.files(name) and form.take_files() (FormFile), under
the security.upload policy. In a test, build one with FormFile::new and
ChangesetForm::with_files. See docs/guide/forms.md.
Don't hand-write an HTTP client to call another Autumn service in the same workspace, and don't keep a schema alongside it. The callee's handler signatures are the contract.
Callee:
#[derive(serde::Serialize, serde::Deserialize, WireShape)]
pub struct Item { pub id: String, pub name: String }
#[endpoint(service = "catalog")] // MUST sit above the route attribute
#[get("/items/{id}")]
#[public]
pub async fn get_item(id: Path<String>) -> AutumnResult<Json<Item>> { … }
Caller:
wire_client! {
name = CatalogClient,
endpoints = [catalog::get_item_endpoint(id)], // (…) lists path params
}
#[contract_checked(client = CatalogClient)]
#[get("/items/{id}")]
#[public]
async fn show(id: Path<String>, http: Client) -> AutumnResult<Markup> {
let catalog = CatalogClient::new(catalog_url(), http);
let item = catalog.get_item(&*id, NoBody).await?; // NoBody = no request body
Ok(html! { h1 { (item.name) } })
}
#[endpoint] emits get_item_endpoint plus a JSON descriptor under
target/autumn-contracts/. It reads the request/response types off the
signature and the method/path off the route attribute below it.
wire_client! generates one method per endpoint, typed with the callee's own
types. A body-less endpoint takes NoBody.
#[contract_checked] fails the build at the call site when a response field
the function reads is no longer produced, a request field it sets is no longer
accepted, or a ..Default::default() request omits a newly-required field.
It refuses a client it cannot find a value for, so it never passes vacuously.
? on a failed call produces 502, not 500: the dependency failed, not the
caller's client.
#[derive(WireShape)] refuses generics, enums, tuple structs,
#[serde(flatten)] and split renames rather than describing them wrongly.
Across releases (0.11.0): autumn contracts export --out contracts.json writes a
sorted, byte-stable bundle; store it with each release.
autumn contracts check --against <bundle|url|git-ref> checks both deploy
windows (new callees with deployed callers, new callers with deployed
callees). Exit 0 safe, 1 not safe, 3 safe in one order only (the report
names it; --order callee-first|caller-first declares it), 4 tool error.
The bundle (format 4) finds a type by its path, not its last name: write
the path where the type is defined (Json<shared::Item>,
Json<crate::dto::Item>) when two reachable crates have an Item, or the
export stops. A path through a re-export or a use … as alias does not
name the type. Nested WireShape types are compared
field by field (details.color). struct Empty; (JSON null) and
struct Empty {} ({}) are different shapes.
A field whose type has no WireShape and is not a known leaf (an enum, for
example) stops the export: mark it #[wire(opaque)] to compare it by type
name only. Do not add WireShape to an enum: the derive refuses it.
Each field records its wire type (the JSON form). A field with
#[serde(with)] is any: name its form with
#[wire(type = "integer", format = "unix-seconds")]. type is string,
integer, number, boolean or any; another value does not compile.
Add nullable for an Option under another name. The check reports a new
JSON form with the same Rust type (bundle format 4).
An #[endpoint] must be in a routes![…] call. Taking it out of the router
is a removed route. For a handler of another crate, write its crate path
(routes![mesh_catalog::get_item]), so the check judges that crate. autumn contracts export --from <dir> joins an existing
descriptor directory with no build. --from <file> reads a bundle file.
Outside the workspace (0.11.0): autumn contracts export --proto --out contracts/proto/
writes .proto schemas (one file per service, one per crate for events, a
buf.yaml). json_name is the serde wire name. proto.lock (beside
--out) keeps field numbers; commit it, and run --check in CI (exit 1
when stale). #[wire(tag = N)] pins a number. Wrapper messages
(…Wrapper) hold shapes protobuf cannot write in place; their JSON is not
Autumn's, so a consumer unwraps by hand. --http-annotations adds
google.api.http options. --well-known-types maps date-time to
Timestamp.
Events for data pipelines (0.11.0): autumn contracts export --avro --out contracts/avro/
writes one .avsc per topic (a new version is a new subject). Field names
are wire names; #[serde(alias)] is an Avro alias; nested types are named
records; an opaque event is bytes. It refuses u64/usize/128-bit
(use a smaller type, or a string adapter plus #[wire(type = "string")])
and any fields (name the form with #[wire(type = …)]). The schema is for the data,
not Avro's JSON encoding. --endpoints adds bodies; --check exits 1 when
stale. Registry mode: FULL (any order), FORWARD (callee-first),
BACKWARD (caller-first).
Limits: one workspace, sync request/response, JSON over HTTP. Guide:
docs/guide/wire-contracts.md; example: examples/mesh-catalog +
examples/mesh-storefront.
Don't hand-roll Last-Event-ID bookkeeping or a manual replay buffer for
server-sent events. Since 0.6.0 the ws-gated channels backend keeps a
bounded per-topic replay ring buffer and assigns every event an
epoch-tagged per-topic id automatically (wire format epoch.seq, opaque
to clients) — no manual .id(...) in handler code.
autumn_web::sse::stream_resumable(&state, topic, last_event_id) is the route
primitive. It reads the client's Last-Event-ID, replays the buffered events
the client missed in order, then continues live — no duplicated or skipped
events at the seam (publish assigns seqs and broadcasts under one lock; resume
subscribes under that same lock and snapshots the buffer). Within one epoch it
replays entries with seq > last_event_id.seq; across an epoch boundary it
gaps and replays the full retained current epoch (see Limitations).autumn_web::sse::last_event_id(&headers) →
Option<EventId> (EventId { epoch: u64, seq: u64 }, exported as
autumn_web::sse::EventId and re-exported autumn_web::channels::EventId), or
the autumn_web::sse::LastEventId(pub Option<EventId>) extractor (never fails;
absent/malformed/legacy-bare-integer → None → treated as a cold connection).None) behaves exactly like sse::stream: no replay,
just live events, dense seqs preserved.gap event (event: gap, data: {"gap":true}, no id) before the
replay so clients can detect missed events rather than silently receiving a
hole. A live broadcast lag surfaces the same gap sentinel and advances the
seq counter.sse::stream, sse::stream_authorized,
sse::from_subscriber, Channels::sse_stream — are unchanged and remain
id-less; stream_resumable is purely additive.ResumeHandle
(Channels::resume(topic, last_event_id) -> ResumeHandle is available on any
backend).use autumn_web::prelude::*;
use autumn_web::sse::LastEventId;
#[get("/events")]
async fn events(State(state): State<AppState>, LastEventId(last): LastEventId) -> impl IntoResponse {
autumn_web::sse::stream_resumable(&state, "feed", last)
}
Retention is configurable via channels.replay_buffer (N, default 256;
env AUTUMN_CHANNELS__REPLAY_BUFFER). Memory is O(N) per topic regardless of
throughput. This is distinct from channels.capacity, which sizes the live
broadcast fan-out ring.
Limitations (in-process best-effort scope, per issue #1356's "Out of Scope") — the replay buffer is a same-process convenience, not a durable log:
Sender). A topic with only transient SSE
subscribers can lose its buffer during the disconnect window. The recreated
topic gets a new epoch, so a reconnect across the gap is not silently
corrupted: the epoch mismatch is signalled as a gap sentinel plus a full
replay of the current epoch (the old epoch's events themselves are gone).seq counter
resets to 1 under a fresh epoch. The epoch tag means a stale Last-Event-ID
from a previous epoch — even one whose seq the new epoch has already passed —
is always distinguishable from a current-epoch id, so the reconnect yields a
gap sentinel followed by a full replay of the current epoch rather than
silently dropping the new epoch's early events (the pre-epoch-tag hole, issue
#1356). The buffered history from before the restart is still gone (persist it
yourself for durability), but the client is never fed a corrupted partial.channels.publish() / broadcast().publish() /
channels.sender().send() is safe on resumable topics: all three route
through the backend's publish, assigning a seq and appending to the replay
buffer. Only calling .send() directly on the raw broadcast::Sender
(obtained from channels.sender().keepalive or the ensure_topic trait
method) broadcasts without assigning an id or appending to the replay buffer,
which breaks resumability for that topic.For cross-restart / multi-replica durability, back the stream with a durable log (e.g. a database table or a Redis stream) instead of the in-process buffer.
Config layering, lowest to highest:
dev / prod)autumn.toml[profile.<name>] inside autumn.tomlautumn-{profile}.tomlAUTUMN_* environment variablesProfile selection precedence:
AUTUMN_ENVAUTUMN_PROFILE--profile <name>Use AUTUMN_SECTION__FIELD for env overrides, for example
AUTUMN_DATABASE__PRIMARY_URL, AUTUMN_JOBS__BACKEND,
AUTUMN_SECURITY__SIGNING_SECRET, and
AUTUMN_SECURITY__WEBHOOKS__REPLAY__BACKEND.
Scale HTTP and background work independently by giving a process a role (no
app-code change) via role = "web"|"worker"|"combined" in config or the
AUTUMN_ROLE env var:
| Role | Serves HTTP | Runs workers + scheduler |
|---|---|---|
combined (default) | yes | yes — unchanged behaviour |
web | yes (can still enqueue jobs) | no |
worker | no (probe-only router) | yes |
autumn serve --role web|worker|combined.combined
(0.10.0, #3541). role and AUTUMN_ROLE accept the same values (case-insensitive;
aliases in ProcessRole::ACCEPTED_VALUES). An empty AUTUMN_ROLE= is unset.
autumn doctor shows the same error on its process_role_backend row.combined) role requires a postgres/redis/sqlite jobs
backend — an in-memory queue can't cross processes. sqlite qualifies only
within one host, since its queue is a table in one file (#1907).release init --split-workers splices a dedicated worker: service into the
generated docker-compose output and sets the web-tier role on the app
service (#1613). See docs/guide/cloud-native.md.The Redis backend keeps the newest jobs.redis.dead_letter_limit dead letters
(default 10 000; 0 = unbounded). A trim removes the oldest entries and their
replay metadata, logs a warn, and increments
autumn_jobs_dead_letter_trimmed_total on /actuator/prometheus. Alert on
that counter. Postgres and SQLite have no count limit: failed rows stay until
retention.job_history deletes them by age. See docs/guide/jobs.md.
ProcessRole on AppState (0.6.0)Carve the per-process worker pool up per queue and dedicate a worker tier to a subset of queues — all config-only, no app-code change:
[jobs.queues] value a table:
critical = { weight = 4, reserved = 2 } keeps 2 slots that no other queue may
ever consume; bulk = { weight = 1, concurrency = 4 } caps a queue at 4 of the
process's jobs.workers slots. A bare integer is still just a weight. Total
capacity stays jobs.workers; the rules only redistribute it and are enforced
on every backend (local/Postgres/Redis).jobs.pin = ["critical"] (or AUTUMN_JOBS__PIN=bulk,default,
comma-separated) makes a worker-role process claim only those queues,
preserving weighted/strict order within the subset; empty/unset drains every
queue. A worker leaving a configured queue uncovered logs a startup WARN
(an ERROR if it would claim nothing). autumn doctor's
jobs_queue_coverage check reports informationally when no fleet topology is
declared; declare every tier's pin under [jobs.fleet] tiers and it hard-fails
(exit 1, in every mode — not only --strict) on a queue drained by no tier
(issues #1623, #1756). autumn serve --pin <queues> sets the pin as a flag,
forwarding AUTUMN_JOBS__PIN, and serve restart restores it.<actuator-prefix>/jobs adds a queues key
with per-queue depth and oldest_waiting_age_ms alongside the existing
per-job-type gauges (per-process approximations on multi-process backends).queues gauges and the
per-job-type queued counter are no longer per-process approximations: a
periodic survey of the durable store (Redis every 2s, the interval doubling as
the gauge cache TTL) wholesale-replaces this process's local enqueue marks each
tick, so an enqueue-only web replica reports the true shared backlog and a
queue absent from the latest survey resets to depth 0. The Redis survey pages
the whole due-delayed ZSET so scheduled/retry bursts count exactly. The local
backend keeps the in-process mark path. See docs/guide/jobs.md.Role on AppState — state.role() returns the resolved
Role (exported at autumn_web::Role) with serves_http() /
runs_workers() predicates (issue #1726).
state.capabilities() returns the RoleCapabilities resolved at boot: one
field for each subsystem (job_workers, scheduler, outbox_relay,
commit_hooks, fleet_relay, restore_check, retention, maintenance,
serves_http).
Gate on the field that matches the work. /actuator/info shows the set
(0.10.0, issue #3542). See docs/guide/jobs.md#role-capabilities.tokio::spawn a loop in
on_startup: every role runs it. Use
app.background_task("media.reaper", Capability::Maintenance, |state, shutdown| async move { .. }).
The framework starts it only where the role runs the capability and waits
for it in the drain. PluginCapability::new("harvest.worker", Capability::JobWorkers) follows its parent; a preset sets it with
capabilities = { "harvest.worker" = false } (the base must run the parent
for true; an unknown key stops the boot of that role). app.background(BackgroundTask::new(..) .queues([..]).explicit(cfg)) adds queues (job workers and the pin apply) and the plugin
switch (wins, with a warning). /actuator/tasks (background_tasks) and
autumn graph (background_task nodes) list the roles that run each task.
See docs/guide/jobs.md#background-tasks-for-plugins-and-apps.autumn-media-plugin registers
media.room_reaper (db store: media.maintenance, on combined/worker;
memory store: serves_http, on combined/web) and
media.recording_retention (media.retention + the media queue). For a
fleet of only web replicas, call MediaPlugin::room_reaper_on_every_role()
and retention_on_every_role(). autumn-billing registers
billing.dunning_rearm (billing.dunning + queue billing): web does
not re-arm. Turn one off on a named role with
capabilities = { "media.maintenance" = false }. spawn_room_reaper_loop
and spawn_retention_sweep_loop are deprecated: call run_room_reaper /
run_retention_sweep from a background_task. The xtask test
plugin_spawns fails on a spawn in a plugin's on_startup or
state_initializer. See docs/guide/media.md#background-tasks-and-roles.[roles.<name>], 0.10.0, issue #3543) — declare a tier once as a
preset: base (combined/web/worker), pin, workers and capability
overrides that can only turn a built-in capability off (a plugin capability
in capabilities can be true where the base runs its parent). Select it with
AUTUMN_ROLE=<name>. state.role() returns &Role: .name() is the
preset name, .base() the ProcessRole. Guards read the base; an
undeclared name stops the boot. autumn doctor --strict derives
[jobs.fleet] tiers from the presets. See docs/guide/jobs.md#named-roles.#[get("/x", group = "marketing")],
.routes_in("marketing", routes![...]) or Plugin::route_group() (default
Plugin::name()) put routes in a group; the default is app. A preset over
web/combined sets mount = ["marketing"] to serve only those groups.
Probes, actuator and assets stay on every role; other routes get 404. Graph
and OpenAPI follow the mount. [route_groups] declared/manifest lets
autumn doctor --strict fail on a group no preset mounts. See
docs/guide/route-groups.md.Connect Autumn's built-in failure signals to email + a signed webhook with no
app code — configure a destination under [alerts] and every built-in
condition is delivered, deduplicated, with a recovery notice when it clears:
[alerts]
email = "[email protected]" # AUTUMN_ALERTS__EMAIL
webhook_url = "https://alerts.example.com/hooks/autumn"
webhook_secret = "…" # REQUIRED with webhook_url; alerts are always
# signed (prefer AUTUMN_ALERTS__WEBHOOK_SECRET)
Built-in conditions — each carries a stable dedup_key, a severity
(critical on trigger, recovery on resolve), the host/replica, and a "where
to look" actuator pointer:
health_grace_secs (default 60).error_rate_threshold
(default 0.05, a fraction in (0, 1]) over ≥ error_rate_min_requests.#[scheduled]/framework task returns an error.
A failed autumn db backup offsite upload also raises this condition,
delivered via the outbound-HTTP alert channels only (not email)
(0.6.0, issue #1743).Delivery is best-effort and off the request path (background tick every
eval_interval_secs, default 30), reuses your existing mailer + outbound-webhook
machinery, and the webhook is signed exactly like other Autumn webhooks
(Autumn-Signature: t=…,v1=<hmac-sha256>). enabled = false is the master off
switch (also silences custom channels). Add your own transport (PagerDuty,
Slack, …) by implementing AlertChannel and registering it with
AppBuilder::with_alert_channel. autumn doctor warns (in production) on a
missing or unusable destination — see the doctor skill. See
docs/guide/operator-alerts.md.
PagerDuty, Slack, and Discord now ship as built-in AlertChannels — no code,
just [alerts] keys (each with an AUTUMN_ALERTS__* env override):
[alerts]
pagerduty_routing_key = "…" # Events API v2 integration key; enables PagerDuty
pagerduty_url = "https://events.pagerduty.com/v2/enqueue" # optional override
pagerduty_severities = "all" # "all" (default) | "critical"
slack_webhook_url = "https://hooks.slack.com/services/…"
slack_severities = "all"
discord_webhook_url = "https://discord.com/api/webhooks/…/slack" # append /slack
discord_severities = "all"
dedup_key, so a repeating condition folds into one incident
and a recovery auto-resolves it — keep pagerduty_severities = "all" so the
resolve event reaches PagerDuty. pagerduty_url targets any
PagerDuty-Events-compatible endpoint./slack-suffixed endpoint. Both require an absolute
https webhook URL (enforced at runtime and by autumn doctor).*_severities = "critical" sends only
firing alerts (recoveries suppressed); "all" (default) sends both. An alert
below a channel's threshold is never delivered to it (AlertChannel::accepts_severity).https,
but the sends only validate URL shape and do not run through the SSRF
deny-list, so restrict alert destinations to trusted operator-configured URLs.
A native transport counts as a destination, so configuring one
satisfies autumn doctor --strict without [alerts] email/webhook_url.autumn alert test [--channel <name>] fires a synthetic alert through each
configured outbound-HTTP channel (email is excluded) and reports per-channel
success/error.(issue #1630). See docs/guide/operator-alerts.md.
Every autumn release asset carries a CycloneDX SBOM and a keyless SLSA
build-provenance attestation, and autumn release init makes the same posture
the default for a scaffolded app. Reach for this when asked "what is in this
build?", "where did this binary come from?", or for compliance/audit evidence.
autumn sbom is deterministic on purpose — no wall-clock timestamp, and a
serialNumber derived from the document's content — so --verify can be a
real gate. Do not add a random serial or a timestamp.autumn sbom --binary <path> answers "which crate versions are in this
binary?" with no source tree and no lockfile, reading the .dep-v0 section
cargo-auditable embeds. A binary built without it gets an error naming the
fix, never an empty list.cargo auditable,
fetches Tailwind via the checksum-verifying autumn setup (never a bare
curl), and bakes an SBOM at /usr/share/autumn/sbom.cdx.json behind the
io.autumn.sbom.path label.gh attestation verify <asset> --repo autumn-foundation/autumn. Always pass
--repo: without it any repository's attestation would satisfy the check.See docs/guide/supply-chain.md for the end-to-end walkthrough, including the
negative case (tamper with a byte, watch verification fail).
Every app autumn new generates audits its whole dependency tree on each push
and pull request: the scaffolded .github/workflows/ci.yml installs a pinned
cargo-deny and runs cargo deny check advisories against a deny.toml at the
project root. A known RustSec advisory that deny.toml does not waive fails
the build.
continue-on-error,
|| true, and deleting the step turn a security control into a decoration —
and an integration test in the framework fails if the generated workflow does
any of them. If asked to get CI green, fix or waive the advisory instead.cargo update -p <crate> when a patched version is
compatible, else bump the direct dependency that pulls it in. Read the
dependency path cargo-deny prints bottom-up — the crate to bump is the
highest entry in that chain the app controls.deny.toml:
{ id = "RUSTSEC-…", reason = "why this is acceptable here; review-by <date>" }.
A waiver lets exactly one id through; the gate stays on and every other
advisory still fails.pin-utils,
unmaintained, via autumn-web's cfg(loom_models) loom dependency). That
is why day-one CI is green. Apps scaffolded before autumn-web moved to
jsonwebtoken 12 also carry RUSTSEC-2023-0071 (rsa 0.9) and
RUSTSEC-2026-0387 (crypto-bigint 0.5); delete those after upgrading
autumn-web, once cargo-deny reports them unused. Do not remove a waiver
without checking whether a fixed release has shipped. An unused-waiver warning means one of the
app author's own waivers went stale.deny.toml (the policy is the app's, so autumn upgrade never
writes it). The audit step says so and stops; copy the file from a freshly
generated app rather than removing the step.--offline against it, so a failure in the audit step is always a real
advisory rather than a network blip../scripts/check-advisories.sh (and --self-test, which proves the gate can
still reject an injected known-vulnerable dependency).docs/guide/supply-chain.md "Part 3a" has the failure-reading walkthrough.
Published 0.5.0 behavior:
log.access_log = false, tune exclusions with log.access_log_exclude
(probes/static excluded out of the box).autumn_web::log::context::with_log_field("order_id", id)
(prelude re-export).actuator.prometheus exposes the Prometheus scrape endpoint independently
of sensitive actuator mode.[log] level / [log] format (or
AUTUMN_LOG__LEVEL / AUTUMN_LOG__FORMAT). level takes the full
tracing filter syntax, so "info,my_app::orders=debug" raises one target
without raising the floor; format is Auto (pretty unless the profile is
production, then JSON), Pretty or Json. The profile sets both outright
before those defaults apply: dev is debug/Pretty, prod is
info/Json, any other profile falls back to info/Auto. Both are read
once, at
startup — see "Runtime log levels" below for changing one on a running
process. Every [log] knob, the access log and the PII scrubber included,
is documented on one page: docs/guide/logging-pii.md.autumn-sketch crate (unreleased)The fixed-memory sketches below live in their own crate, not in
autumn-web. Add autumn-sketch = "0.11" to the app's [dependencies]; it is
std only, with no dependencies of its own. Each sketch has a shared form
behind a mutex (put it in an Arc and record from every handler), and
sketches of one shape merge, so per-replica sketches add up to the fleet's
answer.
heavy_hitters (unreleased)To find the hottest tenant, route or client IP without a counter per key,
use autumn_sketch::heavy_hitters::HeavyHitters (the autumn-sketch crate). It
holds capacity counters (Space-Saving): every key over total / capacity
stays in the table, and each Hitter carries count (never below the truth)
and guaranteed() (never above it). frequent(share_ppm) has no false
positives; take() hands back the window and starts a fresh one:
let hot = Arc::new(HeavyHitters::new(100));
hot.observe(tenant_id.clone()); // or observe_n(route, bytes)
for hit in hot.frequent(50_000) { /* each is surely >= 5 % of traffic */ }
distinct (unreleased)To count unique visitors, client IPs or tenants without keeping every key,
use autumn_sketch::distinct::DistinctCounter (the autumn-sketch crate). It is a
HyperLogLog of 2^precision one-byte registers, accurate to
1.04 / sqrt(2^precision); duplicates change nothing. Sketches of the same
precision merge into the union, so each replica counts its own and the
merged sketch counts the fleet's. to_bytes/from_bytes ship a sketch:
let visitors = Arc::new(DistinctCounter::new(14)); // 16 KiB, ~0.8 % error
visitors.insert(&session_id);
let today = visitors.take(); // fresh window, old sketch back
fleet_total.merge(&HyperLogLog::from_bytes(&peer_bytes).unwrap())?;
quantiles (unreleased)To report p50/p99/p99.9 latency or payload size without keeping every sample,
use autumn_sketch::quantiles::Quantiles (the autumn-sketch crate). It is a
DDSketch: every quantile is within the relative accuracy you pass (0.01 =
1 %) of the true sample at its rank, and min/max are exact. Sketches of the
same accuracy merge exactly, so each replica sketches its own traffic and
the merged sketch gives the fleet's percentiles — averaging per-pod p99s
cannot:
let latency = Arc::new(Quantiles::new(0.01));
latency.observe_duration(started.elapsed());
let p99 = latency.quantile_duration(0.99); // Option<Duration>
let window = latency.take(); // fresh window, old sketch back
fleet.merge(&window)?; // IncompatibleSketch if accuracies differ
drift (unreleased)To judge a canary or a deploy by its whole latency shape rather than one
percentile, use autumn_sketch::drift::compare(&baseline, &candidate) on two
DdSketches of the same accuracy (take them with Quantiles::snapshot or
take). It runs the two-sample Kolmogorov-Smirnov test: distance() is the
largest gap between the two cumulative distributions, and
is_significant(0.01) says whether it beats chance for those sample counts.
It catches a slower median under an unchanged p99. Bucketing never makes the
distance larger than the exact one, so it raises no false alarm of its own:
if let Some(drift) = drift::compare(&baseline, &canary.snapshot())? {
if drift.is_significant(0.01) { /* roll back */ }
}
A canary gate asks one direction only: drift.is_significant_slowdown(0.01)
is the one-sided test on slowdown(), which a faster candidate never fails
(speedup() is the other side). From two request logs, the CLI runs it:
autumn canary verdict --baseline stable.log --candidate canary.log exits 2
when the canary is slower.
reservoir (unreleased)To keep a few examples of a stream (requests to an endpoint, payloads that
failed validation, slow traces) without keeping all of it, use
autumn_sketch::reservoir::Sampler (the autumn-sketch crate). It holds k items,
and every item offered had the same k / n chance of being one of them.
offer returns whether the item was kept. Reservoirs of the same capacity
merge into a uniform sample of both streams, weighted by how many items each
side saw, so a quiet replica is not over-represented:
let slow = Arc::new(Sampler::new(20));
if slow.offer(request_id) { capture_trace(request_id); } // kept: worth the cost
let window = slow.take(); // fresh window, old Reservoir back
fleet.merge(&window)?; // CapacityMismatch if capacities differ
bloom (unreleased)To skip webhook redeliveries, replayed events or digests already sent without
keeping every key, use autumn_sketch::bloom::SeenFilter (the autumn-sketch crate).
It is a Bloom filter sized from the keys you expect and the false-positive rate
you accept (a million keys at 1 % is about 1.2 MB). There are no false
negatives; insert returns true the first time and false on a probable
repeat. false_positive_rate reads the rate at the current fill, so rotate with
take before it drifts. Filters of the same shape merge into the union:
let seen = Arc::new(SeenFilter::new(1_000_000, 0.001));
if seen.insert(&delivery_id) { handle(event).await?; } // first sighting
if seen.false_positive_rate() > 0.002 { archive(seen.take()); } // rotate
fleet.merge(&BloomFilter::from_bytes(&peer_bytes).unwrap())?; // ShapeMismatch if sized differently
minhash (unreleased)To catch reworded spam, near-duplicate posts or overlapping traffic without
keeping either set, use autumn_sketch::minhash::MinHash (the autumn-sketch crate).
It estimates the Jaccard similarity |A ∩ B| / |A ∪ B| from a fixed number of
slots (128 slots is 1 KiB, about ±0.09; standard_error is 1/sqrt(slots)).
of_text(text, width, slots) sketches word shingles, ignoring case and
punctuation. Sketches with the same slot count merge into the exact sketch of
the union, and to_bytes/from_bytes store one per row:
let incoming = MinHash::of_text(&post.body, 3, 128);
for removed in removed_sketches.iter().filter_map(|b| MinHash::from_bytes(b)) {
if incoming.jaccard(&removed)? > 0.8 { return Err(flag_as_duplicate()); } // SlotMismatch if sized differently
}
frequency (unreleased)To count failed logins per IP, hits per query or timeouts per endpoint for
every key, not only the top ones (heavy_hitters), use
autumn_sketch::frequency::FrequencyCounter (the autumn-sketch crate). It is a
Count-Min sketch: new(epsilon, delta) sizes a fixed grid so an estimate is
never below the truth and above it by at most epsilon × total with
probability 1 - delta (0.001 / 0.01 is about 106 KiB). error_bound() reads
that overcount now. take() swaps in an empty sketch for fixed windows;
sketches of the same shape merge exactly, and to_bytes/from_bytes ship
them between replicas:
let failures = FrequencyCounter::new(0.001, 0.01);
if failures.increment(&client_ip) > 20 { return Err(too_many_attempts()); }
let last_hour = failures.take(); // on a timer: start a fresh window
fleet.merge(&CountMinSketch::from_bytes(&peer_bytes).unwrap())?; // ShapeMismatch if sized differently
PUT /actuator/loggers/{name} now changes the live tracing subscriber,
not just an in-memory map — raise/lower verbosity in production without a
redeploy. The default telemetry init installs a tracing_subscriber reload
layer and hands the handle to LogLevels, so a level change rebuilds the
combined EnvFilter directive (global level + per-target overrides) and pushes
it to the running subscriber on the next event. Examples (sensitive actuator
mode required):
curl -X PUT .../actuator/loggers/root -d '{"level":"debug"}' # global
curl -X PUT .../actuator/loggers/my_app::orders -d '{"level":"trace"}' # per-target
curl -X PUT .../actuator/loggers/root -d '{"level":"info"}' # revert
The response now carries "applied": true and "status":"ok" only when the
change actually reached a reload-capable subscriber; otherwise it reports
"status":"recorded" / "applied": false rather than a false-positive ok.
Overrides stay ephemeral — a restart resets to the configured log.level.
Invalid levels still return 400 — as does a target name carrying an
EnvFilter metacharacter (=, ,, [, ], {, }, whitespace), so a
malformed directive never reaches the subscriber. GET /actuator/loggers
keeps reporting current_level + overrides, now matching real emission. The
reader-facing version of this, with the full request/response shapes, is
"Change log levels at runtime, without a restart" in
docs/guide/logging-pii.md — point a user there rather than restating it.
/actuator/info (0.6.0)GET /actuator/info now reports which commit/build is running, for
deploy/rollback verification. Apps scaffolded by autumn new get this with
zero action: the generated build.rs bakes AUTUMN_BUILD_* values and
#[autumn_web::main] reads them (plus the app's own CARGO_PKG_NAME /
CARGO_PKG_VERSION) at the app's compile time. That also fixes the old
app.version = "unknown" regression — the value is now baked in, correct even
in a --release binary with the cargo env unset at runtime. Sample payload:
{
"app": { "name": "my_app", "version": "1.4.2" },
"autumn": { "version": "0.11.0", "profile": "prod" },
"runtime": { "uptime": "3h 12m" },
"build": {
"version": "1.4.2",
"timestamp": "2026-07-09T12:34:56Z",
"git": {
"commit": "9f3c1a7e…",
"commit_short": "9f3c1a7",
"branch": "main",
"dirty": false
}
}
}
Outside a git checkout (tarball / CI cache) the git.* fields degrade to
null while build.timestamp + version stay present. The block exposes only
commit / branch / time / version / dirty — never remote URLs or an env dump.
Hand-rolled apps opt in by adding the generated build.rs provenance stanza
and using #[autumn_web::main].
Known limitation: apps built from the scaffolded Dockerfile currently report
null git provenance because the Docker build context excludes .git (tracked in
#1676).
0.6.0 — Server-Timing response header:
[observability] server_timing = true (or
AUTUMN_OBSERVABILITY__SERVER_TIMING=true). Defaults on in dev /
development profiles, off everywhere else — so prod never leaks
timings to anonymous clients without explicit opt-in.total;dur=… (whole-request wall time, same clock as access-log
duration_ms) and, when at least one instrumented query ran,
db;dur=…;desc="N queries" for N+1 visibility.text/event-stream) get total-only; header is
best-effort — never turns absent timing data into an error.db metric installs autumn's own Diesel connection instrumentation on
measured checkouts only (nothing is installed when server_timing is off, so
an app's diesel::connection::set_default_instrumentation is untouched).
While enabled, autumn's timer replaces an app-provided default rather than
composing with it — documented limitation; keep server_timing off where you
rely on your own instrumentation.docs/guide/observability/server-timing.md.Unreleased — devtools protocol ([dev] devtools = true):
[dev] devtools = true (or AUTUMN_DEV__DEVTOOLS=true) and read
the feed at /_autumn/devtools instead of hand-adding logging or
RequestInspector::record_query calls. It captures every Db statement,
the N+1 template, htmx headers and the framework error per request, keyed
by X-Request-Id. Dev profile of a debug build only; never mounted in prod.X-Autumn-Devtools: 1 and a local Host:
curl -H 'X-Autumn-Devtools: 1' localhost:3000/_autumn/devtools/requests,
then /_autumn/devtools/requests/{x-request-id} for SQL and stack frames,
or stream /_autumn/devtools/events (SSE, resumable with Last-Event-ID).devtools_sql_params = "show" is
the explicit opt-in. Query strings go through [log] filter_parameters.docs/guide/devtools.md; types in the autumn-devtools-core crate
(re-exported as autumn_web::devtools::protocol).Admission control caps concurrent in-flight requests; excess is shed
immediately with 503 + Retry-After before the handler runs. Off by
default, except in the prod profile: there the ceiling is primary pool
size × 32, at least 256 (#3057):
[server]
max_concurrent_requests = 256 # 0 = unlimited; unset = profile default
Probes (/health, /live, /ready, /startup, actuator) are never shed;
sheds increment autumn_requests_shed_total. See docs/guide/resilience.md
and docs/adr/0009-adopt-overload-protection-load-shedding.md.
The ceiling no longer has to be a guess. autumn calibrate measures what the
build sustains and writes a committed capacity.lock; autumn calibrate --check gates rebuilds against it in CI, and pointing the runtime at it
sources the ceiling from the proven envelope:
[server]
capacity_contract = "capacity.lock" # explicit max_concurrent_requests still wins
Each route in the contract also carries a resource shape (db-bound,
io-bound, compute-bound) derived statically from the extractors its handler
declares. Every contract failure — missing file, malformed document, a contract
measured on a different host class or under a different profile — falls back
to the profile default, never to a lower ceiling. Calibrate under the profile
you deploy (autumn calibrate --profile). See docs/guide/capacity-contracts.md.
The request timeout sets a deadline for the handler task. Read it with
autumn_web::deadline::Deadline::current(). The outbound Client uses it:
each attempt gets min(timeout_secs, time left), and no retry or
Retry-After wait starts that the time left cannot hold. When the deadline
stops a call, the client returns ClientError::DeadlineExceeded (504).
tokio::spawn drops the deadline; carry it with Deadline::scope. Stop other
calls with deadline::bounded(fut).
[http.client.retry_budget] # per-host token bucket, on by default
capacity = 500
transient_cost = 14 # 5xx, connect error, timeout
throttling_cost = 5 # 429
retry_ratio = 0.1 # retry share when the bucket is empty
[server.timeouts]
accept_deadline_header = false # true: x-autumn-deadline-ms can shorten the deadline
A timeout 503 has Retry-After: 1..=3. The prod drain window is 35 s
(request timeout + 5 s). autumn_web::extract::ShutdownToken is cancelled at
shutdown. See docs/guide/timeouts-and-budgets.md.
Bound slow, idle and excess connections. Every key is optional; the prod
profile sets all [server.http] keys and the [realtime] size/ping/idle keys:
[server.http]
header_read_timeout_ms = 10_000 # slowloris: full head in time, or disconnect
keep_alive_timeout_ms = 75_000 # close a connection with no request in flight
max_header_bytes = 65_536 # HTTP/1 head over the limit gets 431
http2_max_concurrent_streams = 100
max_connections = 10_000 # per listener; accept waits at the cap
[realtime] # every #[ws] route
max_connections = 5_000 # 503 + Retry-After above the cap
max_message_bytes = 1_048_576 # close code 1009
ping_interval_ms = 30_000 # pongs are hidden from the handler
idle_timeout_ms = 120_000 # close code 1001
[database]
replica_max_lag_ms = 5_000 # reads use the primary while lag is over/unknown
warn_on_pooler = true # boot warning for PgBouncer / RDS Proxy URLs
autumn_web::ws::WebSocket / WebSocketUpgrade are Autumn wrappers (same
recv / send / Stream / Sink); into_parts() gives the axum type
(without limits) and a ConnectionHold to keep for the socket's life. Lag
alone never fails readiness. See
docs/guide/connection-limits.md, docs/guide/websockets.md (Limits),
docs/guide/cloud-native.md (Lag-aware reads) and
docs/guide/connection-poolers.md (what breaks behind a transaction-mode
pooler).
The HTTP client (per host), durable job enqueue (job_queue) and the SMTP
mailer (smtp_mailer) run behind a CircuitBreaker. It opens on the failure
ratio or the slow-call ratio (issue #3060):
[resilience.circuit_breaker.defaults]
slow_call_duration_threshold_ms = 60000 # 0 turns slow-call detection off
slow_call_rate_threshold = 1.0 # open when all calls are slow
cancelled_call_outcome = "slow" # or "failure"
[resilience.circuit_breaker.hosts."api.stripe.com"]
slow_call_duration_threshold_ms = 5000
slow_call_rate_threshold = 0.5
server.timeouts.request_timeout_ms, or the timeout
cancels a slow call first.autumn_circuit_breaker_slow_calls_total,
autumn_circuit_breaker_slow_call_ratio (label name).CircuitBreakerPolicy struct literal needs ..CircuitBreakerPolicy::default().See docs/guide/resilience.md.
Add latency or errors in staging with [fault_injection]. Do not use it in
production.
[fault_injection]
enabled = true # or AUTUMN_FAULT_INJECTION__ENABLED=true
[[fault_injection.faults]]
routes = ["/api/*"] # empty = all paths; probes and actuator exempt
target = "route" # route | database | redis | http
kind = "error" # error | latency (needs latency_ms)
rate = 0.05
status = 503
[fault_injection.stop] # disarm on a fast error-budget burn
objective = 99.0
max_burn_rate = 14.4
prod (and with no profile) unless
allow_in_production = true. Put that key only under
[profile.prod.fault_injection].state.extension::<autumn_web::fault_injection::FaultInjection>() and
.arm(actor). Each arm and disarm writes an audit event.AutumnConfig struct literal needs ..AutumnConfig::default().FaultPlan, not this section.See docs/guide/fault-injection.md.
Framework-native horizontal sharding: declare [[database.shards]] (each a
full primary/replica topology), route by key → logical slot → shard. Prelude
extractors: ShardedDb (auto-routed handle — resolves the routing key from
the request, checks out the owning shard's primary, derefs to the connection
like Db) and Shards (explicit routing: db_for/read_for/db_on, plus
bounded each_shard fan-out); install custom routing with
AppBuilder::with_shard_router; build repositories per shard with
from_shard(&ShardedDb). autumn migrate gains --shard <name> /
--control-only; a boot-time shard-map guard fails fast on config drift.
There are no cross-shard queries or transactions by design. See
docs/guide/sharding.md and examples/bookmarks-sharded.
On the sqlite backend, use [database.fleet] (not [[database.shards]])
to give each tenant, or each routing slot, its own SQLite file. Reach for it
when tenants' writes queue behind SQLite's single writer, or when a tenant
must be exported, restored or deleted as a file. The same ShardedDb,
Shards, CrossShard and #[repository(sharded)] code routes to the
tenant's file, opened and migrated on first use.
[database]
url = "sqlite:///var/lib/app/control.db" # sessions, jobs, flags stay here
[database.fleet]
mode = "tenant" # or "slot" (bounded: 16384 files)
root = "/var/lib/app/fleet" # path defaults to "{bucket}/{tenant}.db"
[a-z0-9_-] (lowercase, max 128): anything else is
400, since the id names a file. A tenant fleet does not create unknown
tenants: call shards.fleet().unwrap().provision(&fleet.key_for(id)?) on
signup (404 until then, 409 if it exists).DatabaseFleet (autumn_web::db::fleet): open_for, provision,
delete (410 meanwhile), backup (VACUUM INTO), import (copy a
file into the fleet: check, migrate, publish; 409 when the key has a
file, 422 for a bad file), restore_from_file(&key, &src, LocalRestore::new()) (0.11.0, #3537; replace a live database with a local backup; no
replication needed; openers wait for the swap; another key's backup or a
deleted key is refused unless allow_rekey / clear_tombstone),
restore, list, each, migrate_all, stats. Health: db:fleet.
Use import or restore_from_file, not a
FleetLifecycle::restore_missing hook, for a local backup. CLI:
autumn fleet restore <key> --from <file> --force.max_open is a soft limit by default: a database in use or used within
min_residency (default "2s") is not closed, and an open never waits.
A burst can open far more files than max_open. Size ulimit -n for the
peak (about 2 × pool_size + 1 fds per open database). db:fleet reports
peak_open, over_cap_opens_total and refused_total.[database.fleet] max_open_policy = "wait" or "refuse" (0.11.0, #3538) makes max_open
hard: open and closing databases never pass it. wait parks an open for
at most database.connect_timeout_secs, then answers 503. refuse
answers 503 with Retry-After when no idle database can close. Check the
tenant id before open: the cap counts any key.max_resident_bytes (0.11.0, #3642; default 0, off) is a soft memory budget with the
same rules as max_open. The SQLite engine counts about 2 MB per open
connection. The fleet keeps one database open. db:fleet reports
resident_bytes..migrations_for(MigrationScope::Control, SET) / .migrations_for(MigrationScope::Shards, SET)
(autumn_web::migrate::MigrationScope), not one set for both.Sqlite<Trait> too (alias
of Pg<Trait>). In a module with #[model]/#[repository], import
autumn_web::db::prelude::*, never diesel::prelude::* (E0034).tenant_scoped on its
repositories. CrossShard / each_shard open every database on disk —
admin paths only.[replication] on, each open database ships its WAL under
fleet/tenant/<id> / fleet/slot/<n> (health replication:fleet;
[database.fleet] replica_key = "{base}/tenants/{tenant}" sets another
key);
restore_missing = true serves a missing database from its replica on a
fresh volume. It holds what the old owner shipped: after a crash, up to
rpo_secs of committed writes that already returned success are missing.
A replicated fleet root is served by one process (one replicator per
database).dst, delete
from src): do the second half only after the first is in the replica.
fleet.wait_replicated(&dst, committed_at, timeout) (0.11.0, #3658) with committed_at
read from the app clock after the commit; fleet.replicated_through(&key)
gives the instant itself. Errors: NotReplicating, Fenced, TimedOut
(not a loss: keep the source row, retry). Do not use worst_lag_seconds
or last_success_at for this. Guide: "Know when a write is in the
replica" in docs/guide/sqlite-fleet.md.dst) and
keep it, and record the arrival's time (full precision: nanoseconds, never
rounded) and db.epoch() from the destination. Delete the source copy (keep a tombstone) only when
fleet.replica_bound(&dst).map(|b| b.coverage(arrived_at, arrived_epoch))
is Some(Covered), asked on the process that replicates dst. Pending: ask
later. Stale (another epoch, or not newer than the file, bound.since()):
deliver again. A time-only or epoch-only check is not safe: a restore, a
new volume or a restart can keep the epoch. Mark moved again each copy
that came back. Versioned upserts, deletes bounded by version. Guide:
"Move rows between fleet databases" in docs/guide/sqlite-fleet.md.delete also purges the replica.
It writes a tombstone row (_autumn_fleet_tombstones) on the control
database first; no row, no delete (503). A failed purge keeps the row,
and the maintenance task retries it (purge_deleted_replicas).
restore_missing does not restore a tombstoned key; restore does, and
drops the tombstone. replica_retention_after_delete = "30d" keeps the
replica for undo; during it, a create on demand answers 410 and
provision purges the old replica and ends it. restore_check_sample (default 1) restores random databases every
[replication] verify_interval_secs; a failure turns replication:fleet
Down. Do not write an on_delete hook to delete replicas. Guide:
"Deleting a database's replica" in docs/guide/sqlite-fleet.md.[database.fleet.ownership] (owner unique per volume,
slots = ["0-8191"], lease_secs = 30) with restore_missing. A host
serves only the slot ranges it claims; an unowned slot is 421
(FleetError::NotOwner), and restore_missing runs only for an owned key.
Each claim gets an epoch: a restore selects the newest epoch, and an old
owner's replicator stops. A host that gets a range back restores files
older than the replica before it serves them, with or without
restore_missing. Replication is asynchronous: a takeover loses the
unshipped writes (rpo_secs in steady state), and a fail-back does not
recover them. A crash costs up to lease_secs + lease_secs / 3 of outage.
Guide: "What a failover costs". An open refuses a file stamped with a
newer epoch than this host's (FleetError::NewerEpoch, 421).
Health: fleet:ownership. The built-in table is
on the control database, so it fences the processes of one host only;
for hosts on different machines, use
.fleet_ownership_store(PgSlotOwnership::new(pg_pool, clock)) (needs the
postgres feature next to sqlite; one store per fleet) or another
SlotOwnershipStore (autumn_web::db::fleet_ownership). Guide:
"Failover: slot ownership" in docs/guide/sqlite-fleet.md.autumn_web::fleet::resolve::<E>(parts, state): routing key, owner check
(421), open, FleetLease<E>. Jobs use resolve_key::<E>(state, id).
Put the DatabaseFleet<E> in the state with insert_extension. A sidecar
hook ships through db.sidecar_replica("duckdb"), a ScopedDestination
that refuses keys outside <key prefix>/duckdb/ and writes after a close or
a fence. Guide: "Writing a fleet extractor" in docs/guide/sqlite-fleet.md.autumn_web::fleet::install_replication(&state, &fleet, &config) (needs
sqlite), not a hand-built FleetReplication. Call it in the plugin's
on_startup, after DatabaseFleet::with_engine, before the first open.
It gives the same parts as [database.fleet]: replica, tombstones,
replication:fleet, loop. [replication] off: NoReplication. A second
fleet with the same name on one replica root: RootInUse. Without it, a
standby that becomes the owner opens empty databases; a fleet with ownership
and no replica logs one warning. Guide: "Shipping a plugin engine".[database.fleet] plus a
DuckDB fleet: name every fleet but one,
DatabaseFleet::with_engine(&config, engine)?.named(FleetName::parse("duckdb")?)?
(autumn_web::fleet_layout::FleetName; DatabaseFleet::builder(..).name(..)
for SQLite). A named fleet ships under <root>/fleets/<name>/fleet/, keeps
tombstones <name>/<key> and reports replication:fleet:<name>. Two fleets
on one root: FleetRootShared. Serve every fleet under one ownership with
autumn_web::fleet::join_ownership(&state, &fleet, ownership_config) (same
owner and slots, or refused); at shutdown stop each loop, then each fleet's
release_ownership votes and the last ready vote releases. Find fleets with
insert_fleet, fleet_named::<E>, resolve_named, resolve_key_named.
Guide: "More than one fleet".fleet.lake()?.materialize().await?.query(sql)
(autumn_web::db::fleet_lake) restores each live tenant from its replica
into a scratch SQLite file. Each table gets _autumn_tenant. One
SELECT/WITH/VALUES on a read-only connection; grouped SUM/AVG
work across tenants. It never opens the fleet root (FleetLake::new(dest, base) on a host with no volume). Deleted tenants are skipped. No
tombstone source: markers_only(). Each tenant is consistent on its own;
no atomic snapshot. CLI: autumn fleet lake q.sql --out q.csv. Never
pass request input as the SQL. Guide: "Query the lake".LakeSink and call
fleet.lake()?.load(sink). Core runs the inclusion rule, restores, and
checks the identity row of a WAL member. For a Generations fleet
(member.format == LakeFormat::Generations), implement
check_identity(member): the default refuses the member. The sink gets
add(LakeMember { key, generation, format, file }) and gives its lake
from finish(). To keep a lake between loads, return true from
has(key, generation): core calls keep and restores nothing. At
finish, drop each member that got neither add nor keep.
LakeGeneration holds the WAL position, so compare all of it. For a
generations member the position is None, and the id names the
generation. TAKES_SLOTS = true gets slot databases. Keep the catalog in files
under the sink's own prefix, never under <base>/fleet/. Guide: "Lake
sinks".root (validation refuses it inside).[database.fleet] mmap_size / cache_size_kib tune fleet files on their
own; [database] mmap_size does not reach the fleet. Keep them 0 for
small tenant files. Guide: "Memory-mapped reads" in
docs/guide/sqlite-fleet.md.DatabaseFleet<E: FleetEngine>
(autumn_web::db::fleet_engine, experimental surface). With sqlite,
DatabaseFleet means DatabaseFleet<SqliteEngine>, so SQLite code does
not change. An engine plugin implements FleetEngine (async open that
stamps the key and the epoch, close, in_use, snapshot, remove,
resident_bytes, ship_mode), builds with
DatabaseFleet::with_engine(&config, engine), reads db.handle(), and
runs plugin_conformance::fleet::run_fleet_conformance with a
FleetFixture in its CI. Engines go in their plugin, never in core.ShipMode::Generations { every } from
ship_mode and call fleet.install_replication(replication) (needs
sqlite). Core snapshots every every (the first at a random time in
the first every) and at close, puts only files with
a new SHA-256, and restores the newest generation on a new volume. The
engine never writes the replica: core checks the fence before each put
(FleetError::Fenced, 421). Make a snapshot of unchanged data the same
bytes, and return the stamp from epoch_stamp. Core ships each changed
file whole. Bytes written to the replica a day ≈
changed files × file size × 86,400 / every, with every in seconds.
Calculate every from that write volume, not from the default.
ShipMode::Rebuild ships
nothing: restore_latest calls FleetEngine::rebuild. Operators:
fleet.ship_now(&key), fleet.restore_latest(&key). FleetStats has
ship_mode and rpo_secs. A close-time generation that did not ship
stays as unshipped work: the replication loop (spawn_loop) and the
shutdown flush ship it again, and release_ownership lets the ranges
lapse until then. Watch replication:fleet unshipped and
FleetReplication::unshipped_generations(). Do not write your own retry.
Guide: "Shipping a plugin engine" in docs/guide/sqlite-fleet.md.ShipMode::Log { every, base_every } and
implement log_base (a copy and the LogPosition it holds),
read_log(from, out) (the committed changes after from, as
LogRead::Written { through }, Empty or Gap), log_shipped (the
engine may drop its log through it) and replay_log (apply the records
to a base copy). Core ships a base at each open and every base_every,
then one record of only the new changes every every (the RPO) and at
close; a Gap ships a new base. Restores replay the records after the
newest base. Do not ship whole files every second with Generations
for an engine that has a log. Refuse a second process's open of a path.
A lake sink replays LakeMember::log on the base. Kit check:
fleet-log-replay. Guide: "Log mode" in docs/guide/sqlite-fleet.md.#[derivation] backfills work on fleet
databases, also closed ones (issue #3234). Write outbox rows in a
transaction on the tenant connection: the write records the database in
_autumn_fleet_pending on the control database. A worker-role process
(the fleet sweeper) opens each listed database, never past max_open,
does the work, then closes it. Outbox handlers of a tenant fleet run in
the tenant's scope. Health: fleet:sweeper (backlog,
oldest_pending_secs). Do not enqueue on a fleet database inside a
control-database write transaction: the write fails.TestApp::new().with_db(control).with_fleet(fleet); call
FleetSweeper::install(client.state()) (autumn_web::db::fleet_sweeper)
before the first request, then sweep_once() to run a pass.sqlite CLI build:
autumn fleet list --open, migrate [--key K], backup <key> <dest>,
import <key> <src>, delete <key> --force, restore <key> [--timestamp T] --force. Keys are
tenant:<id> / slot:<nnnnn>. A file another process has open is refused
("open in another process"). migrate reads migrations/ only: plugin
sets need AUTUMN_MIGRATE=1. Run it from the app directory.See docs/guide/sqlite-fleet.md ("Operating the fleet").
Limit the effect of one noisy tenant. All settings are off by default. See
docs/guide/cell-isolation.md and docs/adr/0018-shard-local-framework-state.md.
[tenancy] max_concurrent_requests: the in-flight requests of one tenant.
Over the cap: 503 + Retry-After: 1. Runs before the admission limit.[tenancy] max_db_connections: the Db/shard checkouts of one tenant.
Over the cap: 503. Set it to at least the connections one handler holds.[jobs.tenants] (local backend only): max_concurrent (per-tenant job
slots), lanes and lanes_per_tenant (shuffle-sharded worker lanes; at
most jobs.workers lanes). Each queue serves tenants round-robin.
autumn_web::bulkhead::shuffle_shard(key, lanes, size) gives the lanes.[jobs.postgres] shard_local = true: an autumn_jobs table, workers and
slots on each shard. enqueue_in_tx on a shard connection commits or rolls
back with the shard's data. Needs jobs.backend = "postgres" and shards.autumn_web::cell_router::CellRouter (with CellSpec::new) maps a tenant
to a cell with the shard slot hash: for_tenant, for_key, for_slot,
url_for.autumn_tenant_bulkhead_rejections_total{kind="request"|"db"}.Row-level tenancy scopes a tenant's rows; per-tenant memory cells bound a
tenant's in-process memory. Each resolved tenant gets a TenantCell — a
byte-accounting boundary with a soft quota and an owned scratch buffer — minted
lazily by the process-wide TenantCellRegistry on the first call to
current_tenant_cell() (returns Option<Arc<TenantCell>>; None when tenancy
is disabled or no tenant is bound, so a route outside a tenant context degrades
gracefully). Reach for it in a handler, charge the memory you want bounded, and
let the RAII guard release it:
use autumn_web::prelude::*;
use autumn_web::tenant_cell::current_tenant_cell;
#[post("/reports")]
async fn build_report() -> AutumnResult<String> {
// Over-quota tenants get a 503 here via `?`; the charge releases on drop.
let _charge = match current_tenant_cell() {
Some(cell) => Some(cell.try_charge(512 * 1024)?),
None => None, // tenancy disabled / no tenant bound
};
Ok(expensive_render().await?)
}
try_charge(n) reserves before you allocate and hands back a Charge
guard; the per-tenant scratch store
(scratch_insert/scratch_get/scratch_remove) is charged by allocation
capacity (not length) plus a fixed per-entry overhead
(TenantCell::scratch_entry_overhead()).QuotaExceeded
converts to AutumnError as HTTP 503; every other tenant's counter is
independent, so one whale degrades only its own traffic.[tenancy]: quota_bytes (soft quota; 0, the default,
disables it), max_cells (LRU cap on resident cells) and idle_ttl_secs
(idle eviction) — both 0 by default, both enforced lazily on cell insert.
The quota is stored atomically and refreshed on every access (retune-ready;
no config-reload path exists yet).[tenancy] source defaults to "session" (0.11.0). source = "header" needs
header_trust = "trusted_proxy" (a gateway sets the header) or
"any_client" (unsafe), or the app does not start. A session that holds
session_key binds the tenant: a header, host or token for another tenant
gets 403. See docs/guide/tenant-cells.md "Tenant sources".[tenancy] section is settable from the environment via
AUTUMN_TENANCY__* (e.g. AUTUMN_TENANCY__QUOTA_BYTES,
AUTUMN_TENANCY__MAX_CELLS, AUTUMN_TENANCY__IDLE_TTL_SECS).TenantCellRegistry::evict(tenant_id) or automatic
(max_cells/idle_ttl_secs) — reclaims tracked bytes on Drop; an in-flight
request keeps its own cached Arc<TenantCell> to completion, so evicting
mid-request never resets a running request's state. While any handle is still
live, the next get_or_create for that tenant resurrects the same
domain (quota counter and scratch store) rather than minting a fresh one —
eviction ends cache residency, not the accounting lifetime, so do not rely on
it to give the next request a clean slate or purge scratch immediately. This is a tracked-bytes
accounting boundary via tracked_bytes() / total_tracked_bytes(), not
RSS — allocations made outside the cell API are invisible by design.For the allocations Autumn can own, not just charge for, use the typed
arena: current_tenant_arena() returns Option<TenantArena>, and
arena.try_bytes(len) / arena.try_string(&str) hand back TenantBytes /
TenantString values that carry their own RAII quota charge and release it on
drop — including through eviction, until the value itself is gone. A
TenantAllocationError (quota or allocator failure) converts to HTTP 503
via ?, and the failed reservation mutates nothing. This is a cooperative,
tracked boundary, not hard isolation: ordinary Vec/String/Box,
framework, third-party and allocator-internal allocations stay outside it
(ADR 0012).
TenantCell/TenantCellRegistry/current_tenant_cell live in
autumn_web::tenant_cell (not in the prelude). Orthogonal to sharding: sharding
picks the database, cells bound process memory. See
docs/guide/tenant-cells.md (issue #1766).
JSON errors are standardized as RFC 7807-style Problem Details.
Handlers should return AutumnResult<T> and use the typed constructors:
Err(AutumnError::not_found_msg("post not found"))?;
Err(AutumnError::bad_request_msg("invalid input"))?;
Err(AutumnError::unprocessable_msg("validation failed"))?;
Err(AutumnError::unauthorized_msg("login required"))?;
Err(AutumnError::forbidden_msg("not allowed"))?;
Err(AutumnError::conflict_msg("duplicate delivery"))?;
Err(AutumnError::service_unavailable_msg("queue unavailable"))?;
Clients that prefer JSON receive application/problem+json with type,
title, status, detail, instance, code, request_id, and errors.
Autumn provides framework primitives a canary controller drives — it does not own the load-balancer traffic split (that stays a platform concern).
Label the canary replica (env var, no code change):
AUTUMN_DEPLOY_VERSION=canary # explicit label (any string)
# …or the boolean shorthand:
AUTUMN_CANARY=true # resolves to version="canary"
Stable replicas leave both unset → version="stable".
Prometheus metrics are tagged with the version label so a controller can
compare cohorts:
autumn_http_requests_total{version="canary"} 412
autumn_http_responses_total{version="canary",status="5xx"} 3
autumn_http_request_duration_seconds_count{version="canary",method="GET",route="/items/{id}",status_class="2xx"} 409
autumn_http_request_duration_seconds is a histogram (method, route,
status_class labels). Use histogram_quantile over its _bucket series for
p99. The old quantile lines are in the deprecated
autumn_http_request_duration_quantiles_seconds summary.
CanaryRoute extractor (in prelude::*) — lets a handler see whether the
LB routed this specific request to the canary (X-Canary: true):
async fn handler(canary: CanaryRoute) -> String {
if canary.routed_to_canary { "canary".into() } else { "stable".into() }
}
Rollback — when a controller decides the canary is unhealthy:
autumn canary rollback --reason "p99 latency exceeded" --by ci-controller
# The replica flips /ready → 503 and drains cleanly (same as SIGTERM).
autumn canary status # check flag state
autumn canary promote # clear the rollback flag after traffic is moved
Verdict — decide from the whole latency distribution of two logs (bare ms
per line, or access-log lines with duration_ms); exits 2 when the canary is
slower, 0 when not; --rollback writes the flag on a slowdown:
autumn canary verdict --baseline stable.log --candidate canary.log --rollback
The rollback flag file lives at tmp/autumn-canary-rollback.json. A controller
that cannot exec into the replica can write it directly. The flag is sticky
across restarts — clear it with autumn canary promote once traffic has moved.
Declare SLOs in autumn.toml. The app does not read them at run time.
[[slo]]
name = "availability" # lowercase letters, digits, '-'
objective = 99.9 # percent, at most 4 decimals
sli = "availability" # or "latency" (needs threshold_ms, a bucket bound)
# route = "/api/orders/{id}"
autumn slo generate --selector 'job="shop"' # writes deploy/slo/ (6 files)
autumn slo generate --check # CI: fail on drift
The files are Prometheus burn-rate rules and alerts (14.4x over 1h/5m, 6x over
6h/30m, 1x over 3d/6h), a PrometheusRule, a Grafana dashboard, an Argo
Rollouts AnalysisTemplate, Flagger MetricTemplates and Helm values. Route
and latency SLOs read the request-duration histogram (issue #3064).
To act on a burning budget inside the app, use
autumn_web::slo_meter::BurnMeter (slo feature, 0.11.0). Build it from a validated
Slo, call record(good) per event, and check firing(&BURN_WINDOWS[0])
(both windows over the factor, as in the generated alert) or
burn_tenths_at(now, window). Memory is retention / bucket slots:
let meter = Arc::new(BurnMeter::new(&slo, Duration::from_mins(1), Duration::from_hours(1)));
meter.record(status < 500);
if meter.firing(&slo::BURN_WINDOWS[0]) { /* shed optional work */ }
Bake each host after its cutover; roll it back on a 5xx or latency breach or a restart (off by default):
[deploy.bake]
duration_secs = 300 # or: autumn deploy up --bake-secs 300
Kubernetes: autumn release init --target kubernetes writes a Helm chart
(deploy/helm/, set trustedHosts) and a Kustomize base with probes, a
preStop hook, a safe grace period, a PDB, and opt-in Argo Rollouts or Flagger
canaries. Each role gets its own workload (roles: in values.yaml, one
Kustomize component per role); only HTTP roles get a Service and an Ingress.
--roles picks the roles. --target fly writes one [processes] entry per
role (0.11.0, #3547). A fleet sets a role per host group with a [[deploy.groups]] table
(role = "worker" and hosts = ["10.0.0.3"]). autumn doctor warns when a
manifest names an undeclared role. See docs/guide/slo.md, docs/guide/kubernetes.md and
docs/guide/fleet-deploys.md.
Canary decides from cohort metrics over traffic the new build really serves.
Shadow decides from a per-request diff and serves nobody: Autumn mirrors
sampled GET/HEAD traffic to a candidate build you run alongside production
and compares the two responses. Use it to catch the subtly-wrong-but-200
regression — a dropped JSON field, a reordered list, an off-by-one total — that
cohort metrics cannot see. It composes with canary; it does not replace it.
Off by default. Requires the http-client feature (on by default).
# autumn.toml
[shadow]
enabled = true
target = "http://127.0.0.1:9091" # the candidate build (you run it)
sample_rate = 0.05 # of ELIGIBLE traffic. Default 1.0 — start low.
routes = ["/api/*"] # empty (default) = every eligible route
timeout_ms = 2000 # one deadline per mirror: request, primary wait, comparison
max_in_flight = 8 # excess mirrors are dropped, never queued
max_body_bytes = 262144 # larger responses are not compared, either side
max_records = 50 # divergences kept for the actuator
max_sample_bytes = 2048 # per recorded JSON sample, before truncation
Every key has an env override (AUTUMN_SHADOW__ENABLED,
AUTUMN_SHADOW__TARGET, AUTUMN_SHADOW__SAMPLE_RATE, …).
What it guarantees. The client never waits on the mirror (detached task; the
primary body is teed, not buffered) and never receives a candidate byte. The
candidate is dialed at target but sees the Host the live build accepted, and
pages served from an SSG/ISG static cache are mirrored too. Only
GET/HEAD are mirrored, and that is a constant, not a config key — replaying
a POST needs effect virtualization, which does not exist yet. Requests the
live build refuses (429/503) are not mirrored. Actuator and probe paths are
never mirrored. Every mirrored request carries X-Autumn-Shadow: 1, so
mirroring cannot recurse.
What it compares. Status class (200 vs 201 is not a divergence; 200 vs
500 is) and a normalized body: JSON object key order is normalized away,
array order is not. Headers, latency, and fuzzy JSON tolerance are out of
scope.
Reading the results — {actuator-prefix}/shadow, sensitive-gated like
/actuator/tasks:
curl -s localhost:3000/actuator/shadow | jq '.stats, .divergences[0]'
Plus two built-in metric families on /actuator/prometheus:
autumn_shadow_comparisons_total{version,route,outcome} # match|diverged|error|
# timeout|skipped|dropped|
# refused|incomplete|abandoned
autumn_shadow_divergences_total{version,route,kind} # the series to alert on
Tell the user before they enable it: the candidate receives live cookies and
Authorization headers (a candidate that cannot authenticate makes every diff
noise), its own side effects are real so it must be contained by environment
(scratch database / writes disabled), and recorded samples are redacted by a
key-name allowlist ([log] filter_parameters) — not a PII classifier — so
any other keyed field of a response body is stored verbatim on that actuator
endpoint. (Bodies with unkeyed scalars record only a digest.)
One configuration step is easy to miss: the candidate honours the forwarded
client identity only if it trusts the mirroring host as a proxy. Add that host
to the candidate's [security.trusted_proxies] ranges, or accept that routes
reading ClientAddr/ClientScheme — and candidate-side per-IP rate limits —
will see the mirror rather than the real client.
See docs/guide/staged-deploys.md.
plugin-sandbox)Two plugin lanes now. The native Plugin trait is unchanged and full-trust: its
build(self, app) gets the whole AppBuilder. A sandboxed plugin is the
trade for code nobody audited — it ships as a .autumn-plugin artifact (a
wasm32-wasip1 module plus a manifest) and the runtime enforces the manifest.
Non-default feature. Experimental: everything in autumn_web::plugin_sandbox
is outside SemVer (see STABILITY.md).
# plugin.toml — the whole review surface
name = "autumn-plugin-hello"
version = "0.1.0"
wire_version = 1
prefix = "/hello"
# `http-request` plus, since #1632: kv, http-outbound, db, jobs, render.
capabilities = ["http-request", "kv", "http-outbound", "db", "jobs", "render"]
sha256 = "0000…" # stamped by `autumn plugin package`
[grants] # what each capability is scoped to; BOTH ways enforced
hosts = ["api.example.com"] # http-outbound may call exactly these
tables = ["orders"] # db owns exactly these, tenant-scoped
job_types = ["reindex"] # jobs may enqueue exactly these
slots = ["order-summary"] # render may fill exactly these
[quotas] # per request, operator-tunable; conservative defaults
kv_reads = 64
outbound_calls = 4
[[routes]]
method = "GET"
path = "/hello/{name}"
[limits]
fuel = 200_000_000 # CPU: instructions AND host-side bytes copied (64B/unit)
memory_bytes = 33_554_432 # per-request instance; footprint × concurrency ≤ 1 GiB
max_request_body_bytes = 1_048_576
max_response_bytes = 4_194_304
max_concurrency = 8 # requests shed with 503, never queued
request_body_timeout_ms = 5_000 # a dribbled body cannot pin a permit (408)
autumn plugin package --manifest plugin.toml --module hello.wasm --out hello.autumn-plugin
autumn plugin inspect hello.autumn-plugin # the consent screen; exits 1 if unfit
autumn plugin inspect hello.autumn-plugin --format json
# Review an upgrade AS an upgrade: prints what the new manifest asks for that
# the approved one did not, and exits non-zero when authority grew (#1632).
autumn plugin inspect new.autumn-plugin --against installed.autumn-plugin
use std::sync::Arc;
use autumn_web::plugin_sandbox::{
CapabilityServices, KvStore, MemoryKvStore, RenderSlots, SandboxedPlugin,
};
let hello = SandboxedPlugin::from_file(std::path::Path::new("plugins/hello.autumn-plugin"))?
// Capabilities are honoured against backends YOU wire. Anything unwired is
// answered `unavailable` and recorded — a refusal, never a silent success.
// The `as Arc<dyn KvStore>` is load-bearing: unsizing does not pass through
// `Option`, so `Some(MemoryKvStore::new())` will not coerce on its own.
.with_services(CapabilityServices {
kv: Some(MemoryKvStore::new() as Arc<dyn KvStore>),
..CapabilityServices::none()
});
// Render slots need both halves: the manifest names the slots the plugin will
// fill, the app declares the slots that exist. `with` fails at boot on a
// mismatch; `render` returns a String and never breaks the page.
let slots = RenderSlots::declaring(["order-summary"]).with(Arc::new(hello.clone()))?;
let fragment: String = slots.render("order-summary", &[]).await;
// "What did this plugin do in the last hour" — one surface, shapes not values.
// `Display`: the summary already knows its plugin and its window.
let summary = hello.activity().summary("autumn-plugin-hello", std::time::Duration::from_secs(3600));
println!("{summary}");
autumn_web::app().plugin(hello).run().await;
Capabilities are data, not code (#1632). A plugin granted every capability
imports exactly what a plugin granted none imports — fd_read and fd_write.
The guest asks over the NDJSON channel it already answers requests on:
{"op":"call","call":"kv-get","id":1,"key":"cart"} in, {"op":"call_result", "status":"ok"|"denied",…} back, then its response frame. A refusal is a frame
the guest can read (capability-not-granted, not-in-grant, quota-exceeded,
malformed, unavailable, backend-error), never a trap — so a plugin over a
ceiling degrades instead of 502ing.
Scoping is derivation, not checking: the guest names a logical key, table,
host or job type and the host derives plugin-kv:<plugin>:<tenant>:<key> /
plugin_<hex-escaped plugin>__<table> from the manifest and the active tenant
(the escape is injective, so a plugin named shop_orders owning v2 cannot
land on the table shop owning orders_v2 already has). There is no
field in the protocol where another tenant, another plugin, a host-app table or
SQL would go, so cross-tenant access is unspellable rather than refused. Render
hooks return a fragment tree the host renders (no HTML parser, so no parser
differential; nothing needs unsafe-inline), and a hook that traps or overruns
render_bytes omits the fragment rather than breaking the page.
What the runtime enforces. The guest's entire authority is the WASI shim's
import list: no filesystem, no network, no environment, no database, each
attempt answered ENOTCAPABLE/EBADF and logged as a denial. An import the
shim does not define is refused at load. The manifest's [[routes]] are the
router, so an undeclared path under the prefix is a 404 the guest never sees.
Fuel bounds CPU (including host-side copying done on the guest's behalf), a
store limiter bounds memory, both per request against a fresh instance; the
interpreter runs on a blocking worker with the concurrency permit held for its
actual lifetime. A trap, proc_exit, blown budget, malformed frame or missing
answer is a 502/503/504 on the plugin's own prefix — nothing reaches the
rest of the app.
Boundary gotchas worth knowing before authoring one.
accept*, content-type,
content-length, cache-control, if-*, range, user-agent). Everything
else is dropped — a denylist could never name every proxy's identity header.content-type, cache-control,
etag, location, vary, …) with no x- hatch: X-Accel-Redirect /
X-Sendfile would borrow the reverse proxy's filesystem. set-cookie,
strict-transport-security, framing headers and the host's own
x-autumn-sandboxed / x-content-type-options are stripped and logged.GET also serves HEAD (HTTP requires it, axum dispatches it);
the guest sees method: "HEAD" and route_infos() reports the extra row —
unless the manifest declares HEAD itself, in which case that route mounts
alone (two overlapping method routes on one path is an axum panic at boot)._start is not () -> (), which exports no memory (or one already
over the ceiling), or which carries >4096 / >16 MiB of data and element
segments (every request re-instantiates it).text/plain, text/csv,
application/json, application/octet-stream, and raster images. HTML,
SVG, JavaScript and CSS are refused — a document or script from your own
origin carries your origin's authority.SystemTime::now() is a fixed instant; random_get is deterministic, seeded
from the request. Neither is entropy.call frame, which
suspends rather than ends the exchange (the answer arrives on stdin). A frame
must end with \n (println!, not print!) or the host reports a partial
frame; a guest that writes calls without reading the answers is stopped.[grants] list and its capability must agree both ways: a hosts list
without http-outbound is refused, and so is db with no tables.tenant_id (it would choose its own tenant); a
row_id echoed back from db-get is stripped, so read-modify-write works.Mount at runtime (issue #2433). No restart is needed:
let mounts = PluginMounts::new();
let app = autumn_web::app().plugin_mounts(mounts.clone());
mounts.mount(&SandboxedPlugin::from_file(path)?)?; // later, app running
mounts.unmount("/hello");
/actuator, /static) or an overlapping prefix is refused.list() and routes() show what is mounted. autumn routes does not.Guide: docs/guide/sandboxed-plugins.md. Trust model: docs/plugins.md.
cargo install autumn-cli --version 0.11.0
autumn new my-app
autumn setup
autumn dev
autumn build
autumn migrate check
autumn migrate --with-maintenance
autumn task --list
autumn task <name> -- --arg value
autumn generate model Post title:String body:Text
autumn generate migration add_posts
autumn generate scaffold Post title:String body:Text --api
autumn generate auth User --oauth github,google --totp --passkeys
autumn generate admin Post title:String body:Text published:bool
autumn generate mailer User
autumn generate webhook stripe Payments
autumn generate system-test todo_flow
autumn generate pwa
autumn routes --format json --user-only
autumn doctor --strict --json
autumn config list
autumn flags list
autumn experiments list
autumn maintenance on --message "Migrating database"
autumn canary rollback --reason "p99 latency exceeded"
autumn canary status
autumn canary promote
autumn webhook sim generic http://localhost:3000/webhooks/test --secret mysecret --payload '{"ok":true}'
autumn dev-loop-bench --dry-run
autumn calibrate # measure the capacity envelope -> capacity.lock
autumn calibrate --check # CI gate: fail when a rebuild leaves the envelope
autumn plugin-check --plugin-name autumn-admin-plugin --prefix /admin
autumn plugin list
autumn plugin add autumn-admin-plugin
(0.6.0) CLI additions — absent from a 0.5.x autumn-cli, but present in
every published release since 0.6.0, so they are safe to suggest unless the
user pins 0.5.x:
autumn serve --daemon # non-watch local daemon; also: serve stop|status|restart
# native on Windows too (#1639): TCP transport,
# file-requested graceful drain, same serve.addr
autumn serve --bundled-pg # managed local Postgres (managed-pg-bundled feature)
autumn serve install-service # Windows only, elevated: register as a boot-start,
# crash-restarting service; uninstall-service removes it
# (flags go BEFORE the subcommand: serve --bundled-pg install-service)
autumn destroy scaffold Post title:String # cleanly reverses generate; --dry-run supported
autumn generate scaffold Post title:String 'status:enum{draft,published}' 'price:decimal{10,2}' author:references email:String:unique
autumn generate scaffold Post title:String --live --live-validation
autumn generate tauri # desktop sidecar project (cargo tauri build)
autumn generate plugin my-plugin # installable/conformant plugin crate
autumn token issue service:ci --name ci --scope posts:write # scoped tokens; also list, rotate
autumn i18n check # compare t!/t(...) keys vs i18n/*.ftl; --strict, --format json
autumn test # provision/target an isolated *_test DB, migrate, then cargo test
autumn test --reset -- --nocapture # drop+recreate the test DB; forward args to the harness
autumn db backup --keep 7 # dump control DB + shards to ./backups/<profile>/<ts>/; db restore <artifact> reverses it
autumn db backup --upload --keep 7 # + upload each verified run offsite (S3/MinIO/R2); db offsite list; db restore offsite:<profile>/latest # (0.6.0)
autumn db replica restore --force # SQLite tier: rebuild from the continuous replica; --timestamp <RFC3339> for PITR, --overwrite to replace an existing file # (0.7.0)
autumn db replica status --json # replica generation, segments, and current replication lag; db replica verify proves it restorable # (0.7.0)
autumn fleet list --open # SQLite fleet (sqlite CLI build): every tenant/slot database; migrate | backup <key> <dest> | import <key> <src> | delete <key> --force | restore <key> [--timestamp T] --force
autumn db scrub --artifact backups/prod/<run> --force # restore a prod backup into staging, then anonymize every PII column; --check for CI
autumn db scrub --sample users=1% --seed 42 # scrub AND subset in one pass: 1% of users plus every row they relate to, reproducibly
autumn db retention --dry-run # per-dataset retention window, its source, and rows eligible for purge; --purge to enforce now (needs --force outside dev/test), --dataset X, --json # (0.7.0)
autumn seed --count 50 --model Post # generate+insert 50 faked rows via the model's factory (both flags together)
autumn serve --role worker # run only workers + scheduler (web/worker split); also --role web|combined
autumn console # data playground: scaffolds src/bin/playground.rs (pre-wired config+pool), then builds and runs it; alias `autumn c`
autumn console --force # regenerate the playground from the template (never overwritten otherwise)
autumn console --scaffold-only # scaffold + wire Cargo.toml, then stop
autumn console --repl # interactive Rhai prompt: PostRepository::find_all() / find_by_id(id) / count()
autumn release init --target azure-container-apps # Terraform scaffold: main.tf/variables.tf/outputs.tf/terraform.tfvars.example (ACR, Container Apps, Postgres Flexible Server, Key Vault-backed secrets, opt-in Redis) + .github/workflows/azure-deploy.yml (#1278) + azure-cutover.sh, which attaches the identity and secret refs with the real image (#2314). Same --force/collision guard as the fly/docker-compose targets; see docs/guide/deployment.md.
autumn release init --target aws-app-runner # Fast/minimal AWS path: main.tf/variables.tf/outputs.tf/terraform.tfvars.example (ECR, App Runner behind a VPC connector, RDS Postgres, Secrets Manager). No CI workflow (#1279); see docs/guide/deployment.md.
autumn release init --target aws-ecs # Production AWS path: main.tf/variables.tf/outputs.tf/terraform.tfvars.example (VPC, ALB+ACM DNS-validated HTTPS, ECS Fargate w/ circuit-breaker rollback, Application Auto Scaling, RDS, opt-in Redis) + .github/workflows/aws-deploy.yml (#1279); see docs/guide/deployment.md.
autumn release init --target gcp-cloud-run # GCP path: main.tf/variables.tf/outputs.tf/terraform.tfvars.example (Artifact Registry, Cloud Run, Cloud SQL Postgres behind a VPC connector, Secret Manager, opt-in Memorystore Redis) + .github/workflows/gcp-deploy.yml (#1280); see docs/guide/deployment.md.
# Release probe paths (#3066): every target sends traffic checks to /ready and liveness to /live, never the /health alias.
# Image HEALTHCHECK -> /startup (compose --wait waits for startup; Swarm does not replace containers during a DB outage). ECS ALB target group and App Runner cutover -> /ready.
# Cloud Run -> startup probe /ready (its only traffic gate), liveness /live. Azure Container Apps -> startup /startup, readiness /ready, liveness /live. Fly -> /ready + /live.
autumn migrate new add_widget_archived_at # collision-free migration dir: prefer this (or `generate migration`) over hand-creating one — see "Migration version collisions" below
autumn migrate check-collisions # CI gate: fails if this branch's migration version collides with the default branch, another pushed branch, or the framework's own migrations
autumn sbom # CycloneDX 1.5 SBOM for this source tree, to stdout (deterministic: no timestamp, content-derived serialNumber) (0.8.0, issue #1615)
autumn sbom --output sbom.cdx.json --locked # write it; --locked fails when Cargo.lock disagrees with the manifests
autumn sbom --verify sbom.cdx.json --expect-version 0.11.0 # regenerate + compare component-by-component, and pin the root version; exit 1 with a named diff on drift
autumn sbom --binary /usr/local/bin/my-app # crate versions compiled INTO a binary (cargo-auditable `.dep-v0`; ELF/Mach-O/PE) — no source tree, no lockfile
autumn build --auditable # compile through `cargo auditable` so the binary carries its own dependency list (the generated release Dockerfile passes this) (0.8.0, issue #1615)
autumn upgrade # preview BOTH halves as per-file diffs, writing nothing: each release's mechanical app-code migrations (renames), and drift between the project's framework-owned files and this release's scaffold (#1629, #1593)
autumn upgrade --apply # take them; --from/--to override the codemod range, --list-migrations shows what ships
autumn upgrade --check # scaffold files only, writes nothing, exit 3 on drift — the CI gate for scaffold freshness (#1593)
autumn upgrade --accept <PATH> # record a framework-owned file as the developer's own: never offered or written again, and not drift (#1593)
autumn deploy check # SSH/secret/DB/migrate-safety preflight per configured host; `doctor --online` runs the same graders
autumn deploy plan # dry-run: representative unit + ordered steps (+ fleet rollout order when `[deploy] hosts` is set)
autumn deploy up # real deploy over SSH; with `[deploy] hosts` a serial rolling deploy across the fleet (#1621)
autumn deploy up --only web-2 --no-rollback # narrow to a subset (repair lever, warns about a mixed fleet) / halt-and-freeze on failure
autumn deploy rollback # previous release; with `[deploy] hosts` the whole fleet, newest first (`--only <HOST>` for one)
autumn deploy status --json --strict # read-only per-host state + version/state drift; --strict exits non-zero on drift (#1621)
autumn deploy maintenance on --message "…" # maintenance mode on EVERY deploy host over SSH; `off` reverses (#1621)
autumn plugin list # installable plugins + the version compatible with this app's autumn-web; --json, --offline (#1606)
autumn plugin add autumn-admin-plugin # dependency + builder-chain mount + post-install steps; idempot
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
rust-web-framework, axum, maud, htmx, diesel, postgres, tailwind, proc-macros
Generated from the plugin's indexed repository (autumn-foundation/autumn) — no native marketplace selected
npx claudepluginhub p/madmax983-autumn7 skills in this plugin
/autumn-patternsUse when writing, reviewing, or debugging Rust code in an autumn-web project; covers idiomatic patterns for testing, repositories, service layers, job design, security, error handling, and Maud templates that are not covered in the framework API reference.
/devUse when the user runs /autumn:dev, asks to start the Autumn development server, enable hot reload, or check what's running locally.
/doctorUse when the user runs /autumn:doctor, asks to audit their Autumn app's configuration, check for deployment readiness, or diagnose config problems, missing secrets, or stale migrations.
/generateUse when the user runs /autumn:generate, asks to scaffold a resource, generate a model, migration, controller, mailer, or task using the autumn CLI.
/newUse when the user runs /autumn:new, asks to create a new Autumn web application, or wants to scaffold a fresh project with the autumn CLI.
/routesUse when the user runs /autumn:routes, asks to list registered routes, inspect route handlers, check what endpoints exist, or audit an Autumn app's routing table.
Other plugins' skills for the same job