ccproxy.core.request_context¶
ccproxy.core.request_context
¶
Request context management with timing and correlation.
This module provides context managers and utilities for tracking request lifecycle, timing measurements, and correlation across async operations. Uses structlog for rich business event logging.
Key features: - Accurate timing measurement using time.perf_counter() - Request correlation with unique IDs - Structured logging integration - Async-safe context management with contextvars - Exception handling and error tracking
RequestContext
dataclass
¶
RequestContext(
request_id,
start_time,
logger,
metadata=dict(),
storage=None,
log_timestamp=None,
metrics=dict(),
format_chain=None,
)
Context object for tracking request state and metadata.
Provides access to request ID, timing information, and structured logger with automatically injected context.
add_metadata
¶
log_event
¶
Log an event with current context and timing.
get_log_timestamp_prefix
¶
Get timestamp prefix for consistent log filenames.
Returns:
| Type | Description |
|---|---|
str
|
Timestamp string in YYYYMMDDhhmmss format (UTC) |
Source code in ccproxy/core/request_context.py
set_current
¶
Set this context as the current request context.
Returns:
| Type | Description |
|---|---|
Token[RequestContext | None]
|
Token that can be used to restore the previous context |
get_current
staticmethod
¶
Get the current request context from async context.
Returns:
| Type | Description |
|---|---|
RequestContext | None
|
The current RequestContext or None if not set |
clear_current
¶
Clear the current context and restore the previous one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
Token[RequestContext | None]
|
The token returned by set_current() |
required |
to_dict
¶
Serialize the context to a dictionary for JSON logging.
Returns all context data including: - Request ID and timing information - All metadata (costs, tokens, model, etc.) - All metrics - Computed properties (duration_ms, duration_seconds)
Excludes non-serializable fields like logger and storage.
Source code in ccproxy/core/request_context.py
ContextTracker
¶
Thread-safe tracker for managing active request contexts.
Useful for tracking concurrent requests and their states, especially for metrics like active request counts.
Source code in ccproxy/core/request_context.py
add_context
async
¶
remove_context
async
¶
get_context
async
¶
get_active_count
async
¶
get_all_contexts
async
¶
cleanup_stale_contexts
async
¶
Remove contexts older than max_age_seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age_seconds
|
float
|
Maximum age in seconds before considering stale |
300
|
Returns:
| Type | Description |
|---|---|
int
|
Number of contexts removed |
Source code in ccproxy/core/request_context.py
get_request_event_stream
async
¶
Async generator for request events used by analytics streaming.
This is a lightweight stub for type-checking and optional runtime use. Integrations can replace or wrap this to provide actual event streams.
Source code in ccproxy/core/request_context.py
request_context
async
¶
request_context(
request_id=None,
storage=None,
metrics=None,
log_timestamp=None,
**initial_context,
)
Context manager for tracking complete request lifecycle with timing.
Automatically logs request start/success/error events with accurate timing. Provides structured logging with request correlation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request_id
|
str | None
|
Unique request identifier (generated if not provided) |
None
|
storage
|
Any | None
|
Optional storage backend for access logs |
None
|
metrics
|
Any | None
|
Optional PrometheusMetrics instance for active request tracking |
None
|
**initial_context
|
Any
|
Initial context to include in all log events |
{}
|
Yields:
| Name | Type | Description |
|---|---|---|
RequestContext |
AsyncGenerator[RequestContext, None]
|
Context object with timing and logging capabilities |
Example
async with request_context(method="POST", path="/v1/messages") as ctx: ctx.add_metadata(model="claude-3-5-sonnet") # Process request ctx.log_event("request_processed", tokens=150) # Context automatically logs success with timing
Source code in ccproxy/core/request_context.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
timed_operation
async
¶
Context manager for timing individual operations within a request.
Useful for measuring specific parts of request processing like API calls, database queries, or data processing steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation_name
|
str
|
Name of the operation being timed |
required |
request_id
|
str | None
|
Associated request ID for correlation |
None
|
**context
|
Any
|
Additional context for logging |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[dict[str, Any], None]
|
Dict with timing information and logger |
Example
async with timed_operation("claude_api_call", request_id=ctx.request_id) as op: response = await api_client.call() op["response_size"] = len(response) # Automatically logs operation timing
Source code in ccproxy/core/request_context.py
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
get_context_tracker
¶
Get or create global context tracker.
tracked_request_context
async
¶
Request context manager that also tracks active requests globally.
Combines request_context() with automatic tracking in the global context tracker for monitoring active request counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request_id
|
str | None
|
Unique request identifier |
None
|
**initial_context
|
Any
|
Initial context to include in log events |
{}
|
Yields:
| Name | Type | Description |
|---|---|---|
RequestContext |
AsyncGenerator[RequestContext, None]
|
Context object with timing and logging |