Spaces:
Running
Running
Download core/tenancy/context.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 1.23 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/tenancy/context.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/tenancy/context.py
-
curl -L -o context.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/tenancy/context.py
1.23 kB
| """Request-scoped tenant and actor context. | |
| The session layer reads these values and issues ``SET LOCAL app.tenant_id`` at the start | |
| of every transaction, so RLS policies see the right tenant. | |
| """ | |
| from __future__ import annotations | |
| import uuid | |
| from collections.abc import Iterator | |
| from contextlib import contextmanager | |
| from contextvars import ContextVar | |
| from dataclasses import dataclass | |
| class RequestContext: | |
| tenant_id: uuid.UUID | None = None | |
| user_id: uuid.UUID | None = None | |
| actor: str = "system" | |
| _current: ContextVar[RequestContext] = ContextVar( | |
| "wp_request_context", | |
| default=RequestContext(), # noqa: B039 (frozen, immutable) | |
| ) | |
| def current() -> RequestContext: | |
| return _current.get() | |
| def use_context( | |
| tenant_id: uuid.UUID | None = None, | |
| user_id: uuid.UUID | None = None, | |
| actor: str | None = None, | |
| ) -> Iterator[RequestContext]: | |
| ctx = RequestContext( | |
| tenant_id=tenant_id, | |
| user_id=user_id, | |
| actor=actor or (f"user:{user_id}" if user_id else "system"), | |
| ) | |
| token = _current.set(ctx) | |
| try: | |
| yield ctx | |
| finally: | |
| _current.reset(token) | |