Skip to main content

Crate dcontext

Crate dcontext 

Source
Expand description

§dcontext

Distributed context propagation for Rust.

dcontext provides a scoped, type-safe key–value store that travels with the execution flow — across function calls, async/sync boundaries, thread spawns, and even process boundaries via serialization.

§Quick Start

use dcontext::{RegistryBuilder, initialize, enter_named_scope, get_context, set_context, scope_chain};
use serde::{Serialize, Deserialize};

#[derive(Clone, Default, Debug, Serialize, Deserialize)]
struct RequestId(String);

let mut builder = RegistryBuilder::new();
builder.register::<RequestId>("request_id");
initialize(builder); // freeze registry — all reads are lock-free

let _guard = enter_named_scope("ingress");
set_context("request_id", RequestId("req-123".into()));

let rid: RequestId = get_context("request_id");
assert_eq!(rid.0, "req-123");

// Query the scope chain — returns names of all active named scopes
let chain = scope_chain(); // vec!["ingress"]

See also: enter_scope for unnamed scopes, named_scope_async for async named scopes, and scope_chain for querying the full distributed call path (including remote prefix from cross-process propagation).

Re-exports§

pub use error::ContextError;

Modules§

error

Macros§

register_contexts
Register multiple context types on a builder at once.
with_scope
Enter a scope, set values, execute a block, and auto-revert.

Structs§

ContextKey
A typed handle to a registered context entry.
ContextSnapshot
An immutable snapshot of the current context. Clone + Send + Sync.
RegistrationOptions
Builder for configuring per-key registration options.
RegistryBuilder
Collects context registrations during application startup.
ScopeGuard
RAII guard that reverts a scope on drop. Not Send/Sync — scopes are bound to their storage context.

Functions§

attach
Restore a snapshot by pushing a new scope with its values.
deserialize_context
Restore context from bytes. Pushes a new scope with deserialized values.
deserialize_context_string
Restore context from a base64-encoded string.
enter_named_scope
Push a new named scope and return a guard.
enter_scope
Push a new scope and return a guard.
force_thread_local
Escape hatch: explicitly use thread-local storage even inside an async runtime. Panic-safe and nesting-safe via depth counter + RAII guard.
get_context
Get a context value. Returns T::default() if not set. Panics if the key is not registered.
initialize
Freeze the registry. Consumes the builder and makes all reads lock-free.
make_wire_bytes
Construct wire-format bytes with a single entry. This is a helper for testing version migration — it lets you create wire bytes as if they came from a sender running an older schema version.
make_wire_bytes_v
Like make_wire_bytes but allows specifying the wire format version.
max_context_size
Get the current max context size limit. 0 means no limit.
max_scope_chain_len
Get the current max scope chain length. 0 means no limit. Default is 64.
named_scope_async
Async version of enter_named_scope: execute a future in a new named scope.
scope
Execute f in a new scope. Changes revert when f returns.
scope_async
Async version: execute a future in a new scope. The scope is entered before polling and exited after the future completes.
scope_chain
Return the current scope chain: remote prefix + local named scope names.
serialize_context
Serialize the current context (all scopes merged) into bytes.
serialize_context_string
Serialize the current context into a base64-encoded string.
set_context
Set a context value in the current scope. Panics if the key is not registered or type doesn’t match.
set_context_local
Set a local-only context value. The type does NOT need Serialize/DeserializeOwned. Panics if the key is not registered or type doesn’t match.
set_max_context_size
Set the maximum serialized context size in bytes. Serialization functions will return ContextTooLarge if exceeded. Set to 0 to disable (default).
set_max_scope_chain_len
Set the maximum number of entries in the scope chain.
snapshot
Capture a snapshot of the current effective context.
spawn_with_context
Spawn a std::thread that inherits the current context. Returns io::Result instead of panicking on spawn failure.
spawn_with_context_async
Spawn a Tokio task that inherits the current context.
try_get_context
Get a context value. Returns Ok(Some(T)) if set, Ok(None) if registered but not set, Err if not registered.
try_initialize
Try to freeze the registry. Returns Err if already initialized.
try_set_context
Set a context value. Returns Err on type mismatch or if key is not registered.
try_set_context_local
Set a local-only context value. Returns Err on type mismatch or if key is not registered.
with_context
Run an async block with the given snapshot established as task-local context.
wrap_with_context
Wrap a FnOnce closure so context is captured now and restored when called.
wrap_with_context_fn
Wrap an Fn closure so context is captured now and restored on each call.