Expand description
CrateStack server facade — Postgres (sqlx) + Axum.
This crate is the server-side slice of the framework. It re-exports the shared schema / parser / policy / SQL surface plus the sqlx (Postgres) runtime, Axum HTTP bindings, and the generated Rust client runtime.
It deliberately does not depend on cratestack-rusqlite. That keeps
libsqlite3-sys out of the dep graph, so consumers can use the official
sqlx umbrella crate (which optionally declares sqlx-sqlite and trips
Cargo’s links = "sqlite3" collision rule) without needing a local
sqlx-shim workaround.
For embedded / mobile / wasm targets, depend on cratestack-sqlite
instead. The two crates are strictly disjoint by design.
Schema macros emit ::cratestack::* paths, so consumers rename this
crate via Cargo’s package = field:
[dependencies]
cratestack = { package = "cratestack-pg", version = "0.4" }sqlx/cratestack-sqlx sit behind the default-on postgres Cargo
feature (cratestack#329). A db = None-only consumer
(include_server_schema!(schema, db = None), cratestack#328) can drop
sqlx from its dependency graph entirely:
[dependencies]
cratestack = { package = "cratestack-pg", version = "0.4", default-features = false }See docs/design/no-database-mode.md for when db = None applies and
what it gives up.
Re-exports§
pub use async_stream;pub use chrono;pub use cratestack_client_rust as client_rust;pub use futures_util as futures;pub use regex;pub use serde;pub use serde_json;pub use tracing;pub use uuid;pub use cratestack_axum::axum;
Modules§
- audit
- Audit log primitives.
- authn
- Authentication requirements (ADR 0022, cratestack#1244): how recently and how strongly a caller must have authenticated for one operation, and the step-up refusal when it has not.
- axum
- axum is an HTTP routing and request-handling library that focuses on ergonomics and modularity.
- backplane
- The subscription backplane (
docs/design/subscriptions-websocket.md§4): how a published message reaches every replica, so a subscriber connected to one replica sees a write committed on another. - batch
- Batch envelope.
- bigint
BigInt, the schema’s 64-bit signed integer scalar (ADR 0019).- builder
- Type-level markers for the generated typestate builders.
- chain
- The first-success provider chain (ADR 0021 §5, cratestack#1243):
several
AuthProviders composed into one, in order. - client_
contract - Per-op contract digests (cratestack#1123, EXT-14): the 32 bytes that move only when the wire shape of one op changes.
- compact
- Compact wire keys (
docs/design/compact-wire-keys.md, proposal C): the type trees that let a codec swap a body’s field names for integers. - compact_
layer - The server side of compact wire keys (
docs/design/compact-wire-keys.md§5.1, proposal C): a tower layer that swaps schema-declared field names for integer keys on the wire, so the handlers behind it never see them. - composite_
id - Composite
@@id([...])primary keys: detection, and the one message every entry point uses to reject them. - context
- Request-scoped context: authenticated identity, structured
principal, transport extensions, plus the
AuthProvidertrait that auth middlewares implement. - cose
cratestack-cose: the COSE envelope of ADR 0006, unary part (P0).- credential
Credential: what anAuthProvidersays about a request before authenticating it — whether the request carries the provider’s kind of credential at all (ADR 0021 §4, cratestack#1243).- cuid
- Generate the value for
@default(cuid())(cratestack#1209). - cursor
- Opaque keyset-cursor encoding shared by generated
listroutes and hand-writtenCursorPageInput/CursorPage<T>procedures (docs/design/cursor-pagination.md). - decimal
- Decimal scalar(s).
- envelope
- Signed envelope (HMAC-SHA-256).
- envelope_
layer - The server envelope layer (ADR 0006 §§2, 10, 12; cratestack#1006): opens signed requests and seals responses for the generated REST and RPC routers, before rate limiting and idempotency run.
- error
CratestackError— the framework’s error type, its 4xx/5xx HTTP mapping, and the public response envelope clients see on failure.- events
- Model-event bus: typed
created/updated/deletedenvelopes that procedure handlers can subscribe to. - find_
many - Built-in support for the
FindMany<Model>procedure-argument type (.cstacksyntax) — search-with-filters for procedures. Composes withPageInputrather than absorbing it — a procedure wanting both filtering and pagination declares two arguments, e.g.procedure search(query: FindMany<Post>, page: PageInput): Page<Post>. - headers
- Header helpers used by axum-bound handlers: optimistic-locking ETag
parsing/emission, W3C
traceparentextraction, RFC 7239Forwarded/X-Forwarded-Forclient-IP extraction (honored only from a configuredcrate::trusted_proxy::TrustedProxyConfig— seeenrich_context_from_headers, #415), and context enrichment that bundles those. - idempotency
- Idempotency-key middleware.
- idempotency_
record - Persisted record + reservation-outcome state machine.
- json
- Schema-declared
Jsoncolumns need a model-struct field type that’s the same on every backend so the same struct compiles on server and on embedded (includingwasm32-unknown-unknown, which can’t depend on sqlx). - lenient_
bytes - Wire-shape-tolerant deserialization for schema
Bytesfields — see cratestack#783. - limits
- Cross-cutting request/response size ceilings for the generated Axum
surface (cratestack#413). Lives in its own module rather than being
appended to
page.rs/batch.rs: those two already own their own numeric ceiling (MAX_LIST_LIMIT,BATCH_MAX_ITEMS) scoped to their own concern, so a body/response-size constant that cuts across both REST and RPC belongs in a module of its own — seedocs/design/request-response-size-bounds.md(Reviewer notes) for the reasoning. - log_
throttle - A “log at most once per interval, and say how many you swallowed” counter (cratestack#846).
- op_list
- The one list of ops a schema exposes (cratestack#1123, EXT-14).
- page
- Generic paginated-page envelope used by every
listroute. The shape mirrors what generated clients consume. - pascal_
case - Canonical PascalCase derivation for a schema-declared identifier
(currently: procedure names, which are declared camelCase in
.cstacksource but need a PascalCase spelling wherever a generator emits a top-level symbol derived from one — e.g. a procedure’s generated argument-wrapper class). - patch
- Shared “double
Option” (de)serialization forUpdate{Model}Inputfields that back a nullable column — see cratestack#567. - procedure_
route - Canonical REST route path for a procedure, including its
@api_versionprefix. - query
- Query-string parsing for axum-bound handlers: percent-decoded pair
extraction and the structured filter expression grammar
(
?where=...) used by macro-generatedlistendpoints. - ratelimit
- Per-principal rate limiting.
- route_
naming - Canonical REST route-segment derivation for a model name.
- rpc
- Runtime primitives for the
transport rpcgeneration style. - rust_
keywords - Rust keyword classification, shared by
cratestack-parser(schema-time field-name validation) andcratestack-macros(identifier escaping at codegen time) so the two stay in sync — see cratestack#398. - schema
- Schema IR — the parsed shape of a
.cstackfile. Every IR node carries source-span back-pointers so consumers can map errors to positions in the original text. - schema_
fingerprint - Drift-detection middleware for the
x-cratestack-schema-shaheader (issue #178). Every generated client stamps its ownSCHEMA_SHA256constant (the schema’s canonical identity,cratestack_core::schema_digest) onto every request; this middleware compares that value against the server’s own constant andtracing::warn!s on a mismatch — nothing more. It never rejects a request: a missing header (a client not yet regenerated) is not itself a warning, and a present-but-different value only ever produces a log line, never an error response. Applies to every transport (rest/rpcalike), since nothing about schema drift is transport-specific. - schema_
identity - The canonical schema identity (cratestack#1065): the whole-IR digest.
Binding version 1 bound it into the COSE AAD as
schema_sha; binding version 2 binds the per-opcontract_shaofcrate::client_contractinstead (ADR 0006 §4, cratestack#1123), and this digest is now the identity the warn-onlyx-cratestack-schema-shadrift header carries. - sqlx
- Compatibility shim that exposes a
sqlx-shaped API by re-exporting fromsqlx-core+sqlx-postgresdirectly. - store
- Pluggable storage traits for idempotency, rate limiting, and client state, shared between transport and backend-runtime crates.
- subscription
- The transport-neutral half of a subscription
(
docs/design/subscriptions-websocket.md§6.1). - subscription_
wire - What every subscription session binding shares
(
docs/design/subscriptions-websocket.md§6.3, §6.4, §6.6): the frames, admission (Init, authentication, refusal close codes), which browser origins may open a session, the per-principal session count, and the rate-limit seam that charges each subscription open. WebTransport (cratestack-webtransport) and WebSocket (cratestack-websocket) only move these frames over their own transport. - trusted_
proxy - Trusted-proxy configuration for the audit
client_ip(#415):TrustedProxyConfigplus the tests covering the allowlist/hop-count behavior in isolation from header parsing (see [crate::headers::forwarded] for the hop-count-aware chain walk itself andcrate::headers::enrich_context_from_headersfor where the two are combined). Seedocs/design/trusted-proxy-client-ip.mdfor the decided design. - validators
- Field-level validators.
- value
- Backend-agnostic JSON-shaped value used throughout the framework (auth claims, audit payloads, RPC error details, schema config).
Macros§
- include_
client_ schema - HTTP client schema: model/input/procedure stubs for talking to a server
over the wire. No DB, no router, no FromRow impls. Renamed from
include_client_macro!in 0.3.0. - include_
embedded_ schema - Embedded ORM schema: rusqlite backend only. Compiles to native and to
wasm32-unknown-unknown(viasqlite-wasm-rs). No sqlx, no axum, no procedures. Local apps that don’t need an RPC surface use this. - include_
server_ schema - Full server schema: sqlx Postgres backend,
Cratestackruntime, axum router, procedures, events. Passdb = Postgres(only value currently supported; MySQL / SQLite-via-sqlx will land in a future release).
Structs§
- Aggregate
- Aggregate
Column - Aggregate
Count - Attribute
- Audit
Actor - Audit
Event - Auth
Block - Auth
Refusal - A refusal an
AuthProviderreturns, asCratestackError::AuthRefusedthroughAuthRefusal::into_error. See the module documentation. - Authn
Requirement - What one operation requires of the caller’s authentication. Every part is optional; a requirement with none is satisfied by any caller.
- Batch
Item Error - Public, safe-to-expose shape of a per-item failure. Mirrors
crate::CratestackErrorResponsewithout the optionaldetailsfield — batch callers asking for per-item detail can repeat the operation singly against the failed item to get the full error envelope. - Batch
Item Result - Per-item result inside a
BatchResponse. Theindexis the item’s position in the original request, so clients can pair results with inputs even after server-side reordering (e.g. parallelbatch_getfetches in the future). - Batch
Request - Wire envelope for
POST /<model>/batch-*request bodies. Holds the items in a single field so the envelope can grow (e.g. a futureclient_request_id) without breaking deserialization. - Batch
Response - Wire envelope returned by every batch route. Always
200 OKat the HTTP layer; inspectsummary.err(or scanresults) to surface per-item failures to the user. - Batch
Summary - Summary counts attached to every
BatchResponseso callers can branch on aggregate status without scanning the result list. - BigInt
- A signed 64-bit integer that travels as a canonical decimal string on every codec. See the module documentation for the wire form.
- Binding
- Everything that goes into a sealed body’s COSE
external_aad(ADR 0006 §4). It is never sent: the router and the client each rebuild it from context they already hold, so the binding costs 0 bytes on the wire. A body sealed for one(audience, method, route, path_params, query, op contract)fails to open under any other, which defeats cross-service and cross-endpoint replay; a response is bound to its request (the digest and how it was computed) and its status, which defeats response swapping; a signed REST response is bound to the resource it answers, not only to the route’s shape; and a client whose wire shape for the op differs from the server’s fails closed oncontract_sha(binding version 2: per op, not per schema). - Bound
Headers - The two request headers that change what a request does, bound into
the AAD as
bound_headers: [idempotency_key: tstr / null, if_match: tstr / null], right afterpayload_type. - Bounded
Outcome - What
super::RateLimitStore::consume_boundedreturns: the ordinary decision, plus which bucket produced it. - Bucket
Budget - A cap on the number of distinct bucket keys one scope may create in a window, plus where traffic beyond the cap is charged instead.
- Cached
Auth Provider - An
AuthProviderthat always returns a single, already-establishedCratestackContext, ignoring whateverRequestContextit is asked to authenticate. - Cbor
Codec - The CBOR codec.
decoderefuses input nested deeper than [DEFAULT_MAX_DECODE_DEPTH] levels (cratestack#1315); useCborCodec::with_max_depthfor another limit. - Client
IpContext - The trusted-proxy configuration (if an
Extension<TrustedProxyConfig>was applied to the router), the verified socket peer (if the router is served viainto_make_service_with_connect_info), and a clone of the request’s fullhttp::Extensionsmap, bundled into a single axum extractor so every generated dispatch fn threads one new parameter instead of several (#415). - Coalesce
Expr - Left-hand operand of a coalesce-based filter — chain a comparator
method to turn it into a
FilterExpr. - Coalesce
Filter COALESCE(col_a, col_b, ...) <op> <value>— left-hand expression is the first non-null among the listed columns; right-hand side is a bound value via the usualFilterValueenvelope. Lets schemas express the “ranked-fallback compare” pattern that shows up in outbox / scheduler tables, where a single row carries several time columns and the dispatcher wants the earliest non-null one.- Codec
Set - Config
Block - Config
Entry - Consume
Request - One token-consumption request: the bucket the caller asked for, the token-bucket parameters, and optionally the budget that governs whether that bucket may be created at all.
- Contract
Lock - A parsed, integrity-checked lock file.
- Contract
Selector - The first
CONTRACT_SELECTOR_LENbytes of an op contract digest. - Cratestack
Auth Identity - Cratestack
Context - Cratestack
Context Builder - Builds an authenticated
CratestackContext; start one withCratestackContext::builder. A later call for the same claim replaces the earlier value, exceptSelf::tenantand thecnfsetters, which merge into the existing map. - Cratestack
Error Response - Cratestack
Event Bus - Cratestack
Event Envelope - Create
Default - Create
Record - Cursor
Page - Built-in cursor-paginated response (
CursorPage<T>in.cstack, procedure-return only): the items plus the cursor for the next page, absent on the last page. - Cursor
Page Input - Built-in cursor (keyset) pagination input (
CursorPageInputin.cstack), procedure-argument only — the keyset sibling ofPageInput.cursoris the opaque token a previousCursorPage::next_cursorreturned; absent (or empty) means “first page”. Seedocs/design/cursor-pagination.md. - Datasource
- DbError
Info - Structured information extracted from a driver-level database error.
- Delete
Many - Delete
Record - Enum
Decl - Enum
Variant - Field
- Field
Filter Input - Every operator a filterable field might support, as one flat
optional-per-operator envelope — generated per-model code reads only
the operators that make sense for a given field’s type (e.g. a
Booleanfield’s generatedto_filters()never looks atcontains).Vis the field’s own scalar Rust type (String,i64,bool,chrono::DateTime<Utc>, …) — neverOption<V>even for an optional field, since these operators describe a value to compare against, not the field’s own nullability (whichis_nullcovers instead). - Field
Ref - Filter
- Find
Many - Find
Many With - Find
Unique - First
Success - A first-success chain of
AuthProviders, itself anAuthProvider. Built withfirst_success. - Generated
Default - A column cratestack fills on create when the input leaves it out.
- Generation
- One locked moment: the client contract digest and each op’s digest then.
- Hmac
Envelope - HMAC-SHA-256 backed envelope. Sealed messages are self-describing
CBOR maps: signature recipients can decode the envelope, fetch the
key by
kid, and verify without out-of-band coordination. - Idempotency
Record - Persisted idempotency record returned on a replay. Banks need an invariant view of the captured response — the store rebuilds this from its persisted columns when the second caller asks to replay.
- InMemory
Nonce Store - In-memory nonce store. One mutex; the working set is bounded by the clock-skew window — a 5-minute skew at 10k req/s caps at ~3M entries, which is fine. Production multi-replica deployments swap in Redis.
- InMemory
State Store - InProcess
Backplane - Subscription backplanes (
docs/design/subscriptions-websocket.md§4):PgNotifyBackplaneis the default;InProcessBackplaneserves a single replica. Swap withCratestack::builder(pool).with_backplane(..). - Incompatible
- A locked contract the current one no longer stays compatible with.
- Json
- Wrapper for a schema-declared
Jsoncolumn’s Rust field type. See the module docs for why this exists instead ofsqlx::types::Json<Value>. - Json
Codec - Json
File State Store - Json
Text Path - Left-hand operand of a
json_get_textfilter — chain a comparison method (.eq,.lt,.is_null, …) to produce aFilterExpr. - Keyset
Column - Lenient
Bytes Vec<u8>newtype whoseDeserializeaccepts a byte string or a sequence of integers. See the module docs.- McpConfig
- The top-level
mcp { }block. - McpName
- The
name = "..."entry of themcp { }block. - Migration
- A single migration step. The runner applies any rows not yet
present in
cratestack_migrations.downis recorded but never called — irreversible-by-default is the safe banking posture. - Migration
State - Mixin
Decl - Model
- Model
Column - Model
Delegate - Model
Descriptor - Model
Event - Model
McpExposure @@mcp(resource: "...")on a model: expose it as a read-only MCP resource.- Model
OpIds - The five RPC op ids of a model, for a generator’s template context, so a
template never spells
"model.<Name>.list"itself. A verb@@internalsuppresses still has an id here: the template only reads the ones its ownallows_*gate admits. - Multicast
Audit Sink - Fan an audit event out to multiple sinks. Errors from any
individual sink are aggregated into
CratestackError::Internalso a single failing downstream does not silently swallow problems with the others. - NoEnvelope
- Pass-through envelope used when transport-layer signing is not required.
- Noop
Audit Sink - Default sink that does nothing. The in-database audit table is treated as authoritative; downstream consumers are added by wrapping a different sink (or composing several).
- OpDescriptor
- Wire-shape of a single op in a
transport rpcschema. Seedocs/design/rpc-transport.mdfor the full design — in short, an op is the dispatch unit shared by every RPC binding (HTTP unary, HTTP batch, HTTP stream, WebSocket). The macro emits oneOpDescriptorper CRUD verb and per procedure whenSchema.transport == TransportStyle::Rpc. - Or
- Two chain members,
firstasked beforenext. - Order
Catalog - One model’s order-by surface: its own sortable scalar columns
(
(api_name, sql_column)) and its own to-one relation edges. Exactly oneOrderCatalogis emitted per model, regardless of how many distinct relation paths pass through it. - Order
Clause - Order
Relation Edge - One to-one relation edge out of a model.
targetpoints at the related model’s own catalog soresolve_order_targetcan keep walking further segments; to-many relations are never represented here (mirroring the codegen’s existing to-one-only walk), so a key that names one simply fails to resolve. - Orderable
- Marker for a path whose hops are all to-one, so a scalar at the end of it can be rendered as a correlated subquery and used for ordering.
- Owned
Schema Summary - Page
- Page
Info - Page
Input - Built-in pagination-input argument type (
PageInputin.cstack), currently valid only as a procedure argument — the request-side mirror ofPage/PageInfoon the response side. Field names and optionality matchPageInfo’s ownlimit/offsetexactly, so a generatedlistroute and a hand-writtenPageInput-accepting procedure decode the same wire shape. - Parse
BigInt Error - Why a string is not a canonical
BigInt. - Parsed
Composite Unique - The parsed shape of an
@@unique([...], where: "...")attribute. - Parsed
Index Attribute - The parsed shape of an
@@index([...], using: ..., opclass: "...", where: "...")attribute. - Persisted
Client State - PgNotify
Backplane - Subscription backplanes (
docs/design/subscriptions-websocket.md§4):PgNotifyBackplaneis the default;InProcessBackplaneserves a single replica. Swap withCratestack::builder(pool).with_backplane(..). - Principal
Context - Principal
Facet - Procedure
- Procedure
Arg - Procedure
McpExposure @mcp(tool ...)on a procedure: expose it as an MCP tool.- Procedure
Policy - Projected
Find Many - Projected
Find Unique - Projection
- Result of a
.select(...)-projected read. Holds the model with only the selected columns populated — non-selected fields carry their type’sDefault::default()value (""forString,0for integers,NoneforOption<T>, etc.). - Pruned
- What a prune removed.
- Query
- Rate
Limit Config - Configuration for a single bucket: capacity (max burst) and refill rate in tokens per second. Banks running high-frequency back-office traffic pick large bursts; consumer-facing channels use small bursts to dampen abuse.
- Read
Policy - Relation
Filter - Relation
Hop - One traversed relation edge: the FK linkage, how the related rows are
quantified (
ToOnefor a plain to-one hop,Some/Every/Nonefor a to-many hop under a quantifier), and the related model’s read scope, which every backend that enforces policy applies inside the subquery this hop renders to (GHSA-p55v-6xv5-93p3). - Relation
Include - Typed handle for an
.include(...)call on a query builder. Carries everything the runtime needs to issue the side-load query for a to-one relation: a function pointer that extracts the FK value from a parent row, and a static descriptor of the related model. - Request
Context - Everything an
AuthProvidergets to see about an inbound request. - Request
Digest - A request’s digest together with the
RequestKindthat says how it was computed. - Request
Journal Entry - Request
Nonce - A
Cratestack-Nonce: 16 bytes, chosen by the client. - Reserved
Claim - One reserved claim: its path (a dotted path for a facet member such as
tenant.id) and the type it must have. - Reserved
Ordinals - An enum’s
@@reserved(n, …)line: ordinals no variant may use, ever. - Resolved
Order Target - A dotted sort key resolved down to the relation hops to traverse plus
the terminal scalar column, ready for
crate::OrderClause::relation_path(each hop carries the related model’s read scope). - Response
Binding - The part of a
Bindingonly a response has: which request it answers, and with what status. - Route
Transport Capabilities - Wire-level capabilities for one route under a REST binding.
- Route
Transport Descriptor - RunIn
TxOutcome - See the module doc comment.
- Rust
Decimal Decimalrepresents a 128 bit representation of a fixed-precision decimal number. The finite set of values of typeDecimalare of the form m / 10e, where m is an integer such that -296 < m < 296, and e is an integer between 0 and 28 inclusive.- Schema
- Schema
Error - A schema error, identified by which file it came from (cratestack#916).
- Schema
Summary - Scoped
Aggregate - Scoped
Aggregate Column - Scoped
Aggregate Count - Scoped
Create Record - Scoped
Delete Many - Scoped
Delete Record - Scoped
Find Many - Scoped
Find Many With - Scoped
Find Unique - Scoped
Model Delegate - Scoped
Projected Find Many - Scoped
Projected Find Unique - Scoped
Update Many - Scoped
Update Many Set - Scoped
Update Record - Scoped
Update Record Set - Scoped
Upsert Record - Scoped
Upsert Record DoNothing .upsert(..).do_nothing()bound to aCratestackContextvia.bind(ctx). SeeUpsertRecordDoNothingfor the run-time semantics; this is purely actx-carrying wrapper, same relationship asScopedUpsertRecordhas toUpsertRecord.- Sealed
Envelope - Sealed
Item - What sealing one stream item produced.
- Selection
Query - Source
Span - SqlColumn
Value - Sqlx
Idempotency Store - Static
KeyProvider - In-memory
KeyProviderfor tests and single-tenant deployments. Banks running real workloads bring a backed implementation (KMS, Vault, HSM). - Subscription
Guard - RAII cleanup for one or more
CratestackEventBussubscriptions that all share one lifecycle — e.g. the per-operation handlers a singleGET /rpc/subscribe/{op_id}connection registers for the duration of its SSE stream (docs/design/rpc-transport.md§3.4a, cratestack#390). Every tracked handle is unsubscribed when the guard drops, whether that’s because the underlying stream ended normally (backpressure overflow) or because it was cancelled mid-poll (an ordinary client disconnect) — both just drop this guard the same way, so cleanup doesn’t need to special-case which one happened. Without this, a long-running server would accumulate one permanently-registered, permanently-a-no-op handler per historical connection — a real unbounded-memory footgun for a public, freely-reconnectable endpoint, not a hypothetical one. - Subscription
Handle - Opaque token returned by
CratestackEventBus::subscribe, needed to later remove that exact handler viaCratestackEventBus::unsubscribe. Fields are private — the only way to obtain one issubscribe, and the only thing it’s good for is passing back tounsubscribe. - Subscription
Open - Everything a dispatcher needs to open one subscription. Owned, so the
future
SubscriptionDispatcher::openreturns borrows nothing from the binding’s connection state. - System
Context - A context representing trusted in-process/server code (a procedure, a worker, a reconciliation job) rather than an end user.
- Topic
- A schema
topic’s handle (slice S4):db.topics().<topic>(key). One topic under one key. Cheap to build; hold none.subscribeandchannelare theTopicHandle’s;publishis this type’s own, so a topic bound to an@isolationattempt rides it. - Topic
Handle - One topic under one key. Cheap to build; hold none.
- Transaction
Abort - Payload of
CratestackError::TransactionAborted. - Trusted
Proxy Config - Which peers are trusted to set
Forwarded/X-Forwarded-For, how many hops into the chain to trust when they are, and which of the two headers to honor. - Tx
- Opaque handle onto a live Postgres transaction. Obtained only via
SqlxRuntime::transaction; never constructed directly by consumers. - Type
Decl - TypeRef
- Unorderable
- Marker for a path that has crossed a to-many hop. Ordering accessors are
not implemented for this marker, which reproduces the old guarantee that
asc()/desc()simply did not exist past a to-many relation — a compile error, not a runtime failure. - Update
Many - Update
Many Set - Update
Record - Update
Record Set - Upsert
Record - Upsert
Record DoNothing - Vector
Distance Expr - Builder returned by
FieldRef::distance_to— chain a comparator (.lt/.lte/.gt/.gte/.eq) for a threshold filter, or.asc/.descto use it as anORDER BYtarget. The common k-NN “closest first” case is.asc(); see alsoFieldRef::order_by_distance, sugar for exactly that. - Vector
Distance Filter <column> <metric op> <query_vector> <cmp> <value>— a distance-to- a-query-vector expression compared against a bound threshold. Built via [super::field_ref_ext]’sFieldRef::distance_to, then a comparator method turns it into aFilterExpr. Mirrorssuper::CoalesceFilter’s shape: a left-hand computed expression plus a bound right-hand value.- Verified
Signer - The key that signed a request body, as verified by
CratestackEnvelope::open. - View
- View
Delegate - View delegate for views that declared an
@idfield. Exposesfind_many+find_unique(andrefresh()on materialized views). Views declared@@no_uniquegetViewDelegateNoUniqueinstead, which omitsfind_uniqueat the type level so a call likeruntime.views().<v>().find_unique(())is a compile error rather than a runtime “WHERE = $1” footgun. - View
Delegate NoUnique - View delegate for views declared
@@no_unique. Exposes onlyfind_many—find_uniqueandrefresh()are absent at the type level because: - View
Descriptor - View
Source
Enums§
- Abort
Ownership - Where a
CratestackError::TransactionAbortedstands relative to the procedure dispatch that answers the request. DecidesCratestackError::is_idempotency_replayableand what the response says (CratestackError::disowned_transaction_abort). - Audit
Operation - Auth
Refusal Kind - Whether the caller is unknown (401) or known and refused (403).
- Backplane
Message - One delivery on a backplane channel.
- Batch
Item Status - Either a successful per-item outcome (
Ok) or a per-item failure (Error). Serializes as a tagged enum with the discriminant instatus: - Body
Shape - Which kind of body an envelope is asked to name a media type for.
- Charged
- Which bucket a
super::RateLimitStore::consume_boundedcall ended up charging, and why. Purely observational — the decision itself is carried byBoundedOutcome::decision— but it is what lets the middleware log an in-progress amplification attempt instead of silently absorbing it. - Claim
Type - The type a reserved claim must have.
- Computed
Params Arg - The parenthesized argument of a
@computed(...)attribute, however it parses. - Conflict
Target - Conflict target for an upsert. Defaults to the model’s primary key
(matching the previous PK-only behavior).
Self::Columns/Self::columnslet callers upsert on an arbitrary unique tuple — most commonly a natural key that’s distinct from the PK (e.g.(owner_id, provider)on a per-owner-and-provider settings row, or(pairing_id, slot)on a per-slot envelope). - Cratestack
Error - Create
Default Type - Credential
- Whether a request carries a provider’s credential. See the module documentation.
- Extension
Kind - An opt-in framework/database capability a schema announces via a
top-level
extension <name> { }block (cratestack#153). Declaring an extension only unlocks schema-visible syntax for that capability (e.g.@no_rate_limit, theVector(n)scalar type) — it never gates codegen or runtime behavior by itself; that’s a separate, same-named Cargo feature per consuming crate (cratestack#161, out of scope here). - Field
Path - A position in a request body: the root, a field of the value above it, or an element of the list above it.
- Filter
Expr - Filter
Op - Forwarded
Header - Which single forwarding header a trusted proxy is expected to write.
- Generated
Value - What cratestack generates for a
@default(now()),@default(uuid())or@default(cuid())column (cratestack#1209). Chosen per field type at codegen, so the value binds as the column’s own type. - Json
Filter - JSON / JSONB filter predicates. Two flavors:
- KeyRole
- Which device key proved this request (the
key_roleclaim): one that never prompts, or one that prompts for user presence on every signature. - Keyset
Leaf - One comparison the caller must turn into a typed filter on
column. - Lock
Error - Why a lock could not be read or used.
- Migration
Status - Model
Event Kind - Model
Verb - What an op does to its model.
- Null
Order - Where NULLs sort relative to non-NULL values. PostgreSQL’s default is
NULLS LASTforASCandNULLS FIRSTforDESC; SQLite’s default isNULLS FIRSTfor both. CrateStack pins the framework default toNULLS LASTso listings stay deterministic across backends and so soft-deleted rows (typedOption<DateTime>that surface asNonefor visible rows) don’t muscle their way to the top of every listing. Override per-clause viaOrderClause::nulls_firstwhen scheduler / outbox queries want fresh-as-null tasks at the head of the queue. - OpKind
- Opened
Frame - What the opener made of one framed cbor-seq item.
- Order
Target - Path
Params - The path parameter values the router matched, in route-template order,
as it decoded them. Empty for RPC. See
Binding::path_params. - Policy
Expr - Policy
Literal - Procedure
Kind - Procedure
Policy Expr - Procedure
Policy Literal - Procedure
Predicate - Projected
Value - One projected model field, or a nested included relation. See the
module doc for why this replaces
serde_json::Valueon the projection path. - Query
Expr - Rate
Limit Decision - Result of attempting to consume a token.
Allowedcarries the number of tokens left after consumption;Throttledcarries seconds the caller should wait before retrying. - Read
Predicate - Related
Read Scope - Relation
Quantifier - Request
Kind - How the request a response answers was sent, which fixes how its
digest was computed. The AAD encodes it right before the digest, as
code. - Reservation
Outcome - Outcome of an atomic
reserve_or_fetchcall. - Sort
Direction - SqlValue
- Stream
End - How a stream ended. The terminal checkpoint that carries it is mandatory (§6).
- Transaction
Isolation - Transaction isolation level requested by a procedure via
@isolation(...). Mirrors the PostgreSQL spec: lower variants tolerate more anomalies, higher ones cost more under contention. Banks running multi-row updates (transfers, postings) typically pickSerializableand pair it with retry-on-serialization-failure. - Transport
Style - Wire-shape the schema generates for. Picked once per schema (via
the top-level
transport rest|rpcdirective) so generated servers and clients only carry one binding’s worth of surface. - Type
Arity - Unmet
- Which part of a requirement the caller did not meet, in the order the
refusal’s
details.unmetlists them. - Upsert
Outcome - Outcome of a
.upsert(..).do_nothing().run(..)call. - Value
Serialize/Deserializeare hand-written in [mod@codec] and are untagged:Value::String("foo")goes on the wire as"foo", not{"String":"foo"}. Do not replace them with a derive — that reintroduces serde’s externally-tagged enum representation into every wire payload and every generated client. See the module docs on [mod@codec] for the two format-specific choices (Nullviaserialize_none,Bytesbranching onis_human_readable) and why each is load-bearing.- Vector
Metric - Distance metric for a
Vector(n)similarity search (seedocs/design/extensions.md§6/§7, cratestack#163). Maps 1:1 onto pgvector’s three distance operators and theopclassnames used by@@index([...], opclass: "...")(cratestack#156’s DDL) — but is never inferred from an index: an index is only ever an optional access-path speedup, and AC #2 on cratestack#163 requires distance ordering/filtering to keep working with no vector index present at all (a plain sequential scan), so callers state the metric explicitly at the call site.VectorMetric::from_opclassis a convenience for callers that already know their index’s opclass and don’t want to duplicate the mapping by hand — it is never called automatically. - Verdict
- The classifier’s answer for one op.
Constants§
- AUDIT_
TABLE_ DDL - DDL for the audit log table. Banks typically run migrations
through their own tooling — this DDL is exposed so the
crate::SqlxRuntimecan idempotently ensure the table exists during bootstrap. - BATCH_
CONTRACT_ KEY - The row of a signed
/rpc/batch: the route the AAD already binds. - BATCH_
MAX_ ITEMS - Default upper bound on items in a single batch request. Server
backends enforce this before any SQL runs and surface
CratestackError::Validationon the outerResultwhen exceeded. The cap is identical for all five batch operations; deviating per-op would invite footguns wherebatch_getaccepts a list thatbatch_createof the same length rejects. - CBOR_
SEQUENCE_ CONTENT_ TYPE - CLIENT_
CONTRACT_ DOMAIN - Domain-separation tag of
client_contract_digest. - CONTRACT_
HEADER - The request header that carries the selector.
- CONTRACT_
HEADER_ VALUE_ LEN - The header value’s exact length: 8 bytes as unpadded base64url.
- CONTRACT_
SELECTOR_ LEN - The selector’s length in bytes: a prefix of the op contract digest.
- CONTRACT_
UNSUPPORTED_ CODE - The
RpcErrorBodycode (REST:CONTRACT_UNSUPPORTED) of the unsigned426a verifier answers when the selector names no accepted digest. - CONTRACT_
UNSUPPORTED_ REST_ CODE CONTRACT_UNSUPPORTED_CODE’s REST twin: theCratestackErrorResponsecode of the same unsigned426.- DEFAULT_
BODY_ LIMIT_ BYTES - Default request body limit (bytes) for the generated
router()/rpc_router()entry points, applied viaaxum::extract::DefaultBodyLimit::max(body_limit_bytes). - DEFAULT_
PAYLOAD_ MEDIA_ TYPE - What a message that names no payload type carries: CBOR.
- ENUM_
ORDINAL_ MAX - The largest ordinal a variant may carry: the column is a
SMALLINT. - ENUM_
RESERVED_ ATTRIBUTE - The block attribute that retires ordinals, so a removed variant’s number can never be handed to a new one.
- INTERNAL_
ACTIONS - Action names
@@internal(...)accepts — identical to@@allow’s vocabulary (list/detail/read/create/update/delete/all; seecratestack-macros/src/policy/model.rs’sparse_rule_actionandmodel/descriptor.rs’s action groupings) so an author never has to learn a second action vocabulary to suppress what@@allowalready describes. - LOCK_
FORMAT - The lock file format this build reads and writes.
- MAX_
CURSOR_ LEN - Upper bound on an accepted cursor’s length in characters. Cursors are attacker-controlled input; this bounds decode work before any parsing.
- MAX_
LIST_ LIMIT - Hard ceiling on the
limitquery parameter (REST) / RPC list-input field every generated list route accepts, regardless of whether the model is@@paged. Requests above this are rejected with a400, the same way negativelimit/offsetalready are — seehandle_list_<plural>_dispatchin the generated code, shared byte-for-byte between REST and RPC dispatch. - MAX_
PAYLOAD_ ACCEPT_ ENTRIES - The most types an accept list may name.
- MAX_
PAYLOAD_ TYPE_ LEN - The longest payload type, in bytes.
- MAX_
RESPONSE_ REBUFFER_ BYTES - Bound used at every
axum::body::to_bytes(body, N)call site that re-buffers aResponseproduced in-process (RPC batch per-frame re-encoding, handler-error re-shaping, and the per-frame codec round-trip helper — seecrates/cratestack-axum/src/rpc/{batch,error_encode, codec_helpers}.rs). None of these three sites face an untrusted upstream/proxied body; all buffer a response cratestack itself produced, so this is a safety valve against a pathological in-process response (e.g. a handler bug or a legitimately huge result set), never a network-trust boundary the wayDEFAULT_BODY_LIMIT_BYTESis. - MAX_
TTL_ SECS - Ceiling on any store-side TTL, in seconds: one year.
- MCP_
MAX_ PAGE_ SIZE - Hard ceiling on a collection resource’s page size (ADR 0002 Q3). A model
may lower its own maximum with
max_page_size:, never raise it past this; a larger value is a validation error, not a clamp. - MIGRATIONS_
TABLE_ DDL - NONCE_
HEADER - The request header that carries the nonce.
- NONCE_
HEADER_ VALUE_ LEN - The header value’s exact length: 16 bytes as unpadded base64url.
- OP_
CONTRACT_ DOMAIN - Domain-separation tag of an op digest.
- PAYLOAD_
ACCEPT_ HEADER - The request header that lists the response payload types the client reads.
- PAYLOAD_
TYPE_ HEADER - The request and response header that names the sealed payload’s type.
- PAYLOAD_
TYPE_ NOT_ ACCEPTABLE_ CODE - The
RpcErrorBodycode of the unsigned406a verifier answers when none of the response types the client reads may be sealed for the op. - PAYLOAD_
TYPE_ NOT_ ACCEPTABLE_ REST_ CODE PAYLOAD_TYPE_NOT_ACCEPTABLE_CODE’s REST twin.- PAYLOAD_
TYPE_ UNSUPPORTED_ CODE - The
RpcErrorBodycode of the unsigned415a verifier answers when the request names a payload type the op does not accept. - PAYLOAD_
TYPE_ UNSUPPORTED_ REST_ CODE PAYLOAD_TYPE_UNSUPPORTED_CODE’s REST twin.- PRIMARY_
KEY_ ATTRIBUTE - The one spelling that marks a field as its model’s (or view’s) primary key.
- QUERY_
SQL_ ATTRIBUTE - The attribute a
queryblock’s SQL body is written in. - REQUEST_
NONCE_ LEN - Nonce length in bytes.
- RESERVED_
CLAIMS - The reserved claim names, in the ADR’s order.
idis deliberately not one of them: many schemas declareauth User { id Int }. - RESERVED_
ENVELOPE_ MEMBERS - The envelope members an
AuthRefusalcan never set as an extra member: they belong to the framework. - STEP_
UP_ ERROR - The envelope member
error’s value, and the challenge’serrorparameter: RFC 9470’s code. - STEP_
UP_ MESSAGE - The refusal’s message, and the challenge’s
error_description. - UNAUTHENTICATED
- The one message every failed envelope verification carries (ADR 0006
§10): the peer must never learn which check failed. A malformed body, an
unknown
kid, a disallowed algorithm, a bad signature, a staleiatand a replayedctiall produceCratestackError::Unauthorizedwith this text, byte for byte.
Traits§
- Audit
Sink - Pluggable audit sink. Implementations fan audit events out to
downstream systems (Kafka topics, Redis pubsub, HTTP webhooks, S3
buckets) for long-term retention or SIEM ingestion. The in-database
audit table written by
cratestack_sqlxremains the canonical record; sinks are best-effort projections. - Auth
Provider - Resolves the caller of a request into a
CratestackContext. - Client
State Store - Cratestack
Codec - Cratestack
Envelope - The signing seam between the codec and the HTTP body (ADR 0006 §1).
- Create
Model Input - Decimal
Value - Backend-agnostic bound for a decimal scalar. Blanket-implemented for
any type satisfying these bounds — deliberately structural rather than
naming
rust_decimal::Decimal/bigdecimal::BigDecimalexplicitly, so this trait (and everything written against it, e.g.validators::validate_range_decimal) compiles unconditionally, with no#[cfg]gate of its own and no dependency on either optional backend crate. - From
Partial PgRow - Companion to
sqlx::FromRowthat decodes a row projected by.select(...)— i.e. a row where only the named columns are present in the SQLSELECTlist. Non-selected fields populate to their type’sDefault::default()value. - Http
Transport - Idempotency
Store - Into
Column Name - Anything that can name a single SQL column. Lets
coalesceaccept both bare&'static strcolumn names and typedFieldRefhandles, so callers don’t have to choose between schema-rooted typing and ad-hoc strings at the call site. - Into
SqlValue - KeyProvider
- Resolves signing keys by kid (key id). Banks running multi-tenant or rotating keysets implement this so the envelope code never has to know the storage mechanism. Implementations must be constant- time for not-found vs wrong-tenant errors — never use the error message to leak whether a key id exists.
- Model
Primary Key - Accessor for a model’s primary key. Implemented by the macro on every
generated model struct so the batch operations can pair returned rows
back to the position of their input PK in the request, producing a
BatchItemResultwith the rightindexand aNotFoundentry for any requested PK that didn’t come back. - Nonce
Store - Tracks the nonces of sealed envelopes that have already been verified inside the clock-skew window, so a captured-and-replayed request gets rejected the second time. Banks running multi-replica deployments back this with Redis so the rejection holds cluster-wide.
- Procedure
Args - Projection
Decoder - Rate
Limit Store - Pluggable storage for token-bucket state. Implementations must be safe to share across tasks (use a Mutex internally, or rely on the backing store’s atomicity).
- Read
Source - Anything a read-path query builder needs to plan and emit SQL.
- Stream
Opener - Verifies one incoming stream (§6). Framing is not its job. The cbor-seq
chunk decoder splits the body into data items and hands each one here.
The opener classifies it (item, or
Tag(48901)checkpoint) and checks the chain. - Stream
Sealer - Seals one outgoing stream (§6). Created per stream by
CratestackEnvelope::stream_sealer, which seeds the running hash withh₀ = SHA-256(external_aad). - Subscription
Backplane - Fans a published message out to every replica, this one included.
- Subscription
Dispatcher - Opens subscriptions by op id. Implemented by generated code (one impl per schema); called by every subscription binding.
- Update
Model Input - Upsert
Model Input - Input shape for the upsert primitive —
INSERT … ON CONFLICT (<pk>) DO UPDATE ….sql_values()must include the primary-key column (so the backend can target the conflict), andprimary_key_value()exposes the PK separately so the runtime can issue aSELECT … FOR UPDATEbefore the upsert to driveCreatedvs.Updatedevent / audit semantics. - Validate
Fields - Write
Source - Anything a write-path query builder needs on top of
ReadSource— create defaults, update / delete policy slots, audit + retention + versioning state, upsert column list, emitted event topics.
Functions§
- apply_
pending - Apply every pending migration in the input slice in order. Each
runs in its own transaction —
Migration::up_prethenMigration::up, both inside it — and checksum drift aborts the whole apply (banks treat drift as a release-process failure for humans, not a silent overwrite). - authorize_
procedure - Evaluate a procedure-dialect policy. Deny-by-default: an empty
allow_policiesrefuses everyone. - authorize_
query authorize_procedurefor aqueryblock (cratestack#867).- bound_
contracts - The digest a call to
method routebinds, for every key ofschema(what the macros emit asOP_CONTRACTS): each op’s digest, plus thebatchrow fortransport rpc. In key order, which nothing relies on. - bucket_
ttl_ secs - How long an idle bucket stays relevant: the time to refill a full
bucket plus a minute of slack, clamped to
[60s, 24h]. - canonical_
geometry_ subtype - Normalises a schema-written geometry subtype to its canonical
PostGIS casing, or
Noneif it isn’t a recognised subtype. - canonical_
query querydecoded asapplication/x-www-form-urlencoded, its pairs ordered by key (values of a repeated key keep their order), and re-encoded.None, and a query with no pairs, give"".- canonical_
request_ string - Canonical string assembled by the envelope signing path:
METHOD\nPATH\nQUERY\nCONTENT-TYPE\nbody-hex. Both seal and verify reconstruct the same string from the same inputs. - classify
- Judge the contract
old(a canonical op contract, as stored in a lock) againstnew(the schema’s current one), both as JSON values of the shapeop_contract_jsonprints. - client_
contract_ digest - A build identity for the client-facing contract: a hash over the sorted
[key, hex(op digest)]table. It moves when any op’s contract moves, a new op appears or one disappears. - coalesce
- Build a
COALESCE(...)left-hand operand. The returnedCoalesceExprcarries the column list; chain a comparator method (.lte,.eq,.is_null, …) to produce aFilterExprthe query builders can consume. - computed_
params_ type_ name - The params type name off a field’s
@computed(params: <Type>?)attribute, orNonefor a bare@computedfield (or a field with no@computedattribute at all). Assumes the attribute is already well-formed — per-declaration validation (e.g.cratestack-parser’svalidate_computed_field_attribute) must run first and reject anything else. Callers that still need to validate the argument form should parse the raw attribute text withparse_computed_params_arginstead. - cratestack_
error_ from_ sqlx - Convert a
sqlx::ErrortoCratestackError, preserving structured database error information when available. - create_
record_ with_ executor - Passing a pool as
policy_poolwhileexecutoris a transaction takes a second connection; prefer the builder’srun_in_tx. - cursor_
scalar - Render one ordering-column value as its cursor wire string through
serde (
DateTime→ RFC 3339,Uuid→ hyphenated, numbers → decimal).Nonefor SQLNULL. Arrays/objects are not orderable scalars. - decode_
codec_ request - decode_
cursor - Decode and validate a cursor against the order the request resolved
to. Every failure is a
CratestackError::BadRequest(RPCinvalid_argument): oversized, not base64url/JSON, minted for a different order, or carrying the wrong number of values. - decode_
transport_ request_ for - deserialize_
bytes - A required
Bytesfield —Vec<u8>. - deserialize_
bytes_ list - A list-arity
Bytesfield —Vec<Vec<u8>>. Each element independently accepts either shape. - deserialize_
double_ option - Deserializes
Option<Option<T>>distinguishing “key absent” from “key present with valuenull”. Pair with#[serde(default, ...)]— see the module doc for whydefaultis required once a field opts into a customdeserialize_with. - deserialize_
double_ option_ bytes - A patch-wrapped nullable
Bytesfield —Option<Option<Vec<u8>>>. TheBytescounterpart ofcrate::patch::deserialize_double_option(which can’t be reused: itsT: Deserializebound resolves toVec<u8>’s strict blanket impl, the exact thing this module works around). Same contract — the outerSomerecords “this key was present”, so it must be paired with#[serde(default, …)]. - deserialize_
optional_ bytes - A nullable
Bytesfield, or a patch-wrapped required one —Option<Vec<u8>>. Pair with#[serde(default, …)]: a customdeserialize_withopts the field out of serde-derive’s implicit “missingOption<T>field defaults toNone” (seecrate::patch). - deserialize_
optional_ bytes_ list - A patch-wrapped list-arity
Bytesfield —Option<Vec<Vec<u8>>>. Pair with#[serde(default, …)], perdeserialize_optional_bytes. - detail_
route_ of - The detail route of the collection route
list_route, for a caller that holds the route and not the model name. - digest_
hex - Lowercase hex of a digest.
- encode_
codec_ response - encode_
codec_ result - encode_
codec_ result_ with_ status - encode_
cursor - Mint a cursor for
order(the canonical effective sort, e.g."-createdAt,id") from the last row’s per-column wire values;Noneis SQLNULL. - encode_
transport_ result - encode_
transport_ result_ with_ status - encode_
transport_ result_ with_ status_ for - encode_
transport_ sequence_ result - encode_
transport_ sequence_ result_ with_ status - encode_
transport_ sequence_ result_ with_ status_ for - encode_
transport_ stream_ result_ with_ status_ for - Genuinely incremental counterpart to
encode_transport_sequence_result_with_status_forfor@streamprocedures (cratestack#283):resultcarries the still-unconsumed itemStreamrather than an already-collectedVec.Errhere means a preflight failure (authorization, before anything was produced) — the ordinary buffered error path applies, since nothing has streamed to the client yet. A failure during the stream is a different thing entirely and never reaches this function as anErr: it’s absorbed into the item stream itself as the tag-48900 sentinel (seesuper::stream_sequence). - enrich_
context_ from_ envelope - Record the
VerifiedSignerthe envelope layer left inextensions, if any, onctx.extensionsis the request’s (generated handlers passClientIpContext::extensions, a clone of them). - enrich_
context_ from_ headers - Enrich a
CratestackContextwith the request id (fromtraceparent) and the client IP recorded on audit events. Malformedtraceparentheaders are silently ignored here — the auth/header-validation layer is the right place to reject them, not the enrichment seam. - ensure_
migrations_ table - event_
topic - field_
attribute_ name - The bare name of a field-level attribute, with the
@sigil and any(...)argument list removed:@length(min: 1)->Some("length").Nonefor model-level@@...text or text without the sigil. - find_
contract - The row a call belongs to: an RPC route is its
op_id(orbatch); a REST route is bound as the template, and keyed"<METHOD> <template>". No allocation: an RPC id never starts with a method and a space. AHEADis theGETop’s (axum serves it from that route; the binding still names the method it was sent with). - find_
duplicate_ position - Detect duplicate keys in a batch input, loud-failing the whole request when found. Returns the first duplicate (by position) so the surfaced error can name a specific offending index. Linear- time, allocation-only in proportion to the input length.
- first_
success - Starts a first-success chain with
first; add members withFirstSuccess::or. See the module documentation. - geometry_
subtype_ names - Every accepted subtype spelling, for building “expected one of: …” diagnostics. Ordered base-major so the common 2D names lead.
- install_
fips_ crypto_ provider - Crypto provider selection for FIPS-validated deployments.
- is_
computed_ attribute - True when a single attribute’s raw text is either spelling of
@computed— bare@computedor the parameterized@computed(...)form (whatever its argument, valid or not; argument-shape validation is a separate concern — seecratestack-parser’svalidate_computed_field_attribute). Anchored withstarts_with("@computed(")rather than the looserstarts_with("@computed")deliberately: the latter would also match a hypothetical unrelated attribute merely prefixed with the same characters (e.g.@computedSomethingElse). - is_
computed_ field - True for a field carrying either spelling of
@computed— bare or@computed(params: <Type>?). Seeis_computed_attributefor why this must be the only place the string comparison is written. - is_
orderable - Whether every hop is to-one. Ordering through a to-many hop is not
expressible as a scalar correlated subquery, so generated
asc()/desc()accessors are gated on this (previously enforced by simply not emitting those methods past a to-many hop). - is_
primary_ key_ attribute - Whether
attributemarks its field as the primary key. Exact match onPRIMARY_KEY_ATTRIBUTE:@identity,@idxand@id_fooare other (unknown) attributes, not a primary key. - is_
relation_ attribute - Whether
attributeis a@relation/@relation(...)declaration — by name, so a bare@relationcounts too.@relationshipdoes not. - is_
sealable_ payload_ type - Whether
media_typemay be the type of a sealed payload: the grammar above, and not an envelope in an envelope (application/cose*), a stream that cannot be sealed until ADR 0006 P1 (application/cbor-seq,text/event-stream) or a multipart body. - keyset_
after - Filter selecting the rows strictly after the row whose per-column
values are
values(None=NULL), expanded asOR_i (c_0 = v_0 AND … AND c_{i-1} = v_{i-1} AND c_i AFTER v_i). WithNULLS LAST, a non-nullv_ion a nullable column is also followed by everyNULL; aNULLv_ihas nothing after it in that column (only ties, handled by the next term).leafbuilds the typed comparison — the caller owns value parsing, so a bad value fails here exactly as the same value in a?col__gt=filter would. - keyset_
order_ spec - Canonical effective-order string (
"-createdAt,id") a cursor is bound to. - model_
detail_ route - The detail route of a model on REST:
/widgets/{id}. - model_
event_ channel - The backplane channel model events of
modelare published on. - model_
internal_ actions - The single shared source of truth every surface consults exactly
once: the set of wire verbs (
"list","get","create","update","delete") a model’s@@internal(...)attributes suppress. Assumes every attribute already parsed successfully viaparse_internal_attribute— per-declaration validation (cratestack-parser’svalidate_internal_attribute) must run first and reject anything else, mirroringcomputed_params_type_name’s same assume-validated contract. Malformed or unrecognized attributes are silently skipped here rather than panicking: a caller reaching this function after a failed parse would already have surfaced the error at schema validation time, and this function must stay infallible so every codegen surface can call it without threading aResultthrough unrelated emission code. - model_
list_ route - The collection route of a model on REST:
/widgets. - model_
op_ key - The op key of a model verb: the RPC op id, or
"<METHOD> <route>"on REST.Nonefor a verb REST does not have. - model_
subscribe_ route - The subscription route of a model on REST:
/widgets/$subscribe. - model_
verbs - The verbs
modelexposes, inModelVerb::CRUDorder withSubscribelast: every CRUD verb@@internaldoes not suppress, plusSubscribefor an@@subscribemodel. - op_
contract_ digest - The digest of the op
key(an RPCop_id, or"<METHOD> <route>"on REST), orNonewhen the schema exposes no such op. - op_
contract_ digests - Every op’s digest, sorted by key.
- op_
contract_ json - The canonical JSON an op digest hashes (what
cratestack contract printshows), orNonewhen the schema exposes no op with that key. - op_keys
- The key of every op
schemaexposes, sorted: the keys the generated routers and clients expose, asserted equal to the macro’sOPS/ROUTE_TRANSPORTSby the parity test. - order_
value_ sql - Build the correlated-subquery expression that yields
columnat the end ofhops, relative to the table reached by the first hop. - parse_
client_ ip - Extract the client IP
max_hopsentries in from the right end of whichever single headerheaderselects — never both. Falls back toNoneif that header is absent, empty, or the walk runs off the end of the chain. - parse_
composite_ id_ attribute - Parses
@@id([field1, field2, ...])into its ordered list of local field names. Callers are responsible for checking that each name resolves to a real scalar field on the model. - parse_
composite_ unique_ attribute - Parses
@@unique([field1, field2, ...], where: "...")into its ordered list of local field names plus an optional partial-index predicate. Callers are responsible for checking that each name resolves to a real scalar field on the model. - parse_
computed_ params_ arg - Parses the text between (but not including) the parens of a
@computed(...)attribute into its recognized shape. Whitespace-tolerant around the:and before the trailing?. - parse_
computed_ params_ object - Decodes the raw
?computedParams=query value (already percent-decoded bysuper::parse_query_pairs) into a{ fieldName: paramsJson }map. Shared, schema-independent JSON-shape validation — “is this even a JSON object” — lives here once rather than being re-emitted per model by the macro; per-model concerns (which keys are legal for this model, does the referenced field have a params type, is it excluded by?fields=) stay in generated code, which is the only place that field list is known. Seedocs/design/computed-fields.md’s “Parameterized resolvers on the wire” section. - parse_
cuid - parse_
emit_ attribute - parse_
filter_ expression - parse_
if_ match_ version - Parse an
If-Matchheader carrying a strong ETag of the form"<int>". ReturnsNoneif the header is absent. Returns an error if the header is present but malformed (weak validators, non-integer payloads, etc.). - parse_
index_ attribute - Parses
@@index([field1, field2, ...]), optionally followed byusing: <method>,opclass: "<name>", and/orwhere: "<predicate>". Callers are responsible for checking that each field name resolves to a real scalar field on the model. - parse_
internal_ attribute - Parses one
@@internal("action")attribute’s action name and validates it againstINTERNAL_ACTIONS. ReturnsErrnaming the model and the bad action for anything else — the compile-error case the design’s acceptance criteria requires (“@@internalnaming an action that is not a valid action verb ⇒ compile error naming the model and the bad action”). - parse_
keyset_ sort - Resolve
sort("-createdAt,name";None= unsorted) into keyset columns, appendingprimary_keyascending when absent so the order is total.nullable_ofreturnsSome(is_nullable)for a sortable scalar column andNonefor anything else. Relation-path (a.b) terms, unknown or duplicate columns and empty terms areBadRequest. - parse_
payload_ accept - Parse a received
PAYLOAD_ACCEPT_HEADERvalue, strictly: the sender’s order is kept, entries are separated by exactly", ", and a repeated entry is refused so the list has one spelling. - parse_
payload_ type - Parse a received
PAYLOAD_TYPE_HEADERvalue, strictly. - parse_
query_ pairs - parse_
schema - parse_
schema_ file - Loads the schema at
path, including theparts it lists and the files itimports (seecrate::load_schema). - parse_
schema_ named - parse_
traceparent - Extract a W3C
traceparentheader, returning the trace-id portion when the header is present and well-formed. ReturnsOk(None)when absent — callers should mint their own request id in that case so every audit row carries something. The trace-id is the second hyphen-delimited segment per W3C Trace Context; this implementation does not validate the flags/version segments since banks usually rebuild traceparent at the edge anyway. - payload_
accept_ header_ value - The
PAYLOAD_ACCEPT_HEADERvalue fortypes, the wayparse_payload_acceptreads it back. - procedure_
op_ key - The op key of a procedure:
procedure.<name>on RPC,POST <path>on REST (the path carries@api_version). - request_
digest - The request digest a response binding carries when the request was
signed: SHA-256 over the request body exactly as it travelled, the
whole COSE message (tag, headers, signature and all), marked
RequestKind::Signed. The caller passes the received body, never a re-encoding of it. - request_
digest_ unsigned - The request digest of a response to an unsigned request: SHA-256
over the 16 nonce bytes followed by the request payload exactly as
received (empty for a bodiless request), marked
RequestKind::Unsigned. The nonce has a fixed length, so the split between the two is unambiguous. - require_
authn Okwhen there is no requirement orctxmeets it now, otherwise the step-up refusal. The generated code calls it with the operation’sAUTHN,Nonefor an operation without one.- require_
authn_ at require_authnfor one requirement at a given time, for tests and callers with their own clock.- resolve_
order_ target - Walk
key(dot-separated, e.g."author.profile.nickname") throughcatalog, following to-one relation edges one segment at a time and resolving the final segment against the current model’s scalar columns. - run_
in_ isolated_ tx - Begin a transaction at the requested isolation level, run
bodyagainst the live transaction, and commit. On40001(serialization_failure) or40P01(deadlock_detected) the transaction is rolled back and the body runs again, up toMAX_RETRIES_DEFAULTtimes. Other errors propagate immediately. Only a database error is retried: an errorbodybuilds itself (Validation,Internal, …) is returned as is even when its text contains40001ordeadlock detected, and a typed database error is retried by its SQLSTATE alone, never by its text. - run_
in_ isolated_ tx_ with_ retries - Same as
run_in_isolated_txbut with a caller-chosen retry budget. Banks running long-tail contended writes sometimes want a higher cap (5–10); single-row CAS workflows can drop to 1 to fail fast. - scan_
sql_ placeholders - Every distinct
Nin a$Ntoken appearing insqlas an actual parameter reference, ascending. - schema_
digest - The canonical identity of
schema, as raw SHA-256 bytes. - schema_
digest_ hex schema_digestas 64 lowercase hex digits (theSCHEMA_SHA256string).- scope_
ttl_ secs - How long a scope’s admission record must live: at least as long as the buckets it admitted, and at least the caller’s requested floor.
- set_
version_ etag - Insert an
ETagheader onto a response, formatted as a strong validator over the integer optimistic-locking version. - status
- Inspect each migration in
migrationsagainstcratestack_migrationsand report which are pending / applied / drifted. Use beforeapplyto surface drift to the operator without changing state. - subscription_
procedure_ op_ key - The op key of a
subscription procedure(slice S4):procedure.<name>on RPC, as a unary procedure;GET <path>on REST, its stream served over SSE at the path a unary procedure wouldPOSTto. - topic_
channel - The backplane channel of
topic’s messages underkey(topic RoomMessage(roomId: String): ChatMessage, slice S4):cratestack.topic.RoomMessage.<key>. - update_
record_ with_ executor - Passing a pool as
policy_poolwhileexecutoris a transaction takes a second connection; prefer the builder’srun_in_tx. - validate_
codec_ request_ headers - validate_
codec_ response_ headers - validate_
email - Pragmatic email check: requires exactly one
@, non-empty local and domain parts, at least one.in the domain, and no whitespace. Not a full RFC 5322 grammar — that grammar admits forms (quoted local parts, IP literals) banks rarely accept anyway. Reject early; let real KYC flows do deeper validation. - validate_
iso4217 - ISO 4217 currency codes are 3 ASCII uppercase letters. We do not enforce the registered set here — that table churns and is downstream policy. Banks typically pin allowed currencies via a separate allow-list anyway.
- validate_
length - validate_
length_ bytes @lengthon aBytesfield (cratestack#572).Bytesgenerates asVec<u8>, which has no character encoding to count against, so “length” here is unambiguously the byte count – unlikevalidate_length, which countschars (Unicode scalar values, not UTF-8 code units) becauseStringgenuinely has more than one plausible notion of “length”. AVec<u8>doesn’t have that ambiguity, which is why this is a separate function dispatched by scalar type (cratestack-macros/src/validators/emit.rs::emit_length) rather than a shared generic: fixed-width digest/hash columns are the motivating use case (digest Bytes @length(min: 32, max: 32)).- validate_
range_ decimal - Decimal-typed
@rangeenforcement. The parser accepts integer bounds (@range(min: 0, max: 100)) on both Int and Decimal fields; the i64 bounds are promoted to Decimal here so monetary fields can declare the same shape as integer counters. Banks routinely write things likeamount Decimal @range(min: 0)to forbid negative amounts at the framework layer — without this, the validator silently no-ops and out-of-range values reach the database. - validate_
range_ i64 - validate_
transport_ request_ headers - validate_
transport_ request_ headers_ for - validate_
transport_ response_ headers - validate_
transport_ response_ headers_ for - validate_
uri - wrap_
filter - Fold a scalar
FilterExproutward through the traversed path, applying each hop’s quantifier and carrying each hop’s read scope onto the relation node it becomes.
Type Aliases§
- Accepted
Contracts - What a server accepts: per op (and
batch), the digests a request may bind, current first, then older compatible ones newest first. - Backplane
Future - A boxed future, so the trait stays object-safe (
Arc<dyn SubscriptionBackplane>). - Backplane
Receiver - What
SubscriptionBackplane::subscribereturns: everything published on the channel from the moment the subscription is established. - Cratestack
Body - Body bytes carried through the transport layer.
- Cratestack
Event Future - Decimal
- Legacy single-backend alias, kept for hand-written call sites outside generated code. Only exists when exactly one backend feature is active — see this module’s doc for why “both” doesn’t pick a default instead of simply not exporting this name.
- OpContracts
- What a client stamps: one digest per op (and
batch), emitted in key order for a stable diff. Lookup (find_contract) is a linear scan: nothing relies on the order. - Subscription
Stream - A live subscription’s items. Ending (
None) means the subscription is over; anErritem is terminal too — the binding sends it and stops.