Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_correlation.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

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
3from __future__ import annotations
4
5from contextvars import ContextVar, Token
6from uuid import UUID, uuid4
7
8
9CORRELATION_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
17def new_correlation_id() -> str:
18 """Return a new UUIDv4 correlation ID."""
19 return str(uuid4())
20
21
22def 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
42def 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
47def 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
52def 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
57def 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)