Skip to main content

RequestContext

Struct RequestContext 

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

Request context that wraps asupersync’s capability context.

RequestContext provides access to:

  • Request-scoped identity (request ID, trace context)
  • Cancellation checkpoints for cancel-safe handlers
  • Budget/deadline awareness for timeout enforcement
  • Region-scoped spawning for background work
  • Body size limit configuration for DoS prevention

§Example

async fn handler(ctx: &RequestContext) -> impl IntoResponse {
    // Check for client disconnect
    ctx.checkpoint()?;

    // Get remaining time budget
    let remaining = ctx.remaining_budget();

    // Check body size limit
    let max_body = ctx.body_limit().max_size();

    // Do work...
    "Hello, World!"
}

Implementations§

Source§

impl RequestContext

Source

pub fn new(cx: Cx, request_id: u64) -> Self

Creates a new request context from an asupersync Cx.

This is typically called by the server when accepting a new request, creating a new region for the request lifecycle. Uses the default body size limit (1MB).

Source

pub fn with_body_limit(cx: Cx, request_id: u64, max_body_size: usize) -> Self

Creates a new request context with a custom body size limit.

Use this when the application has configured a specific max_body_size in AppConfig, or when a route has an override.

Source

pub fn with_overrides( cx: Cx, request_id: u64, overrides: Arc<DependencyOverrides>, ) -> Self

Creates a new request context with shared dependency overrides.

Source

pub fn with_overrides_and_body_limit( cx: Cx, request_id: u64, overrides: Arc<DependencyOverrides>, max_body_size: usize, ) -> Self

Creates a new request context with overrides and a custom body size limit.

Source

pub fn request_id(&self) -> u64

Returns the unique request identifier.

Useful for logging and tracing across the request lifecycle.

Source

pub fn dependency_cache(&self) -> &DependencyCache

Returns the dependency cache for this request.

Source

pub fn dependency_overrides(&self) -> &DependencyOverrides

Returns the dependency overrides registry.

Source

pub fn resolution_stack(&self) -> &ResolutionStack

Returns the resolution stack for cycle detection.

Source

pub fn cleanup_stack(&self) -> &CleanupStack

Returns the cleanup stack for registering cleanup functions.

Cleanup functions run after the handler completes in LIFO order.

Source

pub fn body_limit(&self) -> &BodyLimitConfig

Returns the body limit configuration for this request.

This can be used by body extractors (e.g., Json<T>) to enforce size limits and prevent DoS attacks.

Source

pub fn max_body_size(&self) -> usize

Returns the maximum body size in bytes for this request.

This is a convenience method equivalent to ctx.body_limit().max_size().

Source

pub fn region_id(&self) -> RegionId

Returns the underlying region ID from asupersync.

The region represents the request’s lifecycle scope - all spawned tasks belong to this region and will be cleaned up when the request completes or is cancelled.

Source

pub fn task_id(&self) -> TaskId

Returns the current task ID.

Source

pub fn budget(&self) -> Budget

Returns the current budget.

The budget represents the remaining computational resources (time, polls) available for this request. When exhausted, the request should be cancelled gracefully.

Source

pub fn is_cancelled(&self) -> bool

Checks if cancellation has been requested.

This includes client disconnection, timeout, or explicit cancellation. Handlers should check this periodically and exit early if true.

Source

pub fn checkpoint(&self) -> Result<(), CancelledError>

Cooperative cancellation checkpoint.

Call this at natural suspension points in your handler to allow graceful cancellation. Returns Err if cancellation is pending.

§Errors

Returns an error if the request has been cancelled and cancellation is not currently masked.

§Example
async fn process_items(ctx: &RequestContext, items: Vec<Item>) -> Result<(), HttpError> {
    for item in items {
        ctx.checkpoint()?;  // Allow cancellation between items
        process_item(item).await?;
    }
    Ok(())
}
Source

pub fn masked<F, R>(&self, f: F) -> R
where F: FnOnce() -> R,

Executes a closure with cancellation masked.

While masked, checkpoint() will not return an error even if cancellation is pending. Use this for critical sections that must complete atomically.

§Example
// Commit transaction - must not be interrupted
ctx.masked(|| {
    db.commit().await?;
    Ok(())
})
Source

pub fn trace(&self, message: &str)

Records a trace event for this request.

Events are associated with the request’s trace context and can be used for debugging and observability.

Source

pub fn cx(&self) -> &Cx

Returns a reference to the underlying asupersync Cx.

Use this when you need direct access to asupersync primitives, such as spawning tasks or using combinators.

Trait Implementations§

Source§

impl Clone for RequestContext

Source§

fn clone(&self) -> RequestContext

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for RequestContext

Source§

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

Formats the value using the given formatter. Read more
Source§

impl FromRequest for RequestContext

Source§

type Error = Infallible

Error type when extraction fails.
Source§

async fn from_request( ctx: &RequestContext, _req: &mut Request, ) -> Result<Self, Self::Error>

Extract a value from the request. 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<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
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> Same for T

Source§

type Output = T

Should always be Self
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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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
Source§

impl<T> ResponseProduces<T> for T