Skip to main content

ash_domain/
lib.rs

1//! # ash-domain
2//!
3//! **Model your domain, derive the rest.**
4//!
5//! `ash-domain` is a declarative, resource-oriented application core for Rust.
6//! Where the `ash-*` ecosystem provides *satellite* primitives (`ash-fsm`,
7//! `ash-flow`, `ash-time`, …), `ash-domain` is the **planet they orbit**: you
8//! declare a [`Resource`] once — its attributes, relationships, and actions —
9//! and persistence, a uniform action pipeline, and extension hooks are derived
10//! from that single definition.
11//!
12//! ## The model
13//!
14//! | Concept | What it is |
15//! |---------|-----------|
16//! | [`Resource`] | a domain entity: [`Attribute`]s, [`Relationship`]s, and [`ActionDef`]s |
17//! | [`ActionKind`] | `Read` / `Create` / `Update` / `Destroy` / `Generic` |
18//! | pipeline | composable [`Preparation`] · [`Change`] · [`Validation`] · [`GenericHandler`] |
19//! | [`Changeset`] | the mutable state threaded through a write action |
20//! | [`Domain`] | the registry + executor that runs actions |
21//! | [`Context`]`<B>` | the mutable unit of work; its backend `B` decides its capabilities |
22//! | [`Store`] | the backend's persistence capability; any `Arc<`[`DataLayer`]`>` is one |
23//! | [`DataLayer`] | the pluggable storage trait, with a reference [in-memory](datalayer::memory) impl |
24//! | [`Extension`] | how `ash-*` crates attach to a resource's actions |
25//! | [`Policy`] / [`PolicySet`] | scoped authorization: gate operations and redact attribute reads |
26//! | [`Clock`] | time source ([`SystemClock`] / [`AshTimeClock`], the `ash-time` HLC) |
27//!
28//! ## Two convictions
29//!
30//! **The context is a generic you build.** `Context<B>` carries a backend `B`
31//! of your choosing, and `B`'s trait impls decide what the context can do:
32//! persist (`B: Store`) or not. A store-less `Context<()>` has no CRUD methods —
33//! the compiler removes them, rather than a runtime error rejecting them.
34//! Richer persistence behaviour (transactions, batching, a unit-of-work) is not
35//! built in: extend [`DataLayer`] and implement `Store` for a backend of your
36//! own, giving it whatever lifecycle those semantics require.
37//!
38//! **The core validates nothing on your behalf.** It runs no built-in attribute
39//! validation — no presence, range, length, or membership checks baked into
40//! attribute metadata. Every rule, from a single required field to a cross-field
41//! invariant, is the consumer's job, written the Rust way as an
42//! `impl Validation for MyType` (or a [`validate_lambda`](ActionDef::validate_lambda))
43//! that returns `Err`, registered on the write action — not configured through a
44//! DSL.
45//!
46//! ## What is implemented vs. a seam
47//!
48//! Fully built: the resource/action model, the pipeline, the [`Domain`]
49//! executor, the [`DataLayer`] trait with an **in-memory** backend (durable
50//! backends are the consumer's to `impl DataLayer for`), and one real
51//! [`Extension`] — the `ash-fsm` state-machine guard
52//! ([`extension::fsm`]). Ergonomics come from the `derive` feature (on by
53//! default): [`#[derive(Resource)]`](macro@Resource), from the workspace's
54//! `ash-domain-macros` crate, generates the [`Resource`] impl from annotated struct
55//! fields. The validated registry is available as data —
56//! [`Domain::schema`](Domain::schema), with a JSON Schema rendering — so an API
57//! description, an admin UI or a client type can be *generated* from the same
58//! declaration the executor runs. Left as documented seams: the API surfaces
59//! themselves (GraphQL/JSON servers, admin UIs) and real policy engines. There
60//! is **no distributed logic** in the core; `ash-lock` attaches as an optional
61//! extension.
62//!
63//! The shipped extensions and the HLC clock are opt-in cargo features (`fsm`,
64//! `audit`, `lock`, `hlc`; `extensions` for the three extensions at once), all
65//! **off by default** — a default build links no `ash-*` code beyond the derive
66//! macros.
67//!
68//! Reads are **bounded and ordered**: `Query::limit` caps every read (with the
69//! domain's `max_rows` ceiling filling in), `Query::sort` gives it a
70//! deterministic order, and `ReadRequest::page` turns the pair into keyset
71//! pagination whose cursor neither skips nor repeats rows. Writes to a resource
72//! that declares [`Resource::version_attribute`] are **conditional**: the update
73//! lands only if the row still holds the version the caller read, and a lost race
74//! surfaces as [`Error::Conflict`] instead of silently overwriting.
75//!
76//! Two more opt-in features: `sandbox` (a deterministic side-effect harness for
77//! tests) and `trace` (execution-trace instrumentation — `tracing` spans and
78//! per-stage events over every action, off unless the feature is built *and*
79//! [`Domain::enable_tracing`] is called, with the trace's sink chosen by the
80//! subscriber the consumer installs).
81//!
82//! ## Example
83//!
84//! ```
85//! use ash_domain::{erase, Context, Domain, DomainConfig, DomainContext, Record, Value, Query, Resource};
86//! use ash_domain::action::{ActionDef, ActionInput};
87//! use ash_domain::attribute::{Attribute, AttrType};
88//! use ash_domain::datalayer::memory::InMemoryDataLayer;
89//! use std::sync::Arc;
90//!
91//! // 1. Declare a resource — a type, resolved at compile time. It keeps the
92//! //    dynamic `Record` as its `Data`, so actions hand back a `Record`.
93//! struct Note;
94//! impl Resource for Note {
95//!     const NAME: &'static str = "note";
96//!     type Data = Record;
97//!     fn attributes() -> Vec<Attribute> {
98//!         vec![
99//!             Attribute::scalar::<String>("id"),
100//!             Attribute::scalar::<String>("title"),
101//!             Attribute { default: Some(Value::Bool(false)), ..Attribute::scalar::<bool>("done") },
102//!         ]
103//!     }
104//!     fn actions() -> Vec<ActionDef> {
105//!         vec![ActionDef::write("create"), ActionDef::read("read")]
106//!     }
107//! }
108//!
109//! let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
110//! rt.block_on(async {
111//!     // 2. Build a domain from a plain config struct. Authorization is
112//!     //    default-deny, so a domain with no policies must say so explicitly
113//!     //    (`PolicySet::permissive()`); register real policies instead when
114//!     //    the domain gates access itself.
115//!     let domain = Domain::new(DomainConfig {
116//!         resources: vec![erase::<Note>()],
117//!         policies: ash_domain::PolicySet::permissive(),
118//!         ..DomainConfig::default()
119//!     }, DomainContext::new());
120//!
121//!     // 3. Create the context up front over a persistence backend, then thread
122//!     //    it — `&mut` — through the actions. A bare `Arc<DataLayer>` is a `Store`.
123//!     let mut ctx = Context::new(Arc::new(InMemoryDataLayer::new()));
124//!     let created = domain
125//!         .handle_action::<Note>(&mut ctx, "create", ActionInput::create_record(Record::from_iter([("title", "hello")])))
126//!         .await
127//!         .unwrap()
128//!         .into_record()
129//!         .unwrap();
130//!     assert_eq!(created.get("title"), Some(&Value::from("hello")));
131//!     assert_eq!(created.get("done"), Some(&Value::Bool(false))); // default applied
132//!
133//!     let all = domain
134//!         .handle_action::<Note>(&mut ctx, "read", ActionInput::read(Query::new("note")))
135//!         .await
136//!         .unwrap()
137//!         .into_records()
138//!         .unwrap();
139//!     assert_eq!(all.len(), 1);
140//! });
141//! ```
142
143#![forbid(unsafe_code)]
144#![warn(missing_docs)]
145
146pub mod action;
147pub mod aggregate;
148pub mod attribute;
149pub mod clock;
150pub mod context;
151pub mod id;
152#[cfg(feature = "sandbox")]
153pub mod sandbox;
154// Internal execution-trace instrumentation (macros used by the executor). Not
155// public surface; emission is opt-out at compile time (the `trace` feature) and
156// at runtime (`Domain::enable_tracing`).
157pub mod datalayer;
158pub mod domain;
159pub mod error;
160pub mod event;
161pub mod extension;
162pub mod lifecycle;
163pub mod metrics;
164pub mod policy;
165pub mod publish;
166mod trace;
167
168// The ash-flare supervisor adapter — a `Worker` that owns a `Domain`'s serving
169// lifetime and drives its orderly `close()` on shutdown. Behind the `flare`
170// feature so the `ash-flare` dependency is opt-in.
171#[cfg(feature = "flare")]
172pub mod flare;
173pub mod query;
174pub mod query_type;
175pub mod read;
176pub mod resource;
177pub mod schema;
178pub mod value;
179
180// Re-export `async_trait` so derived impls (e.g. `#[derive(TypedQuery)]`) and
181// consumer trait impls can annotate with a version-matched `#[async_trait]`
182// without adding their own skew-prone dependency.
183pub use async_trait::async_trait;
184
185// Re-export the ash-* crates that appear in the public API so callers can name
186// their types without adding a skew-prone dependency of their own. Each rides
187// its own feature — a default build links none of them.
188#[cfg(feature = "fsm")]
189pub use ash_fsm;
190#[cfg(feature = "lock")]
191pub use ash_lock;
192#[cfg(feature = "audit")]
193pub use ash_log;
194#[cfg(feature = "hlc")]
195pub use ash_time;
196
197pub use action::{
198    ActionDef, ActionInput, ActionKind, ActionOutcome, ActionResult, Change, Changeset,
199    GenericHandler, Preparation, Validation,
200};
201pub use aggregate::{Aggregate, AggregateKind, Computed, Computer};
202pub use attribute::{AttrType, Attribute};
203#[cfg(feature = "hlc")]
204pub use clock::AshTimeClock;
205pub use clock::{Clock, SystemClock};
206pub use context::{Context, ContextId, DomainContext, Extensions, FromRef, HandlerContext, Store};
207pub use datalayer::{DataLayer, Transaction};
208pub use domain::{
209    Bound, DEFAULT_MAX_BATCH, DEFAULT_MAX_LOAD_DEPTH, DEFAULT_MAX_ROWS, Domain, DomainBuilder,
210    DomainConfig,
211};
212pub use error::{Error, Result};
213pub use event::{DomainEvent, Emitter, EventHandler};
214pub use extension::Extension;
215pub use id::{DefaultIdGenerator, IdGenerator};
216pub use lifecycle::Closable;
217pub use metrics::{MetricSample, Metrics, Outcome};
218pub use policy::{
219    Admit, AllowAll, AuthorizedOne, AuthorizedRead, ClientPolicy, Decision, Deny, Explanation,
220    Policy, PolicyCheck, PolicyClient, PolicyLevel, PolicyNode, PolicyRequest, PolicySet,
221    PolicyVote, ReadReport, Redaction, Scope, ScopedPolicy, Target, policy_lambda,
222};
223pub use publish::{Job, JobQueue, Notification, Publisher};
224pub use query::{Cursor, Filter, Query, SortDirection, SortKey};
225pub use query_type::TypedQuery;
226pub use read::{OffsetPage, Page, ReadRequest};
227pub use resource::{
228    Cardinality, Embeddable, ErasedResource, Loaded, Relationship, Resource, ResourceHandle,
229    TenantStrategy, Through, erase,
230};
231pub use schema::DomainSchema;
232pub use value::{FromRecord, FromValue, IntoRecord, Record, Value};
233
234/// Derive macro for the [`Resource`] trait (requires the `derive` feature, on by
235/// default). Declare a resource by annotating a struct's fields instead of
236/// hand-writing the trait impl.
237///
238/// - Container: `#[resource(name = "...", table = "...", tenant = "<attr>",
239///   tenant_layer)]` (name defaults to the lower-cased type; `table` sets the
240///   storage name; `tenant`/`tenant_layer` opt into multitenancy).
241/// - Fields: `#[attribute(primary_key, default = <literal>, embed)]`; each
242///   field's `AttrType` is a scalar carrying the field's own Rust type (inferred
243///   automatically), or an embed. `primary_key` names the resource's key (no
244///   attribute flag survives — it emits a `Resource::primary_key()` override).
245///   The core runs no attribute validation — enforce presence/ranges/formats in
246///   a [`Validation`] on the action. A default set of CRUD actions is generated.
247/// - Relationships: `#[relationship(name = "...", has_many|belongs_to|has_one|
248///   many_to_many, destination = "...", source = "...", destination_attr =
249///   "...")]`, repeatable.
250/// - Aggregates: `#[aggregate(count|sum|min|max|exists, name = "...",
251///   relationship = "...", field = "...")]`, repeatable (`field` for
252///   sum/min/max). Computed fields reference a `Computer` type, so they stay a
253///   hand-written [`Resource::computed`] override.
254/// - Typed interface: for the default CRUD actions the derive also generates
255///   compile-checked associated fns — `Note::create(&domain, &mut ctx, params)`,
256///   `read`, `get` (one row by primary key), `update`, `destroy` — so you name
257///   the action as a method, not a
258///   string. Each wraps the single [`Domain::handle_action`] entry point and
259///   projects its outcome back into the typed row.
260/// - Custom actions: `#[action(update, name = "completed")]` (repeatable) declares
261///   an action beyond the CRUD set and generates a typed method for it —
262///   `Note::completed(&domain, &mut ctx, id, params)`, reachable dynamically as
263///   `domain.handle_action::<Note>(&mut ctx, "completed", ActionInput::update(id, params))`.
264///   The attribute is declarative — it names the action and its shape (`create` /
265///   `update` / `destroy` / `read`); the action's *behavior* (the
266///   [`Change`] that sets `completed = true`) is attached as
267///   explicit code. Generic actions, which
268///   need a handler at declaration, stay on the hand-written `actions()` path and
269///   run via `ActionInput::generic(input)`.
270///
271/// A derived resource is resolved by type and hands back **its own struct** —
272/// `#[derive(Resource)]` also generates the [`FromRecord`]/[`IntoRecord`]
273/// conversions and the typed action methods, so `Note::create` returns a `Note`,
274/// not a `Record`:
275///
276/// ```
277/// use std::sync::Arc;
278/// use ash_domain::{erase, Context, Domain, DomainConfig, DomainContext, Record, Query, Resource};
279/// use ash_domain::datalayer::memory::InMemoryDataLayer;
280///
281/// #[derive(Resource, Default)]
282/// #[resource(name = "note")]
283/// struct Note {
284///     #[attribute(primary_key)]
285///     id: String,
286///     title: String,
287///     #[attribute(default = false)]
288///     done: bool,
289/// }
290///
291/// let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
292/// rt.block_on(async {
293///     let domain = Domain::new(DomainConfig {
294///         resources: vec![erase::<Note>()],
295///         policies: ash_domain::PolicySet::permissive(),
296///         ..DomainConfig::default()
297///     }, DomainContext::new());
298///
299///     let mut ctx = Context::new(Arc::new(InMemoryDataLayer::new()));
300///     // Typed code interface: `Note::create` is generated by the derive, so the
301///     // resource and action name are both compile-checked (no `::<Note>("create")`).
302///     let created: Note = Note::create(&domain, &mut ctx, Record::from_iter([("title", "hi")]))
303///         .await
304///         .unwrap();
305///     assert_eq!(created.done, false);       // default applied, typed field
306///     assert!(!created.id.is_empty());       // primary key auto-generated
307///
308///     // `read`/`update`/`destroy` are generated the same way.
309///     let all: Vec<Note> = Note::read(&domain, &mut ctx, Query::new("note")).await.unwrap();
310///     assert_eq!(all.len(), 1);
311/// });
312/// ```
313///
314/// The richer declarations — storage overrides, multitenancy, relationships, and
315/// aggregates — are attributes too, so a `Post` scoped to an `org_id` tenant with
316/// a `belongs_to` author and a mapped column reads:
317///
318/// ```
319/// use ash_domain::{erase, Resource, TenantStrategy, Cardinality, AggregateKind};
320///
321/// #[derive(Resource, Default)]
322/// #[resource(name = "post", table = "posts", tenant = "org_id")]
323/// #[relationship(name = "author", belongs_to, destination = "author",
324///                source = "author_id", destination_attr = "id")]
325/// #[aggregate(count, name = "comment_count", relationship = "comments")]
326/// #[relationship(name = "comments", has_many, destination = "comment",
327///                source = "id", destination_attr = "post_id")]
328/// struct Post {
329///     #[attribute(primary_key)]
330///     id: String,
331///     author_id: String,
332///     org_id: String,
333///     title: String,
334/// }
335///
336/// let h = erase::<Post>();
337/// assert_eq!(h.storage_name(), "posts");                 // table override
338/// assert_eq!(Post::tenant(), Some(TenantStrategy::Attribute("org_id".into())));
339/// assert_eq!(Post::relationships().len(), 2);
340/// assert_eq!(Post::aggregates()[0].kind, AggregateKind::Count);
341/// // The primary-key name is emitted as a `primary_key()` override.
342/// assert_eq!(Post::primary_key(), "id");
343/// ```
344///
345#[cfg(feature = "derive")]
346pub use ash_domain_macros::Resource;
347
348/// Derive macro for a **read-only projection** [`Resource`] (requires the
349/// `derive` feature) — the custom shape a [`TypedQuery`] returns.
350///
351/// Identical to [`#[derive(Resource)]`](macro@Resource) but with a single `read`
352/// action instead of the full CRUD set, and no typed `create`/`update`/`destroy`
353/// helpers: a projection / aggregation is never written, only produced as the
354/// result of a [`Domain::query`]. Its lone `read` action is what its policies gate
355/// and redact under.
356///
357/// ```
358/// use ash_domain::{Projection, Resource, ActionKind};
359///
360/// #[derive(Projection, Default)]
361/// #[resource(name = "owner_stats")]
362/// struct OwnerStats {
363///     owner_id: String,
364///     open_count: i64,
365/// }
366///
367/// let actions = OwnerStats::actions();
368/// assert_eq!(actions.len(), 1);
369/// assert_eq!(actions[0].kind, ActionKind::Read);
370/// ```
371#[cfg(feature = "derive")]
372pub use ash_domain_macros::Projection;
373
374/// Derive macro for the [`TypedQuery`] trait (requires the `derive` feature) —
375/// the `impl` boilerplate for a typed query run through [`Domain::query`].
376///
377/// A typed query is an ordinary read whose result is a **custom resource** (a
378/// projection or aggregation), run against the context's concrete backend. The
379/// hand-written impl is pure plumbing — the associated result type, the backend
380/// capability bound, and a one-line body dispatching to a backend method — so this
381/// derive writes it from a single `#[query(...)]` attribute:
382///
383/// ```
384/// use std::sync::Arc;
385/// use ash_domain::{
386///     erase, Context, DataLayer, Domain, DomainConfig, DomainContext, Projection,
387///     PolicySet, Record, Result, Store, TypedQuery, Value,
388/// };
389/// use ash_domain::datalayer::memory::InMemoryDataLayer;
390///
391/// #[derive(Projection, Default)]
392/// #[resource(name = "owner_stats")]
393/// struct OwnerStats {
394///     owner_id: String,
395///     open_count: i64,
396/// }
397///
398/// // The backend capability the query needs. The `run =` method takes the
399/// // `&Context<B>` the generated `run` hands it.
400/// #[ash_domain::async_trait]
401/// trait TodoStats: Sized {
402///     async fn owner_stats(&self, ctx: &Context<Self>) -> Result<Vec<Record>>;
403/// }
404///
405/// // The whole `impl TypedQuery` from one attribute: which result resource,
406/// // which backend-capability bound, and which method to call.
407/// #[derive(TypedQuery)]
408/// #[query(resource = OwnerStats, backend = TodoStats, run = owner_stats)]
409/// struct StatsByOwner;
410///
411/// // A concrete backend that is both a `Store` and carries the capability.
412/// #[derive(Clone)]
413/// struct Backend(Arc<InMemoryDataLayer>);
414/// impl Store for Backend {
415///     fn layer(&self) -> &dyn DataLayer { &*self.0 }
416/// }
417/// #[ash_domain::async_trait]
418/// impl TodoStats for Backend {
419///     async fn owner_stats(&self, _ctx: &Context<Self>) -> Result<Vec<Record>> {
420///         Ok(vec![Record::from_iter([
421///             ("owner_id", Value::from("u-1")),
422///             ("open_count", Value::Int(3)),
423///         ])])
424///     }
425/// }
426///
427/// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
428/// # rt.block_on(async {
429/// let domain = Domain::new(DomainConfig {
430///     resources: vec![erase::<OwnerStats>()],
431///     policies: PolicySet::permissive(),
432///     ..Default::default()
433/// }, DomainContext::new());
434/// let ctx = Context::new(Backend(Arc::new(InMemoryDataLayer::new())));
435///
436/// let rows: Vec<OwnerStats> = domain.query(&ctx, StatsByOwner).await.unwrap();
437/// assert_eq!(rows[0].open_count, 3);
438/// # });
439/// ```
440///
441/// `#[query(...)]` options: `resource = <Type>` (required, the result resource),
442/// `run = <method>` (required, the backend method called as
443/// `ctx.backend().<method>(ctx)`), `backend = <Trait>` (optional, repeatable —
444/// extra bounds on `B` beyond [`Store`]), `action = "<name>"` (optional —
445/// authorize under a specific named read action of the result resource), and
446/// `tenant_aware` (optional bare flag — see below).
447///
448/// # Tenant-scoped queries
449///
450/// When the result [`resource`] is **tenant-scoped**, the domain refuses to run
451/// the query unless it declares [`tenant_aware`](TypedQuery::tenant_aware) — a
452/// promise that `run` filters by [`ctx.tenant()`](Context::tenant) itself (the
453/// domain can't fold a predicate into a hand-shaped read). Add the bare
454/// `tenant_aware` flag to the attribute to make that promise; the `run` method
455/// must actually honour it. Without it, a tenant-scoped query fails with
456/// [`Error::MissingTenant`].
457///
458/// ```
459/// use std::sync::Arc;
460/// use ash_domain::{
461///     erase, Context, DataLayer, Domain, DomainConfig, DomainContext, Projection,
462///     PolicySet, Record, Result, Store, TenantStrategy, TypedQuery, Value,
463/// };
464/// use ash_domain::datalayer::memory::InMemoryDataLayer;
465///
466/// // A tenant-scoped projection: it carries an `org_id` discriminator.
467/// #[derive(Projection, Default)]
468/// #[resource(name = "org_stats", tenant = "org_id")]
469/// struct OrgStats {
470///     org_id: String,
471///     open_count: i64,
472/// }
473///
474/// #[ash_domain::async_trait]
475/// trait OrgReports: Sized {
476///     async fn org_stats(&self, ctx: &Context<Self>) -> Result<Vec<Record>>;
477/// }
478///
479/// // `tenant_aware` asserts `run` scopes by the tenant, so the guard admits it.
480/// #[derive(TypedQuery)]
481/// #[query(resource = OrgStats, backend = OrgReports, run = org_stats, tenant_aware)]
482/// struct StatsByOrg;
483///
484/// #[derive(Clone)]
485/// struct Backend(Arc<InMemoryDataLayer>);
486/// impl Store for Backend {
487///     fn layer(&self) -> &dyn DataLayer { &*self.0 }
488/// }
489/// #[ash_domain::async_trait]
490/// impl OrgReports for Backend {
491///     async fn org_stats(&self, ctx: &Context<Self>) -> Result<Vec<Record>> {
492///         // A real impl filters by this; here we just echo it back.
493///         let org = ctx.tenant().and_then(Value::as_str).unwrap_or("").to_string();
494///         Ok(vec![Record::from_iter([
495///             ("org_id", Value::from(org)),
496///             ("open_count", Value::Int(2)),
497///         ])])
498///     }
499/// }
500///
501/// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
502/// # rt.block_on(async {
503/// let domain = Domain::new(DomainConfig {
504///     resources: vec![erase::<OrgStats>()],
505///     policies: PolicySet::permissive(),
506///     ..Default::default()
507/// }, DomainContext::new());
508///
509/// let mut ctx = Context::new(Backend(Arc::new(InMemoryDataLayer::new())));
510/// ctx.set_tenant("acme");
511/// let rows: Vec<OrgStats> = domain.query(&ctx, StatsByOrg).await.unwrap();
512/// assert_eq!(rows[0].org_id, "acme");
513/// # });
514/// ```
515#[cfg(feature = "derive")]
516pub use ash_domain_macros::TypedQuery;
517
518/// Derive macro for the [`Embeddable`] trait (requires the `derive` feature).
519///
520/// Declares a struct as an **embedded resource** — a structured value stored
521/// inside another resource, with its own attributes but no name, actions, or
522/// table. Uses the same `#[attribute(...)]` field options as
523/// [`Resource`](macro@Resource); declare a field of the embeddable type on a
524/// parent resource with `#[attribute(embed)]` (or `Vec<T>` for a repeated
525/// embed):
526///
527/// ```
528/// use ash_domain::{Embeddable, Resource};
529///
530/// #[derive(Embeddable, Default)]
531/// struct Address {
532///     city: String,
533///     #[attribute(default = "US")]
534///     country: String,
535/// }
536///
537/// #[derive(Resource, Default)]
538/// #[resource(name = "customer")]
539/// struct Customer {
540///     #[attribute(primary_key)]
541///     id: String,
542///     #[attribute(embed)]
543///     address: Address,
544/// }
545///
546/// // The embedded schema is carried inline on the parent attribute.
547/// let attrs = Customer::attributes();
548/// let address = attrs.into_iter().find(|a| a.name == "address").unwrap();
549/// assert!(matches!(address.ty, ash_domain::attribute::AttrType::_Embed(_)));
550/// ```
551///
552/// The parent round-trips as a typed struct: the embed reads back as a nested
553/// `Address`, with its declared default applied by the write pipeline.
554///
555/// ```
556/// # use std::sync::Arc;
557/// # use ash_domain::{Embeddable, Resource, Context, Domain, DomainConfig, DomainContext, Record, Value, erase};
558/// # use ash_domain::datalayer::memory::InMemoryDataLayer;
559/// #[derive(Embeddable, Default, PartialEq, Debug)]
560/// struct Address {
561///     city: String,
562///     #[attribute(default = "US")]
563///     country: String,
564/// }
565///
566/// #[derive(Resource, Default)]
567/// #[resource(name = "customer")]
568/// struct Customer {
569///     #[attribute(primary_key)]
570///     id: String,
571///     #[attribute(embed)]
572///     address: Address,
573/// }
574///
575/// let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
576/// rt.block_on(async {
577///     let domain = Domain::new(DomainConfig {
578///         resources: vec![erase::<Customer>()],
579///         policies: ash_domain::PolicySet::permissive(),
580///         ..Default::default()
581///     }, DomainContext::new());
582///     let mut ctx = Context::new(Arc::new(InMemoryDataLayer::new()));
583///
584///     // Build the embed as a nested map; omit `country` to prove the default.
585///     let mut addr = Record::new();
586///     addr.insert("city", "London");
587///     let created: Customer = Customer::create(
588///         &domain, &mut ctx,
589///         Record::from_iter([("address", Value::from(addr))]),
590///     ).await.unwrap();
591///
592///     assert_eq!(created.address, Address { city: "London".into(), country: "US".into() });
593/// });
594/// ```
595#[cfg(feature = "derive")]
596pub use ash_domain_macros::Embeddable;
597
598/// Derive macro for the [`FromRecord`] trait (requires the `derive` feature).
599///
600/// [`#[derive(Resource)]`](macro@Resource) and
601/// [`#[derive(Embeddable)]`](macro@Embeddable) already generate this conversion;
602/// derive it on its own for a **plain data type** that isn't a resource — a read
603/// projection or a generic action's typed output — so you can hydrate it from the
604/// dynamic [`Record`] the pipeline flows. `Option<T>` fields are nullable,
605/// integers are range-checked on the way in, and `#[attribute(embed)]` fields
606/// round-trip through a nested type's `FromRecord`.
607///
608/// ```
609/// use ash_domain::{FromRecord, Record, Value};
610///
611/// #[derive(FromRecord)]
612/// struct AuthorRow {
613///     id: i64,
614///     name: String,
615///     bio: Option<String>,
616/// }
617///
618/// let rec = Record::from_iter([("id", Value::Int(7)), ("name", Value::from("Ada"))]);
619/// let row = AuthorRow::from_record(&rec).unwrap();
620/// assert_eq!((row.id, row.name.as_str(), row.bio), (7, "Ada", None));
621/// ```
622#[cfg(feature = "derive")]
623pub use ash_domain_macros::FromRecord;
624
625/// Derive macro for the [`IntoRecord`] trait (requires the `derive` feature).
626///
627/// [`#[derive(Resource)]`](macro@Resource) and
628/// [`#[derive(Embeddable)]`](macro@Embeddable) already generate this conversion;
629/// derive it on its own for a **typed action-params type**, so you can pass a
630/// struct where the [`Domain`] write methods want `impl IntoRecord` instead of
631/// hand-building a `Record::from_iter([...])`.
632///
633/// ```
634/// use ash_domain::{IntoRecord, Value};
635///
636/// #[derive(IntoRecord)]
637/// struct NewNote {
638///     title: String,
639///     done: bool,
640/// }
641///
642/// // `into_record` is fallible (an out-of-`i64` integer field would error);
643/// // for these string/bool fields it can only succeed.
644/// let rec = NewNote { title: "hi".into(), done: false }.into_record().unwrap();
645/// assert_eq!(rec.get("title"), Some(&Value::from("hi")));
646/// assert_eq!(rec.get("done"), Some(&Value::Bool(false)));
647/// ```
648#[cfg(feature = "derive")]
649pub use ash_domain_macros::IntoRecord;
650
651/// Derive macro for a **string-backed enum field** (requires the `derive`
652/// feature): generates [`FromValue`] and `From<Self> for Value` for a fieldless
653/// enum, so a resource field can be a real Rust enum instead of a bare `String`.
654///
655/// Mark the field `#[attribute(enumerate)]` on the [`Resource`](macro@Resource)
656/// and derive `ValueEnum` on its type. Each variant stores as its name
657/// (lower-cased, or a `#[value(rename = "...")]` override); a string matching no
658/// variant fails the read with [`Error::Serialization`], so an unknown value can
659/// never enter a typed row.
660///
661/// ```
662/// use ash_domain::{FromValue, Value, ValueEnum};
663///
664/// #[derive(ValueEnum, PartialEq, Debug)]
665/// enum Status {
666///     Open,
667///     Done,
668///     #[value(rename = "in_progress")]
669///     InProgress,
670/// }
671///
672/// assert_eq!(Value::from(Status::Open), Value::from("open"));
673/// assert_eq!(Value::from(Status::InProgress), Value::from("in_progress"));
674/// assert_eq!(Status::from_value(&Value::from("done")).unwrap(), Status::Done);
675/// assert!(Status::from_value(&Value::from("nope")).is_err());
676/// ```
677#[cfg(feature = "derive")]
678pub use ash_domain_macros::ValueEnum;