Skip to main content

Crate cratestack

Crate cratestack 

Source
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.
axum
axum is an HTTP routing and request-handling library that focuses on ergonomics and modularity.
batch
Batch envelope.
builder
Type-level markers for the generated typestate builders.
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 AuthProvider trait that auth middlewares implement.
decimal
Decimal scalar(s).
envelope
Signed envelope (HMAC-SHA-256).
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/deleted envelopes that procedure handlers can subscribe to.
find_many
Built-in support for the FindMany<Model> procedure-argument type (.cstack syntax) — search-with-filters for procedures. Composes with PageInput rather 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 traceparent extraction, RFC 7239 Forwarded/ X-Forwarded-For client-IP extraction (honored only from a configured crate::trusted_proxy::TrustedProxyConfig — see enrich_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 Json columns need a model-struct field type that’s the same on every backend so the same struct compiles on server and on embedded (including wasm32-unknown-unknown, which can’t depend on sqlx).
lenient_bytes
Wire-shape-tolerant deserialization for schema Bytes fields — 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 — see docs/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).
page
Generic paginated-page envelope used by every list route. 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 .cstack source 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 for Update{Model}Input fields that back a nullable column — see cratestack#567.
query
Query-string parsing for axum-bound handlers: percent-decoded pair extraction and the structured filter expression grammar (?where=...) used by macro-generated list endpoints.
ratelimit
Per-principal rate limiting.
route_naming
Canonical REST route-segment derivation for a model name.
rpc
Runtime primitives for the transport rpc generation style.
rust_keywords
Rust keyword classification, shared by cratestack-parser (schema-time field-name validation) and cratestack-macros (identifier escaping at codegen time) so the two stay in sync — see cratestack#398.
schema
Schema IR — the parsed shape of a .cstack file. 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-sha header (issue #178). Every generated client stamps its own SCHEMA_SHA256 constant (SHA-256 of the .cstack source it was compiled against) onto every request; this middleware compares that value against the server’s own constant and tracing::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/rpc alike), since nothing about schema drift is transport-specific.
sqlx
Compatibility shim that exposes a sqlx-shaped API by re-exporting from sqlx-core + sqlx-postgres directly.
store
Pluggable storage traits for idempotency, rate limiting, and client state, shared between transport and backend-runtime crates.
trusted_proxy
Trusted-proxy configuration for the audit client_ip (#415): TrustedProxyConfig plus 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 and crate::headers::enrich_context_from_headers for where the two are combined). See docs/design/trusted-proxy-client-ip.md for 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 (via sqlite-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, Cratestack runtime, axum router, procedures, events. Pass db = Postgres (only value currently supported; MySQL / SQLite-via-sqlx will land in a future release).

Structs§

Aggregate
AggregateColumn
AggregateCount
Attribute
AuditActor
AuditEvent
AuthBlock
BatchItemError
Public, safe-to-expose shape of a per-item failure. Mirrors crate::CratestackErrorResponse without the optional details field — batch callers asking for per-item detail can repeat the operation singly against the failed item to get the full error envelope.
BatchItemResult
Per-item result inside a BatchResponse. The index is the item’s position in the original request, so clients can pair results with inputs even after server-side reordering (e.g. parallel batch_get fetches in the future).
BatchRequest
Wire envelope for POST /<model>/batch-* request bodies. Holds the items in a single field so the envelope can grow (e.g. a future client_request_id) without breaking deserialization.
BatchResponse
Wire envelope returned by every batch route. Always 200 OK at the HTTP layer; inspect summary.err (or scan results) to surface per-item failures to the user.
BatchSummary
Summary counts attached to every BatchResponse so callers can branch on aggregate status without scanning the result list.
BoundedOutcome
What super::RateLimitStore::consume_bounded returns: the ordinary decision, plus which bucket produced it.
BucketBudget
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.
CachedAuthProvider
An AuthProvider that always returns a single, already-established CratestackContext, ignoring whatever RequestContext it is asked to authenticate.
ClientIpContext
The trusted-proxy configuration (if an Extension<TrustedProxyConfig> was applied to the router), the verified socket peer (if the router is served via into_make_service_with_connect_info), and a clone of the request’s full http::Extensions map, bundled into a single axum extractor so every generated dispatch fn threads one new parameter instead of several (#415).
CoalesceExpr
Left-hand operand of a coalesce-based filter — chain a comparator method to turn it into a FilterExpr.
CoalesceFilter
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 usual FilterValue envelope. 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.
CodecSet
ConfigBlock
ConfigEntry
ConsumeRequest
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.
CratestackAuthIdentity
CratestackContext
CratestackErrorResponse
CratestackEventBus
CratestackEventEnvelope
CreateDefault
CreateRecord
Datasource
DbErrorInfo
Structured information extracted from a driver-level database error.
DeleteMany
DeleteRecord
EnumDecl
EnumVariant
Field
FieldFilterInput
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 Boolean field’s generated to_filters() never looks at contains). V is the field’s own scalar Rust type (String, i64, bool, chrono::DateTime<Utc>, …) — never Option<V> even for an optional field, since these operators describe a value to compare against, not the field’s own nullability (which is_null covers instead).
FieldRef
Filter
FindMany
FindManyWith
FindUnique
HmacEnvelope
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.
IdempotencyRecord
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.
InMemoryNonceStore
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.
InMemoryStateStore
Json
Wrapper for a schema-declared Json column’s Rust field type. See the module docs for why this exists instead of sqlx::types::Json<Value>.
JsonFileStateStore
JsonTextPath
Left-hand operand of a json_get_text filter — chain a comparison method (.eq, .lt, .is_null, …) to produce a FilterExpr.
LenientBytes
Vec<u8> newtype whose Deserialize accepts a byte string or a sequence of integers. See the module docs.
Migration
A single migration step. The runner applies any rows not yet present in cratestack_migrations. down is recorded but never called — irreversible-by-default is the safe banking posture.
MigrationState
MixinDecl
Model
ModelColumn
ModelDelegate
ModelDescriptor
ModelEvent
MulticastAuditSink
Fan an audit event out to multiple sinks. Errors from any individual sink are aggregated into CratestackError::Internal so a single failing downstream does not silently swallow problems with the others.
NoEnvelope
Pass-through envelope used when transport-layer signing is not required.
NoopAuditSink
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 rpc schema. See docs/design/rpc-transport.md for 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 one OpDescriptor per CRUD verb and per procedure when Schema.transport == TransportStyle::Rpc.
OrderCatalog
One model’s order-by surface: its own sortable scalar columns ((api_name, sql_column)) and its own to-one relation edges. Exactly one OrderCatalog is emitted per model, regardless of how many distinct relation paths pass through it.
OrderClause
OrderRelationEdge
One to-one relation edge out of a model. target points at the related model’s own catalog so resolve_order_target can 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.
OwnedSchemaSummary
Page
PageInfo
PageInput
Built-in pagination-input argument type (PageInput in .cstack), currently valid only as a procedure argument — the request-side mirror of Page/PageInfo on the response side. Field names and optionality match PageInfo’s own limit/offset exactly, so a generated list route and a hand-written PageInput-accepting procedure decode the same wire shape.
ParsedCompositeUnique
The parsed shape of an @@unique([...], where: "...") attribute.
ParsedIndexAttribute
The parsed shape of an @@index([...], using: ..., opclass: "...", where: "...") attribute.
PersistedClientState
PrincipalContext
PrincipalFacet
Procedure
ProcedureArg
ProcedurePolicy
ProjectedFindMany
ProjectedFindUnique
Projection
Result of a .select(...)-projected read. Holds the model with only the selected columns populated — non-selected fields carry their type’s Default::default() value ("" for String, 0 for integers, None for Option<T>, etc.).
Query
RateLimitConfig
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.
ReadPolicy
RelationFilter
RelationHop
One traversed relation edge: the FK linkage plus how the related rows are quantified (ToOne for a plain to-one hop, Some/Every/None for a to-many hop under a quantifier).
RelationInclude
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.
RequestContext
Everything an AuthProvider gets to see about an inbound request.
RequestJournalEntry
ResolvedOrderTarget
A dotted sort key resolved down to the relation hops to traverse plus the terminal scalar column, ready for crate::order_value_sql.
RouteTransportCapabilities
Wire-level capabilities for one route under a REST binding.
RouteTransportDescriptor
RunInTxOutcome
See the module doc comment.
RustDecimal
Decimal represents a 128 bit representation of a fixed-precision decimal number. The finite set of values of type Decimal are 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
SchemaError
A schema error, identified by which file it came from (cratestack#916).
SchemaSummary
ScopedAggregate
ScopedAggregateColumn
ScopedAggregateCount
ScopedCreateRecord
ScopedDeleteMany
ScopedDeleteRecord
ScopedFindMany
ScopedFindManyWith
ScopedFindUnique
ScopedModelDelegate
ScopedProjectedFindMany
ScopedProjectedFindUnique
ScopedUpdateMany
ScopedUpdateManySet
ScopedUpdateRecord
ScopedUpdateRecordSet
ScopedUpsertRecord
ScopedUpsertRecordDoNothing
.upsert(..).do_nothing() bound to a CratestackContext via .bind(ctx). See UpsertRecordDoNothing for the run-time semantics; this is purely a ctx-carrying wrapper, same relationship as ScopedUpsertRecord has to UpsertRecord.
SealedEnvelope
SelectionQuery
SourceSpan
SqlColumnValue
SqlxIdempotencyStore
StaticKeyProvider
In-memory KeyProvider for tests and single-tenant deployments. Banks running real workloads bring a backed implementation (KMS, Vault, HSM).
SubscriptionGuard
RAII cleanup for one or more CratestackEventBus subscriptions that all share one lifecycle — e.g. the per-operation handlers a single GET /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.
SubscriptionHandle
Opaque token returned by CratestackEventBus::subscribe, needed to later remove that exact handler via CratestackEventBus::unsubscribe. Fields are private — the only way to obtain one is subscribe, and the only thing it’s good for is passing back to unsubscribe.
SystemContext
A context representing trusted in-process/server code (a procedure, a worker, a reconciliation job) rather than an end user.
TrustedProxyConfig
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.
TypeDecl
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.
UpdateMany
UpdateManySet
UpdateRecord
UpdateRecordSet
UpsertRecord
UpsertRecordDoNothing
VectorDistanceExpr
Builder returned by FieldRef::distance_to — chain a comparator (.lt/.lte/.gt/.gte/.eq) for a threshold filter, or .asc/ .desc to use it as an ORDER BY target. The common k-NN “closest first” case is .asc(); see also FieldRef::order_by_distance, sugar for exactly that.
VectorDistanceFilter
<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]’s FieldRef::distance_to, then a comparator method turns it into a FilterExpr. Mirrors super::CoalesceFilter’s shape: a left-hand computed expression plus a bound right-hand value.
View
ViewDelegate
View delegate for views that declared an @id field. Exposes find_many + find_unique (and refresh() on materialized views). Views declared @@no_unique get ViewDelegateNoUnique instead, which omits find_unique at the type level so a call like runtime.views().<v>().find_unique(()) is a compile error rather than a runtime “WHERE = $1” footgun.
ViewDelegateNoUnique
View delegate for views declared @@no_unique. Exposes only find_manyfind_unique and refresh() are absent at the type level because:
ViewDescriptor
ViewSource

Enums§

AuditOperation
BatchItemStatus
Either a successful per-item outcome (Ok) or a per-item failure (Error). Serializes as a tagged enum with the discriminant in status:
Charged
Which bucket a super::RateLimitStore::consume_bounded call ended up charging, and why. Purely observational — the decision itself is carried by BoundedOutcome::decision — but it is what lets the middleware log an in-progress amplification attempt instead of silently absorbing it.
ComputedParamsArg
The parenthesized argument of a @computed(...) attribute, however it parses.
ConflictTarget
Conflict target for an upsert. Defaults to the model’s primary key (matching the previous PK-only behavior). Self::Columns / Self::columns let 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).
CratestackError
CreateDefaultType
ExtensionKind
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, the Vector(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).
FilterExpr
FilterOp
ForwardedHeader
Which single forwarding header a trusted proxy is expected to write.
JsonFilter
JSON / JSONB filter predicates. Two flavors:
MigrationStatus
ModelEventKind
NullOrder
Where NULLs sort relative to non-NULL values. PostgreSQL’s default is NULLS LAST for ASC and NULLS FIRST for DESC; SQLite’s default is NULLS FIRST for both. CrateStack pins the framework default to NULLS LAST so listings stay deterministic across backends and so soft-deleted rows (typed Option<DateTime> that surface as None for visible rows) don’t muscle their way to the top of every listing. Override per-clause via OrderClause::nulls_first when scheduler / outbox queries want fresh-as-null tasks at the head of the queue.
OpKind
OrderTarget
PolicyExpr
PolicyLiteral
ProcedureKind
ProcedurePolicyExpr
ProcedurePolicyLiteral
ProcedurePredicate
ProjectedValue
One projected model field, or a nested included relation. See the module doc for why this replaces serde_json::Value on the projection path.
QueryExpr
RateLimitDecision
Result of attempting to consume a token. Allowed carries the number of tokens left after consumption; Throttled carries seconds the caller should wait before retrying.
ReadPredicate
RelationQuantifier
ReservationOutcome
Outcome of an atomic reserve_or_fetch call.
SortDirection
SqlValue
TransactionIsolation
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 pick Serializable and pair it with retry-on-serialization-failure.
TransportStyle
Wire-shape the schema generates for. Picked once per schema (via the top-level transport rest|rpc directive) so generated servers and clients only carry one binding’s worth of surface.
TypeArity
UpsertOutcome
Outcome of a .upsert(..).do_nothing().run(..) call.
Value
Serialize/Deserialize are 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 (Null via serialize_none, Bytes branching on is_human_readable) and why each is load-bearing.
VectorMetric
Distance metric for a Vector(n) similarity search (see docs/design/extensions.md §6/§7, cratestack#163). Maps 1:1 onto pgvector’s three distance operators and the opclass names 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_opclass is 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.

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::SqlxRuntime] can idempotently ensure the table exists during bootstrap.
BATCH_MAX_ITEMS
Default upper bound on items in a single batch request. Server backends enforce this before any SQL runs and surface CratestackError::Validation on the outer Result when exceeded. The cap is identical for all five batch operations; deviating per-op would invite footguns where batch_get accepts a list that batch_create of the same length rejects.
CBOR_SEQUENCE_CONTENT_TYPE
DEFAULT_BODY_LIMIT_BYTES
Default request body limit (bytes) for the generated router() / rpc_router() entry points, applied via axum::extract::DefaultBodyLimit::max(body_limit_bytes).
INTERNAL_ACTIONS
Action names @@internal(...) accepts — identical to @@allow’s vocabulary (list/detail/read/create/update/delete/ all; see cratestack-macros/src/policy/model.rs’s parse_rule_action and model/descriptor.rs’s action groupings) so an author never has to learn a second action vocabulary to suppress what @@allow already describes.
MAX_LIST_LIMIT
Hard ceiling on the limit query parameter (REST) / RPC list-input field every generated list route accepts, regardless of whether the model is @@paged. Requests above this are rejected with a 400, the same way negative limit/offset already are — see handle_list_<plural>_dispatch in the generated code, shared byte-for-byte between REST and RPC dispatch.
MAX_RESPONSE_REBUFFER_BYTES
Bound used at every axum::body::to_bytes(body, N) call site that re-buffers a Response produced in-process (RPC batch per-frame re-encoding, handler-error re-shaping, and the per-frame codec round-trip helper — see crates/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 way DEFAULT_BODY_LIMIT_BYTES is.
MAX_TTL_SECS
Ceiling on any store-side TTL, in seconds: one year.
MIGRATIONS_TABLE_DDL
QUERY_SQL_ATTRIBUTE
The attribute a query block’s SQL body is written in.

Traits§

AuditSink
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_sqlx remains the canonical record; sinks are best-effort projections.
AuthProvider
Resolves the caller of a request into a CratestackContext.
ClientStateStore
CratestackCodec
CratestackEnvelope
CreateModelInput
DecimalValue
Backend-agnostic bound for a decimal scalar. Blanket-implemented for any type satisfying these bounds — deliberately structural rather than naming rust_decimal::Decimal / bigdecimal::BigDecimal explicitly, 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.
FromPartialPgRow
Companion to sqlx::FromRow that decodes a row projected by .select(...) — i.e. a row where only the named columns are present in the SQL SELECT list. Non-selected fields populate to their type’s Default::default() value.
HttpTransport
IdempotencyStore
IntoColumnName
Anything that can name a single SQL column. Lets coalesce accept both bare &'static str column names and typed FieldRef handles, so callers don’t have to choose between schema-rooted typing and ad-hoc strings at the call site.
IntoSqlValue
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.
ModelPrimaryKey
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 BatchItemResult with the right index and a NotFound entry for any requested PK that didn’t come back.
NonceStore
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.
ProcedureArgs
ProjectionDecoder
RateLimitStore
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).
ReadSource
Anything a read-path query builder needs to plan and emit SQL.
UpdateModelInput
UpsertModelInput
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), and primary_key_value() exposes the PK separately so the runtime can issue a SELECT … FOR UPDATE before the upsert to drive Created vs. Updated event / audit semantics.
WriteSource
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_pre then Migration::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_policies refuses everyone.
authorize_query
authorize_procedure for a query block (cratestack#867).
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 None if it isn’t a recognised subtype.
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.
coalesce
Build a COALESCE(...) left-hand operand. The returned CoalesceExpr carries the column list; chain a comparator method (.lte, .eq, .is_null, …) to produce a FilterExpr the query builders can consume.
computed_params_type_name
The params type name off a field’s @computed(params: <Type>?) attribute, or None for a bare @computed field (or a field with no @computed attribute at all). Assumes the attribute is already well-formed — per-declaration validation (e.g. cratestack-parser’s validate_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 with parse_computed_params_arg instead.
cratestack_error_from_sqlx
Convert a sqlx::Error to CratestackError, preserving structured database error information when available.
create_record_with_executor
decode_codec_request
decode_transport_request_for
deserialize_bytes
A required Bytes field — Vec<u8>.
deserialize_bytes_list
A list-arity Bytes field — Vec<Vec<u8>>. Each element independently accepts either shape.
deserialize_double_option
Deserializes Option<Option<T>> distinguishing “key absent” from “key present with value null”. Pair with #[serde(default, ...)] — see the module doc for why default is required once a field opts into a custom deserialize_with.
deserialize_double_option_bytes
A patch-wrapped nullable Bytes field — Option<Option<Vec<u8>>>. The Bytes counterpart of crate::patch::deserialize_double_option (which can’t be reused: its T: Deserialize bound resolves to Vec<u8>’s strict blanket impl, the exact thing this module works around). Same contract — the outer Some records “this key was present”, so it must be paired with #[serde(default, …)].
deserialize_optional_bytes
A nullable Bytes field, or a patch-wrapped required one — Option<Vec<u8>>. Pair with #[serde(default, …)]: a custom deserialize_with opts the field out of serde-derive’s implicit “missing Option<T> field defaults to None” (see crate::patch).
deserialize_optional_bytes_list
A patch-wrapped list-arity Bytes field — Option<Vec<Vec<u8>>>. Pair with #[serde(default, …)], per deserialize_optional_bytes.
encode_codec_response
encode_codec_result
encode_codec_result_with_status
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_for for @stream procedures (cratestack#283): result carries the still-unconsumed item Stream rather than an already-collected Vec. Err here 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 an Err: it’s absorbed into the item stream itself as the tag-48900 sentinel (see super::stream_sequence).
enrich_context_from_headers
Enrich a CratestackContext with the request id (from traceparent) and the client IP recorded on audit events. Malformed traceparent headers 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
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.
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 @computed or the parameterized @computed(...) form (whatever its argument, valid or not; argument-shape validation is a separate concern — see cratestack-parser’s validate_computed_field_attribute). Anchored with starts_with("@computed(") rather than the looser starts_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>?). See is_computed_attribute for 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).
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 via parse_internal_attribute — per-declaration validation (cratestack-parser’s validate_internal_attribute) must run first and reject anything else, mirroring computed_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 a Result through unrelated emission code.
order_value_sql
Build the correlated-subquery expression that yields column at the end of hops, relative to the table reached by the first hop.
parse_client_ip
Extract the client IP max_hops entries in from the right end of whichever single header header selects — never both. Falls back to None if 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 by super::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. See docs/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-Match header carrying a strong ETag of the form "<int>". Returns None if 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 by using: <method>, opclass: "<name>", and/or where: "<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 against INTERNAL_ACTIONS. Returns Err naming the model and the bad action for anything else — the compile-error case the design’s acceptance criteria requires (“@@internal naming an action that is not a valid action verb ⇒ compile error naming the model and the bad action”).
parse_query_pairs
parse_schema
parse_schema_file
parse_schema_named
parse_traceparent
Extract a W3C traceparent header, returning the trace-id portion when the header is present and well-formed. Returns Ok(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.
resolve_order_target
Walk key (dot-separated, e.g. "author.profile.nickname") through catalog, 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 body against the live transaction, and commit. On 40001 (serialization_failure) or 40P01 (deadlock_detected) the transaction is rolled back and the body runs again, up to MAX_RETRIES_DEFAULT times. Other errors propagate immediately.
run_in_isolated_tx_with_retries
Same as run_in_isolated_tx but 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 N in a $N token appearing in sql as an actual parameter reference, ascending.
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 ETag header onto a response, formatted as a strong validator over the integer optimistic-locking version.
status
Inspect each migration in migrations against cratestack_migrations and report which are pending / applied / drifted. Use before apply to surface drift to the operator without changing state.
update_record_with_executor
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
@length on a Bytes field (cratestack#572). Bytes generates as Vec<u8>, which has no character encoding to count against, so “length” here is unambiguously the byte count – unlike validate_length, which counts chars (Unicode scalar values, not UTF-8 code units) because String genuinely has more than one plausible notion of “length”. A Vec<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 @range enforcement. 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 like amount 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 FilterExpr outward through the traversed path, applying each hop’s quantifier. Mirrors what the macro previously emitted as nested FilterExpr::relation*(...) token trees.

Type Aliases§

CratestackBody
Body bytes carried through the transport layer.
CratestackEventFuture
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.