Skip to main content

Crate ash_domain

Crate ash_domain 

Source
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

ConceptWhat it is
Resourcea domain entity: Attributes, Relationships, and ActionDefs
ActionKindRead / Create / Update / Destroy / Generic
pipelinecomposable Preparation · Change · Validation · GenericHandler
Changesetthe mutable state threaded through a write action
Domainthe registry + executor that runs actions
Context<B>the mutable unit of work; its backend B decides its capabilities
Storethe backend’s persistence capability; any Arc<DataLayer> is one
DataLayerthe pluggable storage trait, with a reference in-memory impl
Extensionhow ash-* crates attach to a resource’s actions
Policy / PolicySetscoped authorization: gate operations and redact attribute reads
Clocktime 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-record Computed fields.
attribute
Attributes: the typed fields that make up a Resource.
clock
The Clock seam — where record timestamps come from.
context
The Context — the mutable unit of work, generic over its backend.
datalayer
Persistence: the DataLayer seam.
domain
The Domain — the registry and executor that ties everything together.
error
The framework error type.
event
Domain events: the facts the Domain produces.
extension
The Extension system — how ash-* crates attach to a resource.
id
The IdGenerator seam — how a primary key is minted when an action’s input omits one.
lifecycle
Orderly shutdown of a Domain: the Closable seam and the close gate.
metrics
The Metrics seam — a minimal hook for observing action outcomes.
policy
Authorization: the Policy seam and the PolicySet that scopes it.
publish
Consumer-side transports for carrying a domain event to the outside world: a Notification, a Publisher transport, and a JobQueue for deferred work.
query
Backend-agnostic reads: a Query is a bag of parameters, not a hand-built filter tree.
query_type
Typed queries — a read reached through Domain::query.
read
The typed read builder: Domain::read — one door for every shape of read.
resource
The Resource trait — the declarative domain entity everything derives from.
schema
The registry, as data: DomainSchema and the JSON Schema export.
value
The framework’s neutral data representation: Value and Record.

Macros§

record
Build a Record from key => value pairs — the literal form of Record::from_iter, without its one-value-type-per-call limit.

Attribute Macros§

async_trait

Derive Macros§

Embeddable
Derive macro for the Embeddable trait (requires the derive feature).
FromRecord
Derive macro for the FromRecord trait (requires the derive feature).
IntoRecord
Derive macro for the IntoRecord trait (requires the derive feature).
Projection
Derive macro for a read-only projection Resource (requires the derive feature) — the custom shape a TypedQuery returns.
Resource
Derive macro for the Resource trait (requires the derive feature, on by default). Declare a resource by annotating a struct’s fields instead of hand-writing the trait impl.
TypedQuery
Derive macro for the TypedQuery trait (requires the derive feature) — the impl boilerplate for a typed query run through Domain::query.
ValueEnum
Derive macro for a string-backed enum field (requires the derive feature): generates FromValue and From<Self> for Value for a fieldless enum, so a resource field can be a real Rust enum instead of a bare String.