Skip to content

std/context

Import with import std/context.

Types

type Context

Per-life execution context, threaded by the runtime through every call stack. Programs store it on their concrete app struct and read it as MyApp.context; an ordinary block with with MyApp.context = Context.with_X(MyApp.context, ...) derives a child context for that block’s remaining statements.

Opaque: user code cannot construct a Context value directly. Only Context.root() (for boot construction), the language runtime, and the Context.with_* derivers produce them.

fn root(): Context

type function on Context

Construct a fresh root Context — no deadline, not canceled, no parent. Intended for use while constructing the program’s app value.

Interactive Tests

root = Context.root()
assert Context.deadline(root) == Maybe.None
fn deadline(c: Context): Maybe<Instant>

type function on Context

Absolute deadline of this context, if any.

Interactive Tests

assert Context.deadline(Context.root()) == Maybe.None
fn deadline_remaining(c: Context): Maybe<Duration>

type function on Context

Time until the deadline, if there is one. None means no deadline is set; Some(0) means it has passed.

Interactive Tests

assert Context.deadline_remaining(Context.root()) == Maybe.None
fn with_deadline(c: Context, at: Instant): Context

type function on Context

Child context with deadline at at. If the parent has a tighter deadline already, the parent’s deadline wins (no-op).

Interactive Tests

child = Context.with_deadline(Context.root(), Instant.from_seconds(0))
assert Context.deadline_remaining(child) == Maybe.Some(Duration.seconds(0))
fn with_timeout(c: Context, dur: Duration): Context

type function on Context

Child context with deadline at now() + dur. If the parent has a tighter deadline already, the parent’s deadline wins.

Interactive Tests

child = Context.with_timeout(Context.root(), Duration.seconds(-1))
assert Context.deadline_remaining(child) == Maybe.Some(Duration.seconds(0))
fn with_value<T>(c: Context, value: T): Context

type function on Context

Return a child context with value stored under its Nomi type.

Context values are intended for request- or execution-scoped metadata such as trace IDs, auth subjects, or locale. Prefer explicit app fields (MyApp.store, MyApp.logger) for dependencies, and prefer domain types (TraceId, Subject) over raw scalars.

Interactive Tests

type TraceId String
traced = Context.with_value(Context.root(), TraceId("trace-123"))
assert Context.value(traced, TraceId) == Maybe.Some(TraceId("trace-123"))
fn value<T>(c: Context, value_type: Type<T>): Maybe<T>

type function on Context

Look up the nearest value of type T, walking through parent contexts when this context has not overridden that type.

Context.value(context, TraceId)

Interactive Tests

type TraceId String
root = Context.root()
assert Context.value(root, TraceId) == Maybe.None
fn inspect(value: Context): String

impl Debug.inspect