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.
Features
- Scoped context — Enter/leave scopes with automatic rollback (RAII guards)
- Type-safe — Compile-time checked access via generics over
Anystorage - Cross-thread — Snapshot and attach context when spawning threads
- Cross-async — Helpers for propagating context across Tokio tasks
- Runtime-agnostic async —
ContextFuturepoll-wrapper works with any executor - Serializable — Serialize context to bytes/string for cross-process propagation
- Local-only entries — Non-serializable context that stays within the process
- Version migration — Rolling upgrades with automatic old→new schema conversion
- O(1) lookups — Index-based read cache for fast context access
Quick Start
[]
= "0.1"
use ;
use ;
;
Architecture
┌─────────────────────────────────────────┐
│ Application Code │
├─────────────────────────────────────────┤
│ register / get_context / set_context │
├─────────────────────────────────────────┤
│ Scope Tree │ Registry │ Snapshot │
├──────────────┼────────────┼─────────────┤
│ Thread-local storage / Task-local │
└─────────────────────────────────────────┘
Key Concepts
- Context — A
HashMap<String, Any>of named, type-erased values - Scope — A stack frame that overlays the parent; changes revert on exit
- ScopeGuard — RAII guard returned by
enter_scope(); drops → reverts - Snapshot — A captured, cloneable, sendable copy of the current context
- Registry — Global type registration for serialization support
- ContextKey<T> — Optional typed key wrapper for compile-time safe access
Cargo Features
| Feature | Default | Description |
|---|---|---|
tokio |
yes | Tokio task-local storage, scope_async, and async spawn helpers |
base64 |
yes | Base64 string serialization for HTTP headers/gRPC metadata |
context-key |
yes | ContextKey<T> typed key wrapper for compile-time safe access |
context-future |
no | ContextFuture poll-wrapper for runtime-agnostic async (non-Tokio executors) |
Documentation
- Usage Guide — Comprehensive guide covering all features with examples
- Design Document — Internal architecture and design decisions
License
MIT