"""Lets any Python service in this workspace receive AuthGuard's and CarrierNode's current base URL(s) pushed from ProjectConfigurator, instead of hardcoding them in its own env vars. Mirrors shared/backend/coreconfig (Go) exactly -- same Info shape, same Store semantics -- translated to Python idioms; keep both in sync if either changes shape. See ProjectConfigurator/README.md's "Pushing core service info to other projects" section for the wire contract this module implements the receiving end of. Framework-agnostic, like the rest of this package (see the top-level README's "HTTP framework adapters stay in each service" note): this module has no HTTP server of its own. A service wires the actual PUT /api/core-services/internal route in its own framework (FastAPI, aiohttp, ...), gated behind its own SECRET check the same way its other internal-service routes already are, decodes the JSON body into an `Info`, and calls `Store.set(info)` -- see `Store.set`'s doc comment for a minimal FastAPI example. """ from __future__ import annotations import threading from dataclasses import dataclass, field from typing import Callable, Optional @dataclass class Info: """AuthGuard's and CarrierNode's current base URL(s), as pushed by ProjectConfigurator. Field names match the JSON wire shape (coreServiceInfo in ProjectConfigurator/backend/cmd/projectconfigurator/settings.go and coreconfig.Info in shared/backend/coreconfig) exactly.""" auth_guard_url: str = "" # carrier_node_url is the primary CarrierNode instance's URL # (carrier_node_urls[0], if any) -- kept for a service that only ever # talks to one CarrierNode instance. carrier_node_url: str = "" # carrier_node_urls is every CarrierNode instance ProjectConfigurator has # registered, in priority order (the first entry is the same as # carrier_node_url). carrier_node_urls: list = field(default_factory=list) @classmethod def from_json(cls, data: dict) -> "Info": urls = [str(u).strip() for u in (data.get("carrierNodeUrls") or []) if str(u).strip()] if not urls: single = str(data.get("carrierNodeUrl") or "").strip() if single: urls = [single] return cls( auth_guard_url=str(data.get("authGuardUrl") or "").strip(), carrier_node_url=urls[0] if urls else "", carrier_node_urls=urls, ) def to_json(self) -> dict: return { "authGuardUrl": self.auth_guard_url, "carrierNodeUrl": self.carrier_node_url, "carrierNodeUrls": list(self.carrier_node_urls), } class Store: """Holds the most recently pushed Info, defaulting to whatever fallback __init__ was given (typically this service's own AUTHGUARD_URL/ CARRIERNODE_URL env vars, or "" now that they're optional) until ProjectConfigurator's first push arrives -- or forever, if this deployment isn't registered with a ProjectConfigurator instance at all, in which case those env vars (if set) keep working exactly as before.""" def __init__(self, fallback: Optional[Info] = None) -> None: self._lock = threading.Lock() self._info = _normalize(fallback or Info()) self._on_update: Optional[Callable[[Info], None]] = None def get(self) -> Info: with self._lock: return self._info @property def auth_guard_url(self) -> str: return self.get().auth_guard_url @property def carrier_node_url(self) -> str: return self.get().carrier_node_url @property def carrier_node_urls(self) -> list: return self.get().carrier_node_urls def on_update(self, fn: Callable[[Info], None]) -> None: """Registers fn to be called (synchronously, so keep it fast) with the new Info after every set() -- e.g. an AuthClient's set_base_url for a client that isn't already reading through Store on every call. Only one callback is kept; a second registration replaces the first.""" with self._lock: self._on_update = fn def set(self, next_info: Info) -> Info: """Replaces the current Info, field by field, ignoring a blank/empty field so a partial push (e.g. only carrierNodeUrl(s) changed) never clobbers the other value. Returns the resulting Info. Minimal FastAPI usage: @app.put("/api/core-services/internal") async def push_core_services(request: Request): if request.headers.get("X-Internal-Auth") != SECRET: raise HTTPException(status_code=401) body = await request.json() info = core_config_store.set(Info.from_json(body)) return {"ok": True, "info": info.to_json()} """ next_info = _normalize(next_info) with self._lock: if next_info.auth_guard_url: self._info.auth_guard_url = next_info.auth_guard_url if next_info.carrier_node_urls: self._info.carrier_node_urls = next_info.carrier_node_urls self._info.carrier_node_url = next_info.carrier_node_urls[0] current = self._info callback = self._on_update if callback is not None: callback(current) return current def _normalize(info: Info) -> Info: cleaned = [str(u).strip() for u in (info.carrier_node_urls or []) if str(u).strip()] if not cleaned and info.carrier_node_url.strip(): cleaned = [info.carrier_node_url.strip()] return Info( auth_guard_url=info.auth_guard_url.strip(), carrier_node_url=cleaned[0] if cleaned else "", carrier_node_urls=cleaned, )