With Async Context
A Rust library providing thread-safe, type-safe context management across asynchronous tasks. It allows passing contextual data through middleware and async functions while maintaining proper lifetimes and preventing common pitfalls.
Problem Solved
This library provides a way to pass context data through async Rust code without having to manually thread it through every function call. In server applications, you often need to track data like:
- Request IDs
- User authentication details
- IP addresses
- Request timing metrics
- Feature flags
- Account or tenant IDs
Passing this data as function parameters can make code messy and hard to maintain as applications grow. This library provides a simpler approach - it lets you wrap async operations in a context that makes the data available wherever needed in that request or task.
The context is accessed through helper functions, avoiding the need to pass parameters through multiple layers of code. It works well with logging to help track what's happening in your application.
You can use it for web APIs, background jobs, or any async Rust code where you need to maintain contextual data while keeping the benefits of Rust's type system and async support.
Installation
Add the following to your Cargo.toml
:
[]
= "0.1.2"
Core Concepts
The library is built around a few key functions:
with_async_context
: Establishes a new context scope and runs a future within itfrom_context
: Retrieves an immutable reference to the current contextfrom_context_mut
: Gets a mutable reference to modify the contextcontext_as_string
: Converts the context to a string representation
Here's a basic example showing the main patterns:
use ;
async
async
Web Framework Integration
The library seamlessly integrates with web frameworks like Axum for request context handling:
use ;
async
// Add the middleware to your Axum router
app.layer
Access the context from any async handler:
async
Structured Logging
The library includes a logging implementation that automatically incorporates context:
use ;
// Initialize with default format
init_context_logger!;
// Or customize the format
init_context_logger!;
// Logs automatically include context details
info!;
// Outputs: "INFO - request_id=123,method=GET,path=/users - Processing request"
Safe Error Handling
The library encourages robust error handling patterns:
// Safely handle missing context with defaults
let value = from_context;
// Use Result for explicit error handling
let result = from_context;
Thread Safety and Async
All operations are thread-safe and can be used reliably across:
- Async tasks and futures
- Thread pools
- Web request handlers
- Background jobs
The library prevents nested context creation to maintain clear ownership semantics and avoid common pitfalls in async code.
License
Licensed under MIT.