Expand description
§ash-domain
Model your domain, derive the rest.
ash-domain is a declarative, resource-oriented application core for Rust.
Where the ash-* ecosystem provides satellite primitives (ash-fsm,
ash-flow, ash-time, …), ash-domain is the planet they orbit: you
declare a Resource once — its attributes, relationships, and actions —
and persistence, a uniform action pipeline, and extension hooks are derived
from that single definition.
§The model
| Concept | What it is |
|---|---|
Resource | a domain entity: Attributes, Relationships, and ActionDefs |
ActionKind | Read / Create / Update / Destroy / Generic |
| pipeline | composable Preparation · Change · Validation · GenericHandler |
Changeset | the mutable state threaded through a write action |
Domain | the registry + executor that runs actions |
Context<B> | the mutable unit of work; its backend B decides its capabilities |
Store | the backend’s persistence capability; any Arc<DataLayer> is one |
DataLayer | the pluggable storage trait, with a reference in-memory impl |
Extension | how ash-* crates attach to a resource’s actions |
Policy / PolicySet | scoped authorization: gate operations and redact attribute reads |
Clock | time source (SystemClock / [AshTimeClock], the ash-time HLC) |
§Two convictions
The context is a generic you build. Context<B> carries a backend B
of your choosing, and B’s trait impls decide what the context can do:
persist (B: Store) or not. A store-less Context<()> has no CRUD methods —
the compiler removes them, rather than a runtime error rejecting them.
Richer persistence behaviour (transactions, batching, a unit-of-work) is not
built in: extend DataLayer and implement Store for a backend of your
own, giving it whatever lifecycle those semantics require.
The core validates nothing on your behalf. It runs no built-in attribute
validation — no presence, range, length, or membership checks baked into
attribute metadata. Every rule, from a single required field to a cross-field
invariant, is the consumer’s job, written the Rust way as an
impl Validation for MyType (or a validate_lambda)
that returns Err, registered on the write action — not configured through a
DSL.
§What is implemented vs. a seam
Fully built: the resource/action model, the pipeline, the Domain
executor, the DataLayer trait with an in-memory backend (durable
backends are the consumer’s to impl DataLayer for), and one real
Extension — the ash-fsm state-machine guard
([extension::fsm]). Ergonomics come from the derive feature (on by
default): #[derive(Resource)], from the workspace’s
ash-domain-macros crate, generates the Resource impl from annotated struct
fields. The validated registry is available as data —
Domain::schema, with a JSON Schema rendering — so an API
description, an admin UI or a client type can be generated from the same
declaration the executor runs. Left as documented seams: the API surfaces
themselves (GraphQL/JSON servers, admin UIs) and real policy engines. There
is no distributed logic in the core; ash-lock attaches as an optional
extension.
The shipped extensions and the HLC clock are opt-in cargo features (fsm,
audit, lock, hlc; extensions for the three extensions at once), all
off by default — a default build links no ash-* code beyond the derive
macros.
Reads are bounded and ordered: Query::limit caps every read (with the
domain’s max_rows ceiling filling in), Query::sort gives it a
deterministic order, and ReadRequest::page turns the pair into keyset
pagination whose cursor neither skips nor repeats rows. Writes to a resource
that declares Resource::version_attribute are conditional: the update
lands only if the row still holds the version the caller read, and a lost race
surfaces as Error::Conflict instead of silently overwriting.
Two more opt-in features: sandbox (a deterministic side-effect harness for
tests) and trace (execution-trace instrumentation — tracing spans and
per-stage events over every action, off unless the feature is built and
Domain::enable_tracing is called, with the trace’s sink chosen by the
subscriber the consumer installs).
§Example
use ash_domain::{erase, Context, Domain, DomainConfig, DomainContext, Record, Value, Query, Resource};
use ash_domain::action::{ActionDef, ActionInput};
use ash_domain::attribute::{Attribute, AttrType};
use ash_domain::datalayer::memory::InMemoryDataLayer;
use std::sync::Arc;
// 1. Declare a resource — a type, resolved at compile time. It keeps the
// dynamic `Record` as its `Data`, so actions hand back a `Record`.
struct Note;
impl Resource for Note {
const NAME: &'static str = "note";
type Data = Record;
fn attributes() -> Vec<Attribute> {
vec![
Attribute::scalar::<String>("id"),
Attribute::scalar::<String>("title"),
Attribute { default: Some(Value::Bool(false)), ..Attribute::scalar::<bool>("done") },
]
}
fn actions() -> Vec<ActionDef> {
vec![ActionDef::write("create"), ActionDef::read("read")]
}
}
let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
rt.block_on(async {
// 2. Build a domain from a plain config struct. Authorization is
// default-deny, so a domain with no policies must say so explicitly
// (`PolicySet::permissive()`); register real policies instead when
// the domain gates access itself.
let domain = Domain::new(DomainConfig {
resources: vec![erase::<Note>()],
policies: ash_domain::PolicySet::permissive(),
..DomainConfig::default()
}, DomainContext::new());
// 3. Create the context up front over a persistence backend, then thread
// it — `&mut` — through the actions. A bare `Arc<DataLayer>` is a `Store`.
let mut ctx = Context::new(Arc::new(InMemoryDataLayer::new()));
let created = domain
.handle_action::<Note>(&mut ctx, "create", ActionInput::create_record(Record::from_iter([("title", "hello")])))
.await
.unwrap()
.into_record()
.unwrap();
assert_eq!(created.get("title"), Some(&Value::from("hello")));
assert_eq!(created.get("done"), Some(&Value::Bool(false))); // default applied
let all = domain
.handle_action::<Note>(&mut ctx, "read", ActionInput::read(Query::new("note")))
.await
.unwrap()
.into_records()
.unwrap();
assert_eq!(all.len(), 1);
});Re-exports§
pub use action::ActionDef;pub use action::ActionInput;pub use action::ActionKind;pub use action::ActionOutcome;pub use action::ActionResult;pub use action::Change;pub use action::Changeset;pub use action::GenericHandler;pub use action::Preparation;pub use action::Validation;pub use aggregate::Aggregate;pub use aggregate::AggregateKind;pub use aggregate::Computed;pub use aggregate::Computer;pub use attribute::AttrType;pub use attribute::Attribute;pub use clock::Clock;pub use clock::SystemClock;pub use context::Context;pub use context::ContextId;pub use context::DomainContext;pub use context::Extensions;pub use context::FromRef;pub use context::HandlerContext;pub use context::Store;pub use datalayer::DataLayer;pub use datalayer::Transaction;pub use domain::Bound;pub use domain::DEFAULT_MAX_BATCH;pub use domain::DEFAULT_MAX_LOAD_DEPTH;pub use domain::DEFAULT_MAX_ROWS;pub use domain::Domain;pub use domain::DomainBuilder;pub use domain::DomainConfig;pub use error::Error;pub use error::Result;pub use event::DomainEvent;pub use event::Emitter;pub use event::EventHandler;pub use extension::Extension;pub use id::DefaultIdGenerator;pub use id::IdGenerator;pub use lifecycle::Closable;pub use metrics::MetricSample;pub use metrics::Metrics;pub use metrics::Outcome;pub use policy::Admit;pub use policy::AllowAll;pub use policy::AuthorizedOne;pub use policy::AuthorizedRead;pub use policy::ClientPolicy;pub use policy::Decision;pub use policy::Deny;pub use policy::Explanation;pub use policy::Policy;pub use policy::PolicyCheck;pub use policy::PolicyClient;pub use policy::PolicyLevel;pub use policy::PolicyNode;pub use policy::PolicyRequest;pub use policy::PolicySet;pub use policy::PolicyVote;pub use policy::ReadReport;pub use policy::Redaction;pub use policy::Scope;pub use policy::ScopedPolicy;pub use policy::Target;pub use policy::policy_lambda;pub use publish::Job;pub use publish::JobQueue;pub use publish::Notification;pub use publish::Publisher;pub use query::Cursor;pub use query::Filter;pub use query::Query;pub use query::SortDirection;pub use query::SortKey;pub use query_type::TypedQuery;pub use read::OffsetPage;pub use read::Page;pub use read::ReadRequest;pub use resource::Cardinality;pub use resource::Embeddable;pub use resource::ErasedResource;pub use resource::Loaded;pub use resource::Relationship;pub use resource::Resource;pub use resource::ResourceHandle;pub use resource::TenantStrategy;pub use resource::Through;pub use resource::erase;pub use schema::DomainSchema;pub use value::FromRecord;pub use value::FromValue;pub use value::IntoRecord;pub use value::Record;pub use value::Value;
Modules§
- action
- Actions and the composable pipeline that runs them.
- aggregate
- Derived read values:
Aggregates over a relationship and per-recordComputedfields. - attribute
- Attributes: the typed fields that make up a
Resource. - clock
- The
Clockseam — where record timestamps come from. - context
- The
Context— the mutable unit of work, generic over its backend. - datalayer
- Persistence: the
DataLayerseam. - domain
- The
Domain— the registry and executor that ties everything together. - error
- The framework error type.
- event
- Domain events: the facts the
Domainproduces. - extension
- The
Extensionsystem — howash-*crates attach to a resource. - id
- The
IdGeneratorseam — how a primary key is minted when an action’s input omits one. - lifecycle
- Orderly shutdown of a
Domain: theClosableseam and the close gate. - metrics
- The
Metricsseam — a minimal hook for observing action outcomes. - policy
- Authorization: the
Policyseam and thePolicySetthat scopes it. - publish
- Consumer-side transports for carrying a domain event to the outside world: a
Notification, aPublishertransport, and aJobQueuefor deferred work. - query
- Backend-agnostic reads: a
Queryis a bag of parameters, not a hand-built filter tree. - query_
type - Typed queries — a
readreached throughDomain::query. - read
- The typed read builder:
Domain::read— one door for every shape of read. - resource
- The
Resourcetrait — the declarative domain entity everything derives from. - schema
- The registry, as data:
DomainSchemaand the JSON Schema export. - value
- The framework’s neutral data representation:
ValueandRecord.
Macros§
- record
- Build a
Recordfromkey => valuepairs — the literal form ofRecord::from_iter, without its one-value-type-per-call limit.
Attribute Macros§
Derive Macros§
- Embeddable
- Derive macro for the
Embeddabletrait (requires thederivefeature). - From
Record - Derive macro for the
FromRecordtrait (requires thederivefeature). - Into
Record - Derive macro for the
IntoRecordtrait (requires thederivefeature). - Projection
- Derive macro for a read-only projection
Resource(requires thederivefeature) — the custom shape aTypedQueryreturns. - Resource
- Derive macro for the
Resourcetrait (requires thederivefeature, on by default). Declare a resource by annotating a struct’s fields instead of hand-writing the trait impl. - Typed
Query - Derive macro for the
TypedQuerytrait (requires thederivefeature) — theimplboilerplate for a typed query run throughDomain::query. - Value
Enum - Derive macro for a string-backed enum field (requires the
derivefeature): generatesFromValueandFrom<Self> for Valuefor a fieldless enum, so a resource field can be a real Rust enum instead of a bareString.