askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_correlation.py · 1.6 KB · 59 lines
| 1 | """Request correlation IDs for DBBASIC runtime actions.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | from contextvars import ContextVar, Token |
| 6 | from uuid import UUID, uuid4 |
| 7 | |
| 8 | |
| 9 | CORRELATION_ID_HEADER = "x-dbbasic-correlation-id" |
| 10 | |
| 11 | _current_correlation_id: ContextVar[str | None] = ContextVar( |
| 12 | "dbbasic_correlation_id", |
| 13 | default=None, |
| 14 | ) |
| 15 | |
| 16 | |
| 17 | def new_correlation_id() -> str: |
| 18 | """Return a new UUIDv4 correlation ID.""" |
| 19 | return str(uuid4()) |
| 20 | |
| 21 | |
| 22 | def normalize_correlation_id(value: str | None) -> str | None: |
| 23 | """Return a canonical UUID string, or ``None`` for unusable input.""" |
| 24 | if value is None: |
| 25 | return None |
| 26 | |
| 27 | text = str(value).strip() |
| 28 | if not text: |
| 29 | return None |
| 30 | |
| 31 | try: |
| 32 | parsed = UUID(text) |
| 33 | except (TypeError, ValueError, AttributeError): |
| 34 | return None |
| 35 | |
| 36 | if parsed.version != 4: |
| 37 | return None |
| 38 | |
| 39 | return str(parsed) |
| 40 | |
| 41 | |
| 42 | def ensure_correlation_id(value: str | None = None) -> str: |
| 43 | """Normalize an incoming ID or create a new UUIDv4 ID.""" |
| 44 | return normalize_correlation_id(value) or new_correlation_id() |
| 45 | |
| 46 | |
| 47 | def current_correlation_id() -> str | None: |
| 48 | """Return the current request/action correlation ID, if one is set.""" |
| 49 | return _current_correlation_id.get() |
| 50 | |
| 51 | |
| 52 | def set_current_correlation_id(correlation_id: str | None) -> Token[str | None]: |
| 53 | """Set the current correlation ID and return a reset token.""" |
| 54 | return _current_correlation_id.set(normalize_correlation_id(correlation_id)) |
| 55 | |
| 56 | |
| 57 | def reset_current_correlation_id(token: Token[str | None]) -> None: |
| 58 | """Reset the current correlation ID to a previous context value.""" |
| 59 | _current_correlation_id.reset(token) |