text
stringlengths
0
1.47k
Both namespaces expose the same class names, so every `except cex.CosmosX` below is
correct under either backing and none of the control-store logic needs a conditional."""
if _local_mode():
import control_sqlite
return control_sqlite
from azure.cosmos import exceptions as cex
return cex
def enabled() -> bool:
"""True when a control plane is available. Self-hosted always has one (SQLite), so
idempotency and leases work there instead of failing closed with a 503."""
return bool(_ENDPOINT) or _local_mode()
def _pk(org: str) -> str:
return f"org::{org}"
async def _retryable(coro_factory, attempts: int = 3):
"""Run a Cosmos coroutine with a tiny backoff on TRANSIENT errors (429/503/408/
network) so a momentary hiccup doesn't turn a keyed request into a hard 503.
Non-transient errors (409/404/412) propagate immediately — the caller handles
them as control-flow. coro_factory must return a FRESH awaitable each call."""
import asyncio as _a
cex = _exceptions()
last = None
for i in range(attempts):
try:
return await coro_factory()
except cex.CosmosHttpResponseError as e:
if getattr(e, "status_code", None) not in (408, 429, 449, 503):
raise
last = e
except Exception as e: # azure.core ServiceRequestError/ServiceResponseError (network)
name = type(e).__name__
if "ServiceRequest" not in name and "ServiceResponse" not in name:
raise
last = e
await _a.sleep(0.2 * (i + 1))
raise last # exhausted transient retries — caller fails closed
async def _container():
"""Lazily build the async Cosmos container proxy. Raises on misconfig so
fail-closed call sites surface a retryable error instead of running open."""
global _client, _cont
if _cont is not None:
return _cont
if _local_mode():
# Self-hosted: one SQLite file beside the rest of the local data.
import control_sqlite
root = os.environ.get("HR_DATA_DIR", ".hr-data")
_cont = control_sqlite.SqliteContainer(os.path.join(root, "control.db"))
return _cont
if not _ENDPOINT:
raise RuntimeError("control store not configured (COSMOS_ENDPOINT unset)")
from azure.cosmos.aio import CosmosClient
if _KEY:
_client = CosmosClient(_ENDPOINT, credential=_KEY)
else:
# Managed identity — same UAMI the gateway uses for the session pool.
from azure.identity.aio import DefaultAzureCredential
cred = DefaultAzureCredential(
managed_identity_client_id=os.environ.get("AZURE_CLIENT_ID") or None)
_client = CosmosClient(_ENDPOINT, credential=cred)
db = _client.get_database_client(_DB)
_cont = db.get_container_client(_CONTAINER)
return _cont
# ── idempotency ───────────────────────────────────────────────────────────────
async def idem_reserve(org: str, sha: str, resp_id: str, req_hash: str,
ttl_s: int) -> dict | None:
"""Atomically reserve (org, sha) for resp_id. Returns None if WE won the race
(caller proceeds to execute). Returns the EXISTING record if someone else
already reserved it (caller replays that resp_id). Raises on store failure so
the caller can fail closed with a retryable 503."""
cont = await _container()
item = {"id": f"idem::{org}::{sha}", "pk": _pk(org), "kind": "idem",
"resp_id": resp_id, "req_hash": req_hash, "state": "reserved",
"ts": time.time(), "ttl": int(ttl_s)}
cex = _exceptions()
try:
await _retryable(lambda: cont.create_item(item))
return None # we won
except cex.CosmosResourceExistsError:
try:
return await _retryable(lambda: cont.read_item(item["id"], partition_key=_pk(org)))
except cex.CosmosResourceNotFoundError:
# The item existed at create time but is gone now — a TTL expiry between the
# 409 and this read. Genuinely nobody holds it → treat as won. Any OTHER error
# (network/transient) must PROPAGATE so the caller fails closed; swallowing it
# here would let BOTH racers execute and map the key to the wrong resp_id.
return None
async def idem_get(org: str, sha: str) -> dict | None:
cont = await _container()
cex = _exceptions()