Coverage for app / common / workspace.py: 98%
40 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""The svc-core workspace a request's work is done in.
3svc-core gives every call it makes a workspace (``X-Workspace``): ``personal``
4or ``user:<id>`` for a person's own, ``organisation:<id>`` or ``project:<id>``
5(svc-core ``app/services/workspace.py``). svc-ai keeps no workspaces of its
6own; it stamps the key on the trace rows the request writes
7(``llm_invocations.workspace``, ``tool_invocations.workspace``) so that the
8usage figures svc-core shows on a workspace's pages — ``/stats/*`` — are the
9work done there, and never a person's other workspaces'.
11``personal`` is resolved to the row's own user (``user:<id>``) when the row is
12built, so a stored key always names one workspace. Rows from before the column
13existed have none and count as their user's Personal (``clause``).
14"""
16from __future__ import annotations
18from contextvars import ContextVar, Token
19from typing import Any
20from uuid import UUID
22from sqlalchemy import or_
24HEADER = "X-Workspace"
26PERSONAL = "personal"
27_KINDS = frozenset({"user", "organisation", "project"})
29_CURRENT: ContextVar[str | None] = ContextVar("svc_core_workspace", default=None)
32def parse(raw: str | None) -> str | None:
33 """A well-formed workspace key, normalised — or None for anything else,
34 which is stamped as nothing rather than stored as given."""
35 if not raw:
36 return None
37 raw = raw.strip()
38 if raw == PERSONAL:
39 return PERSONAL
40 kind, _, ident = raw.partition(":")
41 if kind not in _KINDS:
42 return None
43 try:
44 return f"{kind}:{UUID(ident)}"
45 except ValueError:
46 return None
49def current() -> str | None:
50 """The workspace key the current request named, if any."""
51 return _CURRENT.get()
54def set_current(key: str | None) -> Token:
55 return _CURRENT.set(parse(key))
58def reset(token: Token) -> None:
59 _CURRENT.reset(token)
62def stamp(user_id: Any) -> str | None:
63 """The key a trace row written now carries: the request's workspace,
64 with ``personal`` resolved to the row's own user."""
65 key = _CURRENT.get()
66 if key == PERSONAL:
67 return f"user:{user_id}" if user_id else None
68 return key
71def clause(model: Any, workspace: str):
72 """SQL: ``model``'s rows of work done in ``workspace`` (a key). A
73 person's Personal also holds their rows that name no workspace — written
74 before rows named one."""
75 key = parse(workspace)
76 if key is None or key == PERSONAL:
77 raise ValueError(f"Not a workspace key: {workspace!r}")
78 if key.startswith("user:"):
79 return or_(model.workspace == key, model.workspace.is_(None))
80 return model.workspace == key