Skip to main content

Context

Struct Context 

Source
pub struct Context { /* private fields */ }
Expand description

Everything one request carries.

Cheap to clone: the fields sit behind an Arc, so handing a Context to a nested call or another task copies a pointer.

ⓘ
use ash_jsonapi::context::Context;

let ctx = Context::new("01H9K2QZ8V")
    .with_principal("alice@example.com")
    .with_tenant("acme");

assert_eq!(ctx.correlation_id(), "01H9K2QZ8V");
assert_eq!(ctx.tenant(), Some("acme"));

Implementations§

Source§

impl Context

Source

pub fn new(correlation_id: impl Into<String>) -> Self

A context for one request, identified by its correlation id.

The id is what ties a response back to the audit record, so it is required rather than optional: it comes from the request’s X-Request-Id where the client sent one, and is generated otherwise.

Source

pub fn with_principal(self, principal: impl Into<String>) -> Self

Bind the authenticated principal.

Absent until authentication has run — an unauthenticated request has a context, just not a principal.

Source

pub fn with_tenant(self, tenant: impl Into<String>) -> Self

Bind the tenant, extracted per the resource’s TenantStrategy.

Source

pub fn with_locale(self, locale: Locale) -> Self

Bind the locale the client asked for, negotiated from Accept-Language.

Set by layer() on every request that sends the header. Nothing in this crate translates — see i18n — so this records what was asked for, and is echoed on the response’s top-level meta.lang.

Source

pub fn locale(&self) -> Option<&Locale>

The locale the client asked for, if it sent an Accept-Language this crate could parse.

Source

pub fn with_metadata( self, key: impl Into<String>, value: impl Into<Value>, ) -> Self

Bind one metadata field, carried into every event logged under this context.

Source

pub fn correlation_id(&self) -> &str

The correlation id. Always present.

Source

pub fn principal(&self) -> Option<&str>

The authenticated principal, if authentication has run.

Source

pub fn tenant(&self) -> Option<&str>

The tenant, if one was extracted.

Source

pub fn with<T: Any + Send + Sync + 'static>(self, value: T) -> Self

Attach a typed value to this request.

For what your own middleware resolves — an authenticated actor, a tenant handle, a feature flag set — so a handler receives one Context rather than a widening tuple. One value per type; attaching a second of the same type replaces the first.

A parsed request body does not travel this way: it is handed to Create::create as an argument, since a create always has one and routing it through here would turn an infallible step into a fallible lookup.

ⓘ
// in middleware, after authenticating
let ctx = ctx.with(actor);

// anywhere downstream
let actor: &Actor = ctx.extract()?;
Source

pub fn get_ext<T: Any + Send + Sync + 'static>(&self) -> Option<&T>

The value of type T attached to this request, if any.

Source

pub fn extract<T: Any + Send + Sync + 'static>( &self, ) -> Result<&T, JsonApiError>

The value of type T, or a 500 naming what was missing.

An absent extension means a handler ran without the middleware or extractor that should have attached it — a wiring bug, not a bad request, so the client is told nothing beyond the correlation id.

Source

pub fn get(&self, key: &str) -> Option<&Value>

One metadata value.

Source

pub fn metadata(&self) -> &BTreeMap<String, Value>

Every metadata field bound on this context.

Source§

impl Context

Source

pub fn scope(&self) -> ScopeGuard

Available on crate feature audit only.

Enter the ash-log scope for this context.

Every log line and audit event emitted while the returned guard lives inherits the correlation id, the principal and the metadata — with no threading through call signatures, and no scope built by hand at the call site.

Hold the guard across the work, not across an .await that might move threads: ash_log::Scope is thread-local, so re-enter on the far side of a spawn instead. The Context itself crosses freely.

ⓘ
let ctx = Context::new("01H9K2QZ8V").with_principal("alice@example.com");

let _guard = ctx.scope();
// ash_info!/ash_audit! here carry the id and the principal.

Trait Implementations§

Source§

impl Clone for Context

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Context

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<B> FromRef<B> for B
where B: Clone,

Source§

fn from_ref(backend: &B) -> B

Extract a Self from a reference to the composite backend B.
Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more