Context and Scoping
Relevant source files
The following files were used as context for generating this wiki page:
The Context and Scoping system in FLEXT-Core provides a robust mechanism for managing request-scoped data, correlation IDs, and service metadata across asynchronous execution boundaries. It acts as a centralized facade for context-variable operations, enabling seamless propagation of observability data such as operation names and user identities throughout the application layers. Sources: src/flext_core/_context_parts/flextcontext_part_01.py:1-12, examples/README.md:41-43
This module is built upon Pydantic v2 models, ensuring strict data validation and immutability where required. It integrates deeply with the project's dependency injection and observability pillars, facilitating "context-first" observability. Sources: src/flext_core/_context_parts/flextcontext_part_01.py:17-21, tests/README.md:12-14
Architecture and Components
The architecture follows a layered approach where FlextContext serves as the public facade, delegating state management and lifecycle operations to specialized utility mixins.
Core Components
- FlextContext: The primary interface for developers to interact with scoped data. It handles instance-level key-value storage and class-level contextvar operations. Sources: src/flext_core/_context_parts/flextcontext_part_01.py:25-30
- FlextUtilitiesContextState: Provides normalization and low-level access to contextvar payloads and metadata projection. Sources: src/flext_core/_utilities/context_state.py:26-30
- FlextUtilitiesContextLifecycle: Manages the merging and exporting of context data, ensuring payloads are correctly validated against canonical models. Sources: src/flext_core/_utilities/context_lifecycle.py:24-28
The following diagram illustrates the relationship between these components:
Scoped Data Management
FLEXT-Core distinguishes between instance-level scope and process-global context variables. The instance-level scope (data) is a mutable key-value store specific to a FlextContext object, while metadata and correlation IDs are typically handled via contextvars.
Instance Scope Operations
Developers can store and retrieve JSON-serializable payloads using standard CRUD-like methods.
| Method | Description | Return Type |
|---|---|---|
set(key, value) | Stores a value in the current context instance. | Result[bool] |
get(key) | Retrieves a value from the instance scope. | Result[JsonPayload] |
has(key) | Checks for key existence. | bool |
remove(key) | Deletes a key from the scope. | None |
clear() | Wipes all instance scope data. | None |
Sources: src/flext_core/_context_parts/flextcontext_part_01.py:46-77, tests/unit/test_context.py:25-50
Metadata and Correlation
Metadata represents a snapshot of service and correlation information. FlextContext provides static and instance methods to apply and resolve these identifiers, often used for distributed tracing.
Lifecycle and State Persistence
The context system supports cloning and merging to facilitate data transfer between different execution blocks or parallel tasks.
Cloning and Merging
- Cloning: Creates a deep copy of the
ConfigMapdata and a snapshot of metadata, ensuring mutations in the clone do not affect the original. Sources: src/flext_core/_context_parts/flextcontext_part_01.py:112-117, tests/unit/test_context.py:96-105 - Merging: Integrates data from another
FlextContextor a dictionary. If merging another context, it specifically targets mergeable scopes defined in constants (e.g.,GLOBAL). Sources: src/flext_core/_utilities/context_lifecycle.py:112-123, src/flext_core/_context_parts/flextcontext_part_01.py:104-110
Exporting Context
The export method allows for the extraction of context state into a serialized format. It can optionally include statistics and metadata. Sources: src/flext_core/_utilities/context_lifecycle.py:32-45
| Option | Type | Default | Description |
|---|---|---|---|
include_statistics | bool | False | Includes operation counters and execution metrics. |
include_metadata | bool | False | Includes the full metadata attribute map. |
as_dict | bool | True | Returns a raw dictionary instead of a Pydantic model. |
Sources: src/flext_core/_utilities/context_lifecycle.py:33-36
Dependency Injection Integration
FlextContext acts as a bridge to the global dependency injection container. It maintains a class-level reference to the ContextContainerState, allowing services to be resolved or registered directly through the context facade. Sources: src/flext_core/_context_parts/flextcontext_part_01.py:43-44, src/flext_core/_context_parts/flextcontext_part_01.py:133-140
# Example: Resolving a service via FlextContext
container = FlextContext.resolve_container()
service_result = FlextContext.fetch_service("user_service")
Sources: src/flext_core/_context_parts/flextcontext_part_01.py:133-145
Conclusion
The Context and Scoping system provides the necessary infrastructure for managing cross-cutting concerns in a clean architecture. By combining Pydantic's validation with Python's contextvars, it ensures that observability and operational data are propagated reliably across the application while maintaining strict type safety and architectural boundaries.