Source code for pain001.logging_schema.context

# Copyright (C) 2023-2026 Pain001. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
# Licensed under either of the Apache License, Version 2.0 or the MIT
# License, at your option. You may not use this file except in
# compliance with one of those licences. Copies are provided in
# LICENSE-APACHE and LICENSE-MIT.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Licences is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the applicable Licence for the specific language
# governing permissions and limitations.

"""Per-request ID propagation for distributed tracing."""

import uuid
from contextvars import ContextVar

# ContextVar rather than a module global or threading.local: the API
# serves concurrent async requests, and each task must see its own
# request id without leaking it to other in-flight requests.
_request_id_context: ContextVar[str | None] = ContextVar(
    "request_id", default=None
)


[docs] def generate_request_id() -> str: """Generate a unique request ID for request tracing. Returns: A short UUID-based request ID (format: req-<8-char-hex>). Example: >>> generate_request_id() 'req-88f24b21' """ return f"req-{uuid.uuid4().hex[:8]}"
[docs] def get_request_id() -> str: """Get or create request ID for current context. Returns: The request ID for the current execution context. """ request_id = _request_id_context.get() if request_id is None: request_id = generate_request_id() _request_id_context.set(request_id) return request_id
[docs] def set_request_id(request_id: str) -> None: """Set request ID for current context (useful for API handlers). Args: request_id: The request ID to set. """ _request_id_context.set(request_id)