pub trait FromContext<C = (), S = ()>: Sized {
type Rejection: Into<HandlerResult>;
// Required method
fn from_context(
ctx: &mut Context<'_, C, S>,
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
}Expand description
A value resolved from the per-delivery Context and shared state, ready to be passed to a
handler as a parameter.
When a type implements it, #[subscriber] handlers can take that type as an argument: the
generated handler calls from_context for each such parameter, in
declaration order, before the body runs. Resolution is async so it may do work (a lookup, a
scoped allocation) and fallible so it may reject the delivery; the Rejection
is turned into a HandlerResult that settles the message (typically a nack).
The first handler parameter (the message &M) and the optional &mut Context are not
extractors; every other by-value parameter is.
To inject a piece of the application state, use State<T>: it implements FromContext
for any T the state can produce (T: FromRef<S>), so handlers take State<T> without a
hand-written impl. Implement FromContext directly only for a custom extractor (an auth guard, a
request-scoped resolver) that does more than read the state.
§Examples
use ruststream::runtime::{Context, FromContext, HandlerResult};
// A custom extractor: reject the delivery unless a header is present.
struct RequireToken(Vec<u8>);
impl<C: Send, S: Sync> FromContext<C, S> for RequireToken {
type Rejection = HandlerResult;
async fn from_context(ctx: &mut Context<'_, C, S>) -> Result<Self, HandlerResult> {
match ctx.headers().get("authorization") {
Some(token) => Ok(RequireToken(token.to_vec())),
None => Err(HandlerResult::drop()),
}
}
}Required Associated Types§
Sourcetype Rejection: Into<HandlerResult>
type Rejection: Into<HandlerResult>
The error returned when extraction fails. It is converted into a HandlerResult (the
reflexive conversion makes HandlerResult itself a valid rejection, and Infallible works
for an extractor that never fails) and the delivery is settled by that outcome, skipping the
handler body.
Required Methods§
Sourcefn from_context(
ctx: &mut Context<'_, C, S>,
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send
fn from_context( ctx: &mut Context<'_, C, S>, ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send
Resolves the value from the delivery context. The context is borrowed mutably so an extractor may also read broker fields or take scratch a middleware left for it.
§Errors
Returns Rejection when the value cannot be produced; the dispatcher
settles the delivery by the resulting HandlerResult instead of running the handler.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".