Skip to main content

ash_domain/
context.rs

1//! The [`Context`] — the mutable unit of work, generic over its backend.
2//!
3//! A `Context<B>` is the object you run work through. You create it *first*, at
4//! the very beginning of a unit of work, and thread it — `&mut` — into every
5//! action. It carries a stable [`ContextId`] (a correlation id for logging and
6//! tracing), an optional acting principal, and a backend `B` of your choosing.
7//!
8//! The backend is the point of this generic: **`B` decides what the context can
9//! do.** The one capability the core defines is persistence:
10//!
11//! * [`Store`] — persistence. The CRUD [`Domain`](crate::Domain) actions
12//!   (`create` / `read` / `update` / `destroy`) require `B: Store`, which hands
13//!   them a [`DataLayer`] to run against.
14//!
15//! Anything richer — transactions, batching, savepoints, a unit-of-work — is
16//! **the consumer's to define**: implement a [`DataLayer`] with the extra
17//! methods you need and a backend (a `Store`) that drives them, then add the
18//! lifecycle methods to *your* type. The core deliberately ships no transaction
19//! machinery, so it imposes no lifecycle you must fit.
20//!
21//! Alongside its backend, a context carries two open-ended bags any operation
22//! threaded through it can write to:
23//!
24//! * [`Extensions`] — a type-indexed bag of *live* values ([`insert`](Context::insert)
25//!   / [`get`](Context::get)): a request id, a recorded policy decision, a db or
26//!   cache client, a logger. One value per Rust type, fully typed.
27//! * `meta` — a string-keyed [`Record`] of dynamic, serializable values
28//!   ([`set_meta`](Context::set_meta) / [`get_meta`](Context::get_meta)) for
29//!   trace ids, flags, and arbitrary annotations.
30//!
31//! So the shape of your context is a compile-time choice. Persisting work? Any
32//! `Arc<L>` over a [`DataLayer`] `L` is a `Store`, so it is a ready-made backend
33//! — `Context::new(Arc::new(layer))` — and the CRUD actions light up. Just
34//! processing data, with no storage? Use a backend that is not a `Store` —
35//! `Context<()>` is the degenerate case — and the CRUD methods are simply not
36//! there to call.
37//!
38//! ```
39//! use std::sync::Arc;
40//! use ash_domain::{Context, Record, Value, DataLayer, Store};
41//! use ash_domain::datalayer::memory::InMemoryDataLayer;
42//!
43//! let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
44//! rt.block_on(async {
45//!     let layer = Arc::new(InMemoryDataLayer::new());
46//!
47//!     // A persistence-backed context: created up front, threaded `&mut`.
48//!     // `Arc<InMemoryDataLayer>` is a `Store`, so it is a backend directly.
49//!     let mut ctx = Context::new(layer.clone());
50//!
51//!     ctx.backend()
52//!         .layer()
53//!         .create("note", "id", Record::from_iter([("id", "1"), ("title", "a")]))
54//!         .await
55//!         .unwrap();
56//!     assert!(layer.get("note", "id", &Value::from("1")).await.unwrap().is_some());
57//!
58//!     // A store-less context: the CRUD actions won't accept it.
59//!     let _process_only = Context::new(());
60//! });
61//! ```
62
63use std::any::{Any, TypeId};
64use std::collections::HashMap;
65use std::sync::Arc;
66use std::sync::atomic::{AtomicU64, Ordering};
67use std::time::{SystemTime, UNIX_EPOCH};
68
69use crate::datalayer::DataLayer;
70use crate::error::Result;
71use crate::value::{Record, Value};
72
73/// A unique identifier for a [`Context`] — a correlation id.
74#[derive(Clone, Debug, PartialEq, Eq, Hash)]
75pub struct ContextId(String);
76
77impl ContextId {
78    /// Generate a fresh, process-unique id.
79    pub fn generate() -> Self {
80        static SEQ: AtomicU64 = AtomicU64::new(0);
81        let nanos = SystemTime::now()
82            .duration_since(UNIX_EPOCH)
83            .map(|d| d.as_nanos())
84            .unwrap_or(0);
85        let seq = SEQ.fetch_add(1, Ordering::Relaxed);
86        ContextId(format!("ctx-{nanos}-{seq}"))
87    }
88
89    /// Wrap an existing id string (e.g. a request id propagated from upstream).
90    pub fn new(id: impl Into<String>) -> Self {
91        ContextId(id.into())
92    }
93
94    /// The id as a string slice.
95    pub fn as_str(&self) -> &str {
96        &self.0
97    }
98}
99
100impl std::fmt::Display for ContextId {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        f.write_str(&self.0)
103    }
104}
105
106/// A type-indexed bag of arbitrary values carried by a [`Context`].
107///
108/// This is how work threaded through a context accumulates *live* state that the
109/// backend generic doesn't model: a request id set by an HTTP layer, a policy
110/// decision recorded by an authorization check, a database or cache client to be
111/// reused downstream, a logger or span. Each value is keyed by its own Rust
112/// type, so there is **at most one value per type** and reads are fully typed —
113/// no string keys, no downcasting at the call site. This is the same pattern as
114/// `http::Extensions`.
115///
116/// Values must be `Send + Sync + 'static` so the context (and everything it
117/// carries) can cross `await` points and move between threads.
118///
119/// ```
120/// use ash_domain::Extensions;
121///
122/// #[derive(Debug, PartialEq)]
123/// struct RequestId(String);
124///
125/// let mut ext = Extensions::new();
126/// ext.insert(RequestId("abc-123".into()));
127///
128/// assert_eq!(ext.get::<RequestId>(), Some(&RequestId("abc-123".into())));
129/// assert!(ext.get::<u64>().is_none());
130/// ```
131#[derive(Default)]
132pub struct Extensions {
133    map: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
134}
135
136impl Extensions {
137    /// An empty bag.
138    pub fn new() -> Self {
139        Self::default()
140    }
141
142    /// Insert a value, keyed by its type. Returns the previous value of the same
143    /// type, if one was present.
144    pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
145        self.map
146            .insert(TypeId::of::<T>(), Box::new(value))
147            .and_then(downcast_owned)
148    }
149
150    /// Borrow the value of type `T`, if one is present.
151    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
152        self.map
153            .get(&TypeId::of::<T>())
154            .and_then(|b| b.downcast_ref())
155    }
156
157    /// Mutably borrow the value of type `T`, if one is present.
158    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
159        self.map
160            .get_mut(&TypeId::of::<T>())
161            .and_then(|b| b.downcast_mut())
162    }
163
164    /// Whether a value of type `T` is present.
165    pub fn contains<T: Send + Sync + 'static>(&self) -> bool {
166        self.map.contains_key(&TypeId::of::<T>())
167    }
168
169    /// Remove and return the value of type `T`, if one is present.
170    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
171        self.map.remove(&TypeId::of::<T>()).and_then(downcast_owned)
172    }
173
174    /// Move every value out of `other` into this bag, consuming it.
175    ///
176    /// A type present in both is **overwritten by `other`'s** value: the bag
177    /// being merged in is the newer, more specific one (a handler's scratch
178    /// merging back into the request context), so it wins.
179    ///
180    /// ```
181    /// use ash_domain::Extensions;
182    /// #[derive(Debug, PartialEq)] struct Timing(u64);
183    /// #[derive(Debug, PartialEq)] struct Tag(&'static str);
184    ///
185    /// let mut parent = Extensions::new();
186    /// parent.insert(Timing(1));
187    /// parent.insert(Tag("parent"));
188    ///
189    /// let mut scratch = Extensions::new();
190    /// scratch.insert(Timing(99));
191    ///
192    /// parent.merge(scratch);
193    /// assert_eq!(parent.get::<Timing>(), Some(&Timing(99))); // scratch wins
194    /// assert_eq!(parent.get::<Tag>(), Some(&Tag("parent"))); // untouched
195    /// ```
196    pub fn merge(&mut self, other: Extensions) {
197        self.map.extend(other.map);
198    }
199
200    /// Whether the bag holds no values.
201    pub fn is_empty(&self) -> bool {
202        self.map.is_empty()
203    }
204
205    /// How many values the bag holds.
206    pub fn len(&self) -> usize {
207        self.map.len()
208    }
209}
210
211impl std::fmt::Debug for Extensions {
212    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213        f.debug_struct("Extensions")
214            .field("len", &self.map.len())
215            .finish()
216    }
217}
218
219fn downcast_owned<T: 'static>(boxed: Box<dyn Any + Send + Sync>) -> Option<T> {
220    boxed.downcast().ok().map(|b| *b)
221}
222
223/// The **domain-scoped** bag of shared clients, owned by the
224/// [`Domain`](crate::Domain) for its whole lifetime.
225///
226/// Where an [`Extensions`] bag on a [`Context`] is *request-scoped* (one unit of
227/// work), a `DomainContext` holds the long-lived handles a domain and its
228/// handlers reuse across every operation: an HTTP client, a database or cache
229/// pool, a message-bus producer, an external policy-service client. It is passed
230/// to [`Domain::new`](crate::Domain::new) and stored there.
231///
232/// Clients are keyed by type (the same primitive as [`Extensions`]), so there is
233/// **at most one client per type** and handler code retrieves one with no string
234/// keys or downcasts:
235///
236/// ```
237/// use ash_domain::DomainContext;
238///
239/// #[derive(Debug, PartialEq)]
240/// struct HttpClient(&'static str);
241/// #[derive(Debug, PartialEq)]
242/// struct CachePool(u32);
243///
244/// let dc = DomainContext::new()
245///     .with(HttpClient("https://api"))
246///     .with(CachePool(16));
247///
248/// assert_eq!(dc.client::<HttpClient>(), Some(&HttpClient("https://api")));
249/// assert_eq!(dc.client::<CachePool>(), Some(&CachePool(16)));
250/// assert!(dc.client::<u64>().is_none());
251/// ```
252///
253/// A handler reaches these through its
254/// [`HandlerContext::client`](HandlerContext::client), which projects them out
255/// of the domain that owns this bag.
256///
257/// Each client must be `Send + Sync + 'static` (typically a cheap-to-clone
258/// `Arc`-backed handle), so the domain — and everything it lends to handlers
259/// across threads and `await` points — stays `Send + Sync`.
260#[derive(Default)]
261pub struct DomainContext {
262    clients: Extensions,
263    /// Clients that opted into shutdown via [`Closable`](crate::lifecycle::Closable),
264    /// in registration order. [`Domain::close`](crate::Domain::close) drives these
265    /// in **reverse** of this order. Kept separate from `clients` because closing
266    /// is opt-in: a client is registered here *only* through
267    /// [`with_closable`](DomainContext::with_closable) / [`insert_closable`](DomainContext::insert_closable).
268    closables: Vec<crate::lifecycle::ClosableHandle>,
269}
270
271impl DomainContext {
272    /// An empty bag — a domain with no shared clients.
273    pub fn new() -> Self {
274        Self::default()
275    }
276
277    /// Register `client`, keyed by its type (builder style). A later `with` of
278    /// the same type replaces the earlier one.
279    pub fn with<T: Send + Sync + 'static>(mut self, client: T) -> Self {
280        self.clients.insert(client);
281        self
282    }
283
284    /// Register `client` both as a type-keyed shared client (like
285    /// [`with`](DomainContext::with)) **and** as a
286    /// [`Closable`](crate::lifecycle::Closable) that
287    /// [`Domain::close`](crate::Domain::close) will shut down.
288    ///
289    /// Use this for clients that hold real resources needing orderly release —
290    /// a connection pool, a message-broker producer, a socket. On close they are
291    /// shut down in **reverse** registration order (last registered, first
292    /// closed). The client is retrievable by type exactly as with `with`.
293    pub fn with_closable<T>(mut self, client: T) -> Self
294    where
295        T: crate::lifecycle::Closable + Clone,
296    {
297        self.insert_closable(client);
298        self
299    }
300
301    /// In-place form of [`with_closable`](DomainContext::with_closable): register
302    /// `client` as both a type-keyed client and a shutdown target. Returns the
303    /// previous client of the same type, if one was present (its `Closable`
304    /// registration, if any, is left in the shutdown list — closing a
305    /// superseded handle is harmless given the idempotent contract).
306    pub fn insert_closable<T>(&mut self, client: T) -> Option<T>
307    where
308        T: crate::lifecycle::Closable + Clone,
309    {
310        self.closables.push(Arc::new(client.clone()));
311        self.clients.insert(client)
312    }
313
314    /// The registered [`Closable`](crate::lifecycle::Closable) clients, in
315    /// registration order. [`Domain::close`](crate::Domain::close) is the normal
316    /// caller; exposed so service code can inspect how many shutdown targets a
317    /// domain carries.
318    pub(crate) fn closables(&self) -> &[crate::lifecycle::ClosableHandle] {
319        &self.closables
320    }
321
322    /// Register `client` in place, returning the previous client of the same
323    /// type, if any.
324    pub fn insert<T: Send + Sync + 'static>(&mut self, client: T) -> Option<T> {
325        self.clients.insert(client)
326    }
327
328    /// Borrow the client of type `T`, if one was registered.
329    pub fn client<T: Send + Sync + 'static>(&self) -> Option<&T> {
330        self.clients.get::<T>()
331    }
332
333    /// Whether a client of type `T` is registered.
334    pub fn has<T: Send + Sync + 'static>(&self) -> bool {
335        self.clients.contains::<T>()
336    }
337
338    /// How many clients are registered.
339    pub fn len(&self) -> usize {
340        self.clients.len()
341    }
342
343    /// Whether no clients are registered.
344    pub fn is_empty(&self) -> bool {
345        self.clients.is_empty()
346    }
347}
348
349impl std::fmt::Debug for DomainContext {
350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        f.debug_struct("DomainContext")
352            .field("clients", &self.clients.len())
353            .field("closables", &self.closables.len())
354            .finish()
355    }
356}
357
358/// Project a value of type `Self` *out of* a composite backend `B`.
359///
360/// This is ash-domain's analogue of axum's `FromRef`. A context carries **one**
361/// backend `B` ([`Context::backend`]), but a real application's backend is
362/// usually a bundle — a data layer *and* a cache client *and* a metrics handle.
363/// `FromRef` lets each of those be extracted from the one `B` by type, so code
364/// asks for the piece it needs ([`ctx.extract::<Cache>()`](Context::extract))
365/// without knowing the shape of the whole backend.
366///
367/// It is the composition seam that keeps `B` from having to be monolithic: your
368/// backend is one `AppState` struct, you implement `FromRef<AppState>` for each
369/// utility it holds (cheap `.clone()`s of `Arc`-shared handles), and both the
370/// CRUD [`Store`] and your own code pull what they need out of the same value.
371///
372/// Every type is trivially projectable from itself (the reflexive blanket impl
373/// below), so a single-utility backend needs no impl at all —
374/// `ctx.extract::<B>()` clones the backend. Provide impls only to expose the
375/// *parts* of a composite backend.
376///
377/// ```
378/// use std::sync::Arc;
379/// use ash_domain::{Context, FromRef};
380///
381/// #[derive(Clone)]
382/// struct Cache(Arc<str>);
383/// #[derive(Clone)]
384/// struct Metrics(u64);
385///
386/// // One backend bundling several utilities.
387/// #[derive(Clone)]
388/// struct AppState { cache: Cache, metrics: Metrics }
389///
390/// impl FromRef<AppState> for Cache {
391///     fn from_ref(state: &AppState) -> Self { state.cache.clone() }
392/// }
393/// impl FromRef<AppState> for Metrics {
394///     fn from_ref(state: &AppState) -> Self { state.metrics.clone() }
395/// }
396///
397/// let ctx = Context::new(AppState { cache: Cache("redis".into()), metrics: Metrics(0) });
398/// let cache: Cache = ctx.extract::<Cache>();       // projected out of the bundle
399/// assert_eq!(&*cache.0, "redis");
400/// let _metrics: Metrics = ctx.extract();
401/// ```
402pub trait FromRef<B> {
403    /// Extract a `Self` from a reference to the composite backend `B`.
404    fn from_ref(backend: &B) -> Self;
405}
406
407/// Every backend is projectable from itself: `ctx.extract::<B>()` clones it.
408/// This is what lets a single-utility backend skip `FromRef` impls entirely,
409/// and it is why the CRUD [`Store`] path is unaffected by projection.
410impl<B: Clone> FromRef<B> for B {
411    fn from_ref(backend: &B) -> Self {
412        backend.clone()
413    }
414}
415
416/// The persistence capability of a context's backend.
417///
418/// A backend that can store records implements `Store`; the CRUD
419/// [`Domain`](crate::Domain) actions take a `Context<impl Store>` and reach the
420/// storage through [`layer`](Store::layer). A backend that does *not* implement
421/// `Store` (for example `()`) cannot be passed to those actions at all — the
422/// bound is not satisfied — which is how a store-less context statically opts
423/// out of persistence.
424///
425/// Any `Arc<L>` over a [`DataLayer`] `L` is a `Store` (see the blanket impl
426/// below), so a bare data layer is a usable backend with no wrapper. When you
427/// want richer behaviour around persistence — transactions, batching, a
428/// unit-of-work — define your own type, implement `Store` for it (returning the
429/// [`DataLayer`] to run against), and give that type whatever lifecycle methods
430/// the behaviour needs. The core takes no position on that lifecycle.
431#[async_trait::async_trait]
432pub trait Store: Send + Sync {
433    /// The [`DataLayer`] the CRUD actions run against.
434    fn layer(&self) -> &dyn DataLayer;
435
436    /// **Optional atomicity capability:** open a [`Transaction`](crate::Transaction) the write
437    /// pipeline runs inside, or `Ok(None)` (the default) to decline.
438    ///
439    /// When a store returns `Some(txn)`, the [`Domain`](crate::Domain) persists
440    /// and runs `after_action` extensions **through the transaction**, then
441    /// [`commit`](crate::datalayer::Transaction::commit)s — so a failure anywhere
442    /// before the commit rolls the write back instead of leaving it durable. When
443    /// it returns `None`, the pipeline uses the bare [`layer`](Store::layer) and
444    /// keeps today's behaviour (persist commits immediately; a later failure can
445    /// return `Err` on a committed row). Event delivery stays post-commit and
446    /// best-effort in **both** paths — atomic event delivery needs an outbox,
447    /// which is a consumer concern.
448    ///
449    /// The default declines, so every existing backend is unaffected. Override it
450    /// to opt a store into transactional writes. See `docs/transaction-seam.md`.
451    async fn begin(&self) -> Result<Option<Box<dyn crate::datalayer::Transaction>>> {
452        Ok(None)
453    }
454}
455
456/// A bare data layer, shared via `Arc`, is a ready-made [`Store`] backend: no
457/// wrapper type needed for the common case of "persist straight through to this
458/// layer". `Context::new(Arc::new(my_layer))` just works.
459impl<L: DataLayer> Store for Arc<L> {
460    fn layer(&self) -> &dyn DataLayer {
461        &**self
462    }
463}
464
465/// The mutable unit of work, generic over its backend `B`.
466///
467/// See the [module docs](self) for the capability model. Construct one with
468/// [`new`](Context::new), set an actor if you have one, and thread it `&mut`
469/// through the [`Domain`](crate::Domain) actions.
470pub struct Context<B> {
471    id: ContextId,
472    actor: Option<Record>,
473    tenant: Option<Value>,
474    cross_tenant: bool,
475    extensions: Extensions,
476    meta: Record,
477    backend: B,
478}
479
480impl<B> Context<B> {
481    /// Create a context over `backend`, with a freshly-generated id.
482    pub fn new(backend: B) -> Self {
483        Self::with_id(backend, ContextId::generate())
484    }
485
486    /// Create a context over `backend` with an explicit id (e.g. a propagated
487    /// correlation id).
488    pub fn with_id(backend: B, id: ContextId) -> Self {
489        Self {
490            id,
491            actor: None,
492            tenant: None,
493            cross_tenant: false,
494            extensions: Extensions::new(),
495            meta: Record::new(),
496            backend,
497        }
498    }
499
500    /// Set the acting principal, chaining — the construction-time form of
501    /// [`set_actor`](Context::set_actor), for the per-request path where a
502    /// context is built, populated, and used in one expression:
503    ///
504    /// ```
505    /// # use ash_domain::{Context, Record};
506    /// # use ash_domain::datalayer::memory::InMemoryDataLayer;
507    /// # use std::sync::Arc;
508    /// let ctx = Context::new(Arc::new(InMemoryDataLayer::new()))
509    ///     .with_actor(Record::from_iter([("id", "u1"), ("role", "admin")]))
510    ///     .with_tenant("acme");
511    /// # let _ = ctx;
512    /// ```
513    pub fn with_actor(mut self, actor: Record) -> Self {
514        self.actor = Some(actor);
515        self
516    }
517
518    /// Scope this unit of work to a tenant, chaining — the construction-time
519    /// form of [`set_tenant`](Context::set_tenant). See
520    /// [`with_actor`](Context::with_actor) for the intended shape.
521    pub fn with_tenant(mut self, tenant: impl Into<Value>) -> Self {
522        self.tenant = Some(tenant.into());
523        self
524    }
525
526    /// This context's unique id.
527    pub fn id(&self) -> &ContextId {
528        &self.id
529    }
530
531    /// The acting principal, if set.
532    ///
533    /// The actor is an opaque [`Record`] — **the core defines no identity type**
534    /// (no `User`, session, token, or credential). It only carries whatever
535    /// record you set here to the [`Policy`](crate::Policy) seam. That is the
536    /// whole authentication contract: an auth library (an `ash-auth`) is a
537    /// *consumer-side* concern that verifies credentials however it likes — its
538    /// own tables, its own hashing, its own token format — and then calls
539    /// [`set_actor`](Context::set_actor) with a record of whatever shape it
540    /// chooses. Nothing about identity is locked to `ash-domain`; swap the auth
541    /// library and the core is unaffected.
542    pub fn actor(&self) -> Option<&Record> {
543        self.actor.as_ref()
544    }
545
546    /// Set the acting principal — the record an auth layer produces after
547    /// verifying a request. Its shape is entirely the caller's; the core treats
548    /// it as opaque and only hands it to policies. See [`actor`](Context::actor).
549    pub fn set_actor(&mut self, actor: Record) {
550        self.actor = Some(actor);
551    }
552
553    /// The tenant this unit of work is scoped to, if any.
554    ///
555    /// A [`Domain`](crate::Domain) action on a resource that declares a tenant
556    /// strategy ([`Resource::tenant`](crate::Resource::tenant)) reads this to
557    /// scope storage: stamping it onto created records and filtering reads,
558    /// updates, and destroys by it. A resource with no tenant strategy ignores
559    /// it entirely.
560    pub fn tenant(&self) -> Option<&Value> {
561        self.tenant.as_ref()
562    }
563
564    /// Scope this unit of work to a tenant. Threaded into every subsequent action
565    /// on a tenant-scoped resource until [`clear_tenant`](Context::clear_tenant).
566    pub fn set_tenant(&mut self, tenant: impl Into<Value>) {
567        self.tenant = Some(tenant.into());
568    }
569
570    /// Remove the tenant scope.
571    pub fn clear_tenant(&mut self) {
572        self.tenant = None;
573    }
574
575    /// Whether this unit of work may **read across tenants** — the sanctioned,
576    /// visible escape from tenant scoping for a legitimate global/admin read.
577    ///
578    /// Defaults to `false`. See [`allow_cross_tenant`](Context::allow_cross_tenant)
579    /// for the exact contract; the [`Domain`](crate::Domain) read paths consult
580    /// this, writes never do.
581    pub fn is_cross_tenant(&self) -> bool {
582        self.cross_tenant
583    }
584
585    /// Opt this unit of work into reading **across all tenants**, dropping the
586    /// tenant predicate the domain would otherwise fold into a
587    /// [`read`](crate::Domain::handle_action) of a tenant-scoped resource.
588    ///
589    /// This is the deliberate, auditable seam for a global/admin read — the *only*
590    /// sanctioned way past tenant scoping, so such a read is a visible call at the
591    /// site rather than a raw query smuggled around the guard. Its contract is
592    /// narrow on purpose:
593    ///
594    /// * **Reads only.** Create / update / destroy ignore it and still fail-closed:
595    ///   a write needs a tenant ([`MissingTenant`](crate::Error::MissingTenant)),
596    ///   is stamped into it, and a cross-tenant update/destroy is still `NotFound`.
597    ///   A [`TypedQuery`](crate::query_type::TypedQuery) must additionally opt in
598    ///   with `tenant_aware`, which under this flag means "scoped to *all* tenants".
599    /// * **Authorization still runs.** The flag removes the tenant *predicate*, not
600    ///   the policy gate — a caller with no admitting read policy is still
601    ///   [`Forbidden`](crate::Error::Forbidden). Gate this behind an admin policy.
602    /// * **Visible downstream.** The domain records the intent on the
603    ///   [`Query`](crate::Query::across_tenants) it hands the layer, so a data
604    ///   layer (and audit) can see a cross-tenant read for what it is.
605    ///
606    /// Stays set until [`deny_cross_tenant`](Context::deny_cross_tenant).
607    pub fn allow_cross_tenant(&mut self) {
608        self.cross_tenant = true;
609    }
610
611    /// Re-scope this unit of work to its tenant, undoing
612    /// [`allow_cross_tenant`](Context::allow_cross_tenant).
613    pub fn deny_cross_tenant(&mut self) {
614        self.cross_tenant = false;
615    }
616
617    /// The typed extension bag: live values keyed by their Rust type — request
618    /// ids, policy decisions, clients, loggers. See [`Extensions`].
619    pub fn extensions(&self) -> &Extensions {
620        &self.extensions
621    }
622
623    /// Mutably borrow the [extension bag](Extensions).
624    pub fn extensions_mut(&mut self) -> &mut Extensions {
625        &mut self.extensions
626    }
627
628    /// Merge a finished [`HandlerContext`]'s scratch bag into this context's
629    /// [extension bag](Extensions) — the merge-back the
630    /// [`Domain`](crate::Domain) performs after a generic action's handler
631    /// returns.
632    ///
633    /// This is what makes handler enrichment (a policy decision it observed, a
634    /// timing, a downstream client it opened) reachable by the caller once the
635    /// action is over. A type the handler recorded **overwrites** the same type
636    /// already in the context: the handler ran later and saw more.
637    ///
638    /// The merge happens only on the handler's **success** path. A handler that
639    /// returned `Err` had its action fail, and the core does not half-apply a
640    /// failed action's observations to the request that outlived it.
641    pub fn merge_scratch(&mut self, scratch: Extensions) {
642        self.extensions.merge(scratch);
643    }
644
645    /// Stash a value in the [extension bag](Extensions), keyed by its type.
646    /// Returns the previous value of the same type, if any. Shorthand for
647    /// `ctx.extensions_mut().insert(value)`.
648    pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
649        self.extensions.insert(value)
650    }
651
652    /// Borrow a value of type `T` from the [extension bag](Extensions), if
653    /// present. Shorthand for `ctx.extensions().get::<T>()`.
654    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
655        self.extensions.get::<T>()
656    }
657
658    /// Read-only view of the string-keyed metadata bag: dynamic, serializable
659    /// values (trace ids, feature flags, arbitrary annotations) carried
660    /// alongside the typed [extensions](Extensions).
661    pub fn meta(&self) -> &Record {
662        &self.meta
663    }
664
665    /// Set a string-keyed metadata value.
666    pub fn set_meta(&mut self, key: impl Into<String>, value: impl Into<Value>) {
667        self.meta.insert(key, value);
668    }
669
670    /// Look up a string-keyed metadata value.
671    pub fn get_meta(&self, key: &str) -> Option<&Value> {
672        self.meta.get(key)
673    }
674
675    /// Borrow the backend.
676    pub fn backend(&self) -> &B {
677        &self.backend
678    }
679
680    /// Mutably borrow the backend.
681    pub fn backend_mut(&mut self) -> &mut B {
682        &mut self.backend
683    }
684
685    /// Project a utility of type `T` out of the backend by value.
686    ///
687    /// This is the axum-`State` move: the context holds one composite backend,
688    /// and `extract` pulls a named piece out of it via [`FromRef`]. A data
689    /// layer, a cache client, a metrics handle — each is `ctx.extract::<T>()`,
690    /// regardless of how the backend bundles them. `T = B` works with no impl
691    /// (the reflexive [`FromRef`] clones the whole backend); expose parts of a
692    /// composite backend by implementing `FromRef<B>` for each.
693    ///
694    /// Extraction is by value — utilities are meant to be cheap-to-clone shared
695    /// handles (`Arc`-backed pools, clients), the same contract axum places on
696    /// its state.
697    pub fn extract<T: FromRef<B>>(&self) -> T {
698        T::from_ref(&self.backend)
699    }
700
701    /// Consume the context and return its backend.
702    pub fn into_backend(self) -> B {
703        self.backend
704    }
705}
706
707/// A short-lived, **derived** context handed to a handler for the span of a
708/// single operation.
709///
710/// Where a [`Context<B>`] is the caller's long-lived unit of work, a
711/// `HandlerContext` is the *inner* view the [`Domain`](crate::Domain) builds
712/// around one action while its handler runs, and drops when the action returns.
713/// It exists to give handler code a richer, scoped surface than the bare
714/// [`Changeset`](crate::action::Changeset) + [`Store`] pair without exposing (or
715/// letting a handler mutate) the whole parent context.
716///
717/// It carries:
718///
719/// * a borrow of the [`Domain`](crate::Domain), so a handler can introspect
720///   registered resources and the [`policy tree`](crate::Domain::policy_tree) —
721///   and, later, re-enter the domain to run nested actions;
722/// * **read-only** projections of the parent context's request state — the
723///   [`actor`](HandlerContext::actor), [`tenant`](HandlerContext::tenant),
724///   [`id`](HandlerContext::id), and [`meta`](HandlerContext::meta);
725/// * the optional [`Store`] the handler reads/writes through;
726/// * its **own** [`scratch`](HandlerContext::scratch) bag — a fresh
727///   [`Extensions`] the handler writes enrichment into (policy results it
728///   observed, logs, timings). It starts **empty** rather than inheriting the
729///   parent's bag, so a handler cannot mutate request state mid-action; what it
730///   records is merged back into the parent context by
731///   [`Context::merge_scratch`](Context::merge_scratch) *after* the handler
732///   returns, where the caller can read it.
733///
734/// Once the operation is done the [`Domain`](crate::Domain) calls
735/// [`complete`](HandlerContext::complete), which **consumes** the context (and
736/// hands back its scratch bag). Spent-context reuse is therefore a *compile
737/// error*, not a runtime panic: the handler only ever borrows the context, so it
738/// cannot keep it, and after `complete` there is no context left to misuse. The
739/// lifetime `'a` additionally ties the borrows to the parent context and domain,
740/// so a `HandlerContext` cannot outlive the operation it was derived for.
741pub struct HandlerContext<'a> {
742    domain: &'a crate::Domain,
743    id: &'a ContextId,
744    actor: Option<&'a Record>,
745    tenant: Option<&'a Value>,
746    meta: &'a Record,
747    store: Option<&'a dyn Store>,
748    scratch: Extensions,
749}
750
751impl<'a> HandlerContext<'a> {
752    /// Derive a handler context from its parts. Called by the
753    /// [`Domain`](crate::Domain) when it is about to run a handler; not usually
754    /// constructed by consumer code.
755    pub fn new(
756        domain: &'a crate::Domain,
757        id: &'a ContextId,
758        actor: Option<&'a Record>,
759        tenant: Option<&'a Value>,
760        meta: &'a Record,
761        store: Option<&'a dyn Store>,
762    ) -> Self {
763        Self {
764            domain,
765            id,
766            actor,
767            tenant,
768            meta,
769            store,
770            scratch: Extensions::new(),
771        }
772    }
773
774    /// The domain this operation runs within — for introspection now, re-entry
775    /// later.
776    pub fn domain(&self) -> &'a crate::Domain {
777        self.domain
778    }
779
780    /// Borrow a shared client of type `T` from the domain's
781    /// [`DomainContext`], if one was registered when the
782    /// domain was built.
783    ///
784    /// This is how a handler reaches the long-lived, domain-scoped handles — an
785    /// HTTP client, a cache pool, an external service client — rather than
786    /// receiving them per call. Returns `None` when no client of that type is
787    /// registered.
788    ///
789    /// ```
790    /// # use ash_domain::HandlerContext;
791    /// # struct HttpClient;
792    /// # fn use_it(ctx: &HandlerContext<'_>) {
793    /// if let Some(_http) = ctx.client::<HttpClient>() {
794    ///     // call out through the shared client…
795    /// }
796    /// # }
797    /// ```
798    pub fn client<T: Send + Sync + 'static>(&self) -> Option<&'a T> {
799        self.domain.domain_context().client::<T>()
800    }
801
802    /// The parent context's correlation id.
803    pub fn id(&self) -> &ContextId {
804        self.id
805    }
806
807    /// The acting principal, if the parent context had one (read-only).
808    pub fn actor(&self) -> Option<&Record> {
809        self.actor
810    }
811
812    /// The tenant this operation is scoped to, if any (read-only).
813    pub fn tenant(&self) -> Option<&Value> {
814        self.tenant
815    }
816
817    /// The parent context's string-keyed metadata (read-only).
818    pub fn meta(&self) -> &Record {
819        self.meta
820    }
821
822    /// Look up a parent metadata value by key.
823    pub fn get_meta(&self, key: &str) -> Option<&Value> {
824        self.meta.get(key)
825    }
826
827    /// The [`Store`] the handler runs against, if this operation was invoked on a
828    /// persistence-backed context. Mirrors the `store` argument handlers already
829    /// receive.
830    pub fn store(&self) -> Option<&dyn Store> {
831        self.store
832    }
833
834    /// The handler's own scratch bag — enrichment produced *during* this
835    /// operation (policy results, logs, timings), keyed by type like
836    /// [`Extensions`]. The domain merges it back into the request
837    /// [`Context`] once the handler returns; see
838    /// [`complete`](HandlerContext::complete).
839    pub fn scratch(&self) -> &Extensions {
840        &self.scratch
841    }
842
843    /// Mutably borrow the [`scratch`](HandlerContext::scratch) bag to record
844    /// enrichment.
845    pub fn scratch_mut(&mut self) -> &mut Extensions {
846        &mut self.scratch
847    }
848
849    /// Stash a value in the [`scratch`](HandlerContext::scratch) bag, keyed by
850    /// its type. Returns the previous value of the same type, if any.
851    pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
852        self.scratch.insert(value)
853    }
854
855    /// Borrow a value of type `T` from the [`scratch`](HandlerContext::scratch)
856    /// bag, if present.
857    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
858        self.scratch.get::<T>()
859    }
860
861    /// Mark the operation done by **consuming** the context, returning its
862    /// scratch bag for the domain to merge into the request [`Context`] via
863    /// [`Context::merge_scratch`](Context::merge_scratch). Called by the
864    /// [`Domain`](crate::Domain) once the handler has produced its result.
865    ///
866    /// Because this takes `self`, a spent context cannot be reused — there is
867    /// nothing left to call. Handlers only ever borrow the context (`&mut`), so
868    /// they can neither complete it early nor hold it past their run; the
869    /// exclusive right to finish it stays with the domain, enforced by the
870    /// compiler rather than a runtime flag.
871    pub fn complete(self) -> Extensions {
872        self.scratch
873    }
874
875    /// Serialize the context's representable state to a JSON string — the form a
876    /// handler returns *alongside* its result. The context is **not** fed back
877    /// into the domain; this snapshot is the only thing that travels out.
878    ///
879    /// This is a **basic** implementation: it captures the fields that have a
880    /// natural serial form — the [`id`](HandlerContext::id), `actor`, `tenant`,
881    /// and `meta`. The typed [`scratch`](HandlerContext::scratch) bag holds
882    /// arbitrary `dyn Any` values that cannot be serialized generically, so it is
883    /// represented only by its entry **count** (`scratch_len`). A handler that
884    /// wants specific scratch values in the output should serialize them itself,
885    /// or a future revision can let entries opt into serialization.
886    ///
887    /// ```json
888    /// {
889    ///   "id": "ctx-… ",
890    ///   "actor": { … } | null,
891    ///   "tenant": <value> | null,
892    ///   "meta": { … },
893    ///   "scratch_len": 2
894    /// }
895    /// ```
896    pub fn serialize(&self) -> String {
897        // Build a serde_json::Value by hand from the parts, reusing the existing
898        // Serialize impls on Record/Value. `serde_json::json!` keeps this basic
899        // and dependency-free beyond serde_json (already a dependency).
900        let snapshot = serde_json::json!({
901            "id": self.id.as_str(),
902            "actor": self.actor,
903            "tenant": self.tenant,
904            "meta": self.meta,
905            "scratch_len": self.scratch.len(),
906        });
907        serde_json::to_string(&snapshot).unwrap_or_else(|_| "{}".to_string())
908    }
909}
910
911#[cfg(test)]
912mod tests {
913    use super::*;
914
915    #[derive(Debug, PartialEq)]
916    struct RequestId(String);
917
918    #[derive(Debug, PartialEq)]
919    enum PolicyDecision {
920        Allow,
921        Deny,
922    }
923
924    #[test]
925    fn extensions_insert_get_by_type() {
926        let mut ext = Extensions::new();
927        assert!(ext.is_empty());
928
929        assert!(ext.insert(RequestId("r-1".into())).is_none());
930        assert!(ext.insert(PolicyDecision::Allow).is_none());
931
932        assert_eq!(ext.len(), 2);
933        assert_eq!(ext.get::<RequestId>(), Some(&RequestId("r-1".into())));
934        assert_eq!(ext.get::<PolicyDecision>(), Some(&PolicyDecision::Allow));
935        assert!(ext.get::<u64>().is_none());
936    }
937
938    #[test]
939    fn extensions_insert_replaces_and_returns_prior() {
940        let mut ext = Extensions::new();
941        ext.insert(RequestId("first".into()));
942        let prev = ext.insert(RequestId("second".into()));
943        assert_eq!(prev, Some(RequestId("first".into())));
944        assert_eq!(ext.get::<RequestId>(), Some(&RequestId("second".into())));
945        assert_eq!(ext.len(), 1);
946    }
947
948    #[test]
949    fn extensions_get_mut_and_remove() {
950        let mut ext = Extensions::new();
951        ext.insert(PolicyDecision::Allow);
952        *ext.get_mut::<PolicyDecision>().unwrap() = PolicyDecision::Deny;
953        assert_eq!(ext.get::<PolicyDecision>(), Some(&PolicyDecision::Deny));
954
955        assert_eq!(ext.remove::<PolicyDecision>(), Some(PolicyDecision::Deny));
956        assert!(!ext.contains::<PolicyDecision>());
957        assert!(ext.is_empty());
958    }
959
960    #[test]
961    fn context_carries_extensions_and_meta() {
962        let mut ctx = Context::new(());
963
964        ctx.insert(RequestId("req-42".into()));
965        ctx.set_meta("trace_id", "trace-abc");
966        ctx.set_meta("attempt", 3i64);
967
968        assert_eq!(ctx.get::<RequestId>(), Some(&RequestId("req-42".into())));
969        assert_eq!(
970            ctx.get_meta("trace_id").and_then(Value::as_str),
971            Some("trace-abc")
972        );
973        assert_eq!(ctx.get_meta("attempt").and_then(Value::as_int), Some(3));
974        assert!(ctx.get_meta("absent").is_none());
975    }
976
977    #[test]
978    fn from_ref_projects_parts_of_a_composite_backend() {
979        use crate::datalayer::memory::InMemoryDataLayer;
980
981        #[derive(Clone)]
982        struct Cache(&'static str);
983        #[derive(Clone)]
984        struct Metrics(u64);
985
986        // A composite backend: a data layer *and* two unrelated utilities.
987        #[derive(Clone)]
988        struct App {
989            db: Arc<InMemoryDataLayer>,
990            cache: Cache,
991            metrics: Metrics,
992        }
993
994        // It is a `Store` (CRUD reaches the db field)...
995        impl Store for App {
996            fn layer(&self) -> &dyn DataLayer {
997                &*self.db
998            }
999        }
1000        // ...and its utilities project out by type.
1001        impl FromRef<App> for Cache {
1002            fn from_ref(a: &App) -> Self {
1003                a.cache.clone()
1004            }
1005        }
1006        impl FromRef<App> for Metrics {
1007            fn from_ref(a: &App) -> Self {
1008                a.metrics.clone()
1009            }
1010        }
1011
1012        let ctx = Context::new(App {
1013            db: Arc::new(InMemoryDataLayer::new()),
1014            cache: Cache("redis"),
1015            metrics: Metrics(7),
1016        });
1017
1018        // Both the CRUD store and the side utilities come out of one backend.
1019        assert_eq!(ctx.extract::<Cache>().0, "redis");
1020        assert_eq!(ctx.extract::<Metrics>().0, 7);
1021        // The whole backend is still a Store — CRUD reaches the db field.
1022        fn assert_store<B: Store>(_: &Context<B>) {}
1023        assert_store(&ctx);
1024    }
1025
1026    #[test]
1027    fn extract_reflexive_clones_whole_backend() {
1028        #[derive(Clone, Debug, PartialEq)]
1029        struct Solo(u8);
1030        let ctx = Context::new(Solo(9));
1031        // No FromRef impl needed: the reflexive blanket clones the backend.
1032        assert_eq!(ctx.extract::<Solo>(), Solo(9));
1033    }
1034
1035    #[test]
1036    fn context_and_extensions_are_send_sync() {
1037        fn assert_send_sync<T: Send + Sync>() {}
1038        assert_send_sync::<Extensions>();
1039        assert_send_sync::<Context<()>>();
1040    }
1041}