Module context

Module context 

Source
Expand description

Thread-local system for adding context data to persisted events.

This module provides a context propagation system for event sourcing that allows attaching metadata (like request IDs, user IDs, or audit information) to events as they are created and persisted to the database.

§Core Components

  • EventContext: Thread-local context manager (!Send) that maintains a stack of contexts within a single thread
  • ContextData: Immutable, thread-safe (Send) snapshot of context data that can be passed across thread boundaries
  • WithEventContext: Extension trait for Future types to propagate context across async boundaries

§Usage Patterns

§Same Thread Context

use es_entity::context::EventContext;

let mut ctx = EventContext::current();
ctx.insert("request_id", &"req-123").unwrap();

// Fork for isolated scope
{
    let mut child = EventContext::fork();
    child.insert("operation", &"update").unwrap();
    // Both request_id and operation are available
}
// Only request_id remains in parent

§Async Task Context

use es_entity::context::{EventContext, WithEventContext};

async fn spawn_with_context() {
    let mut ctx = EventContext::current();
    ctx.insert("user_id", &"user-456").unwrap();

    let data = ctx.data();
    tokio::spawn(async move {
        // Context is available in spawned task
        let ctx = EventContext::current();
        // Has user_id from parent
    }.with_event_context(data)).await.unwrap();
}

§Cross-Thread Context

use es_entity::context::EventContext;

let mut ctx = EventContext::current();
ctx.insert("trace_id", &"trace-789").unwrap();
let data = ctx.data();

std::thread::spawn(move || {
    let ctx = EventContext::seed(data);
    // New thread has trace_id
});

§Database Integration

When events are persisted using repositories with event_context = true, the current context is automatically serialized to JSON and stored in a context column alongside the event data, enabling comprehensive audit trails and debugging.

Structs§

ContextData
Immutable context data that can be safely shared across thread boundaries.
EventContext
Thread-local event context for tracking metadata throughout event sourcing operations.
EventContextFuture
A future wrapper that provides event context during polling.
TracingContext

Traits§

WithEventContext
Extension trait for propagating event context across async boundaries.