Skip to main content

ash_jsonapi/
context.rs

1//! The per-request `Context`.
2//!
3//! Everything a request carries travels in one value, passed down explicitly:
4//! the correlation id, the authenticated principal, the tenant, and any
5//! metadata bound along the way. The `ash-log` scope lives *inside* it — see
6//! [`Context::scope`] — so callers never build one themselves.
7//!
8//! Explicit passing rather than a thread-local is deliberate. `ash_log::Scope`
9//! is bound per-thread, so it does not survive an `.await` that moves the task
10//! to another worker. A `Context` is owned data: it crosses await points and
11//! thread boundaries intact, and [`Context::scope`] re-enters the ash-log
12//! scope wherever the work actually lands.
13
14use std::any::{Any, TypeId};
15use std::collections::BTreeMap;
16use std::collections::HashMap;
17use std::sync::Arc;
18
19use crate::error::JsonApiError;
20
21/// Everything one request carries.
22///
23/// Cheap to clone: the fields sit behind an [`Arc`], so handing a `Context` to
24/// a nested call or another task copies a pointer.
25///
26/// ```ignore
27/// use ash_jsonapi::context::Context;
28///
29/// let ctx = Context::new("01H9K2QZ8V")
30///     .with_principal("alice@example.com")
31///     .with_tenant("acme");
32///
33/// assert_eq!(ctx.correlation_id(), "01H9K2QZ8V");
34/// assert_eq!(ctx.tenant(), Some("acme"));
35/// ```
36#[derive(Debug, Clone)]
37pub struct Context {
38    inner: Arc<Fields>,
39}
40
41#[derive(Debug, Clone)]
42struct Fields {
43    correlation_id: String,
44    principal: Option<String>,
45    tenant: Option<String>,
46    locale: Option<crate::i18n::Locale>,
47    metadata: BTreeMap<String, serde_json::Value>,
48    /// Typed values attached to this request — see [`Context::with`].
49    extensions: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
50}
51
52impl Context {
53    /// A context for one request, identified by its correlation id.
54    ///
55    /// The id is what ties a response back to the audit record, so it is
56    /// required rather than optional: it comes from the request's
57    /// `X-Request-Id` where the client sent one, and is generated otherwise.
58    pub fn new(correlation_id: impl Into<String>) -> Self {
59        Self {
60            inner: Arc::new(Fields {
61                correlation_id: correlation_id.into(),
62                principal: None,
63                tenant: None,
64                locale: None,
65                metadata: BTreeMap::new(),
66                extensions: HashMap::new(),
67            }),
68        }
69    }
70
71    /// Bind the authenticated principal.
72    ///
73    /// Absent until authentication has run — an unauthenticated request has a
74    /// context, just not a principal.
75    #[must_use]
76    pub fn with_principal(self, principal: impl Into<String>) -> Self {
77        self.map(|f| f.principal = Some(principal.into()))
78    }
79
80    /// Bind the tenant, extracted per the resource's `TenantStrategy`.
81    #[must_use]
82    pub fn with_tenant(self, tenant: impl Into<String>) -> Self {
83        self.map(|f| f.tenant = Some(tenant.into()))
84    }
85
86    /// Bind the locale the client asked for, negotiated from
87    /// `Accept-Language`.
88    ///
89    /// Set by [`layer()`](crate::layer()) on every request that sends the
90    /// header. Nothing in this crate translates — see [`i18n`](crate::i18n) —
91    /// so this records what was asked for, and is echoed on the response's
92    /// top-level `meta.lang`.
93    #[must_use]
94    pub fn with_locale(self, locale: crate::i18n::Locale) -> Self {
95        self.map(|f| f.locale = Some(locale))
96    }
97
98    /// The locale the client asked for, if it sent an `Accept-Language` this
99    /// crate could parse.
100    pub fn locale(&self) -> Option<&crate::i18n::Locale> {
101        self.inner.locale.as_ref()
102    }
103
104    /// Bind one metadata field, carried into every event logged under this
105    /// context.
106    #[must_use]
107    pub fn with_metadata(
108        self,
109        key: impl Into<String>,
110        value: impl Into<serde_json::Value>,
111    ) -> Self {
112        self.map(|f| {
113            f.metadata.insert(key.into(), value.into());
114        })
115    }
116
117    /// The correlation id. Always present.
118    pub fn correlation_id(&self) -> &str {
119        &self.inner.correlation_id
120    }
121
122    /// The authenticated principal, if authentication has run.
123    pub fn principal(&self) -> Option<&str> {
124        self.inner.principal.as_deref()
125    }
126
127    /// The tenant, if one was extracted.
128    pub fn tenant(&self) -> Option<&str> {
129        self.inner.tenant.as_deref()
130    }
131
132    /// Attach a typed value to this request.
133    ///
134    /// For what your own middleware resolves — an authenticated actor, a
135    /// tenant handle, a feature flag set — so a handler receives one
136    /// `Context` rather than a widening tuple. One value per type; attaching
137    /// a second of the same type replaces the first.
138    ///
139    /// A parsed request body does *not* travel this way: it is handed to
140    /// [`Create::create`](crate::crud::Create::create) as an argument, since
141    /// a create always has one and routing it through here would turn an
142    /// infallible step into a fallible lookup.
143    ///
144    /// ```ignore
145    /// // in middleware, after authenticating
146    /// let ctx = ctx.with(actor);
147    ///
148    /// // anywhere downstream
149    /// let actor: &Actor = ctx.extract()?;
150    /// ```
151    #[must_use]
152    pub fn with<T: Any + Send + Sync + 'static>(self, value: T) -> Self {
153        self.map(|fields| {
154            fields.extensions.insert(TypeId::of::<T>(), Arc::new(value));
155        })
156    }
157
158    /// The value of type `T` attached to this request, if any.
159    pub fn get_ext<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
160        self.inner
161            .extensions
162            .get(&TypeId::of::<T>())
163            .and_then(|value| value.downcast_ref::<T>())
164    }
165
166    /// The value of type `T`, or a `500` naming what was missing.
167    ///
168    /// An absent extension means a handler ran without the middleware or
169    /// extractor that should have attached it — a wiring bug, not a bad
170    /// request, so the client is told nothing beyond the correlation id.
171    pub fn extract<T: Any + Send + Sync + 'static>(&self) -> Result<&T, JsonApiError> {
172        self.get_ext::<T>().ok_or_else(|| {
173            eprintln!(
174                "[{}] no `{}` in the request context",
175                self.correlation_id(),
176                std::any::type_name::<T>()
177            );
178            JsonApiError::internal(self)
179        })
180    }
181
182    /// One metadata value.
183    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
184        self.inner.metadata.get(key)
185    }
186
187    /// Every metadata field bound on this context.
188    pub fn metadata(&self) -> &BTreeMap<String, serde_json::Value> {
189        &self.inner.metadata
190    }
191
192    /// Copy-on-write update; a `Context` already shared stays untouched.
193    fn map(mut self, edit: impl FnOnce(&mut Fields)) -> Self {
194        let fields = Arc::make_mut(&mut self.inner);
195        edit(fields);
196        self
197    }
198}
199
200#[cfg(feature = "audit")]
201#[cfg_attr(docsrs, doc(cfg(feature = "audit")))]
202impl Context {
203    /// Enter the `ash-log` scope for this context.
204    ///
205    /// Every log line and audit event emitted while the returned guard lives
206    /// inherits the correlation id, the principal and the metadata — with no
207    /// threading through call signatures, and no scope built by hand at the
208    /// call site.
209    ///
210    /// Hold the guard across the work, not across an `.await` that might move
211    /// threads: `ash_log::Scope` is thread-local, so re-enter on the far side
212    /// of a spawn instead. The `Context` itself crosses freely.
213    ///
214    /// ```ignore
215    /// # use ash_jsonapi::context::Context;
216    /// let ctx = Context::new("01H9K2QZ8V").with_principal("alice@example.com");
217    ///
218    /// let _guard = ctx.scope();
219    /// // ash_info!/ash_audit! here carry the id and the principal.
220    /// ```
221    pub fn scope(&self) -> ash_log::ScopeGuard {
222        let mut scope = ash_log::Scope::new().correlation_id(self.correlation_id());
223
224        if let Some(principal) = self.principal() {
225            scope = scope.principal(principal);
226        }
227        // The tenant is a scope field like any other, so an audit event
228        // records which tenant a decision was made for.
229        if let Some(tenant) = self.tenant() {
230            scope = scope.with("tenant", tenant);
231        }
232        for (key, value) in self.metadata() {
233            scope = scope.with(key.clone(), value.clone());
234        }
235
236        scope.enter()
237    }
238}