nomadro/apps/api/services/nomadro_pb/ensure.py
Eric 499f2d3e26 Ship coffeechat scheduling, notify PB access, and social/admin UI polish for .com.
Document the 2026-11-05 UI/UX upgrade and keep roster/live gates aligned with face-check and presence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 18:19:37 +08:00

202 lines
7.0 KiB
Python

"""Create / repair PocketBase collections (idempotent).
PB 0.25+ ignores legacy `schema` on create and may leave empty collections
(only system `id`). Always verify custom fields exist and PATCH if missing.
"""
from __future__ import annotations
import logging
from threading import RLock
from typing import Any
from nomadro_pb.client import PocketBaseClient, PocketBaseError, get_pb
from nomadro_pb.schemas import ALL_COLLECTIONS
log = logging.getLogger("nomadro_pb.ensure")
_ensured = False
_selected_ready: set[frozenset[str]] = set()
_selected_lock = RLock()
def ensure_selected(names: set[str]) -> bool:
"""Initialize only this service's collections; leave other domains alone."""
key = frozenset(names)
with _selected_lock:
if key in _selected_ready: return True
specs = [spec for spec in ALL_COLLECTIONS if spec['name'] in names]
if len(specs) != len(names): raise ValueError('unknown_collection')
results = []
pb = get_pb()
for spec in specs:
private = {**spec, **{rule: None for rule in ('listRule', 'viewRule', 'createRule', 'updateRule', 'deleteRule')}}
ok = ensure_collection(pb, private)
if ok:
current = pb.get_collection(spec['name'])
if current and any(current.get(rule) is not None for rule in ('listRule', 'viewRule', 'createRule', 'updateRule', 'deleteRule')):
pb.request('PATCH', f"/api/collections/{current['id']}", admin=True,
json={rule: None for rule in ('listRule', 'viewRule', 'createRule', 'updateRule', 'deleteRule')})
results.append(ok)
if all(results): _selected_ready.add(key)
return all(results)
def _legacy_schema(fields: list[dict[str, Any]]) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for f in fields:
item: dict[str, Any] = {
"name": f["name"],
"type": f["type"],
"required": bool(f.get("required")),
}
ftype = f.get("type")
if ftype == "select" and "values" in f:
item["options"] = {
"maxSelect": f.get("maxSelect", 1),
"values": f["values"],
}
elif ftype == "json":
max_size = 2_000_000
if isinstance(f.get("options"), dict) and f["options"].get("maxSize"):
max_size = int(f["options"]["maxSize"])
elif f.get("maxSize"):
max_size = int(f["maxSize"])
item["options"] = {"maxSize": max_size}
elif ftype == "text" and f.get("max"):
item["options"] = {"min": None, "max": int(f["max"]), "pattern": ""}
out.append(item)
return out
def _field_names(collection: dict[str, Any] | None) -> set[str]:
if not collection:
return set()
fields = collection.get("fields") or collection.get("schema") or []
return {
str(f.get("name") or "")
for f in fields
if f.get("name") and f.get("name") != "id"
}
def _create_payload(body: dict[str, Any]) -> dict[str, Any]:
"""Prefer modern `fields` (PB ≥0.23); include legacy `schema` for older US boxes."""
fields = body.get("fields") or []
payload: dict[str, Any] = {
"name": body["name"],
"type": "base",
"listRule": body.get("listRule", ""),
"viewRule": body.get("viewRule", ""),
"createRule": body.get("createRule", ""),
"updateRule": body.get("updateRule", ""),
"deleteRule": body.get("deleteRule", ""),
"fields": fields,
"schema": _legacy_schema(fields),
}
if body.get("indexes"):
payload["indexes"] = body["indexes"]
return payload
def _sync_fields(client: PocketBaseClient, existing: dict[str, Any], body: dict[str, Any]) -> bool:
"""PATCH missing custom fields onto an existing collection."""
have = _field_names(existing)
want = [f for f in (body.get("fields") or []) if f.get("name")]
missing = [f for f in want if f["name"] not in have]
if not missing and have:
return True
# Preserve field IDs and extensions already present on production collections.
existing_fields = existing.get("fields") or existing.get("schema") or []
modern = "fields" in existing
patch: dict[str, Any] = (
{"fields": [*existing_fields, *missing]} if modern
else {"schema": [*existing_fields, *_legacy_schema(missing)]}
)
if body.get("indexes"):
patch["indexes"] = list(dict.fromkeys([*(existing.get("indexes") or []), *body["indexes"]]))
expected = {field["name"] for field in want}
try:
client.request(
"PATCH",
f"/api/collections/{existing['id']}",
admin=True,
json=patch,
)
if not expected.issubset(_field_names(client.get_collection(body["name"]))):
raise PocketBaseError("collection update did not persist requested fields")
log.info(
"patched PB collection %s (+%d fields)",
body["name"],
len(missing) if missing else len(want),
)
return True
except PocketBaseError as exc:
# Older PB: try schema key
try:
client.request(
"PATCH",
f"/api/collections/{existing['id']}",
admin=True,
json={"schema": [*existing_fields, *_legacy_schema(missing)]},
)
if not expected.issubset(_field_names(client.get_collection(body["name"]))):
raise PocketBaseError("legacy schema update did not persist requested fields")
log.info("patched PB collection %s via legacy schema", body["name"])
return True
except PocketBaseError as exc2:
log.warning("PB patch %s failed: %s / %s", body["name"], exc, exc2)
return False
def ensure_collection(client: PocketBaseClient, body: dict[str, Any]) -> bool:
name = body["name"]
existing = client.get_collection(name)
if existing:
have = _field_names(existing)
expected = {f["name"] for f in (body.get("fields") or []) if f.get("name")}
if expected and expected.issubset(have):
return True
return _sync_fields(client, existing, body)
payload = _create_payload(body)
try:
created = client.create_collection(payload)
# PB 0.25 may still ignore schema — verify and patch
have = _field_names(created)
expected = {f["name"] for f in (body.get("fields") or []) if f.get("name")}
if expected and not expected.issubset(have):
return _sync_fields(client, created, body)
log.info("created PB collection %s", name)
return True
except PocketBaseError as exc_create:
# Race: created elsewhere
existing = client.get_collection(name)
if existing:
return _sync_fields(client, existing, body)
log.warning("PB create %s failed: %s", name, exc_create)
return False
def ensure_all_collections(client: PocketBaseClient | None = None) -> dict[str, bool]:
global _ensured
pb = client or get_pb()
results: dict[str, bool] = {}
for body in ALL_COLLECTIONS:
name = body["name"]
try:
results[name] = ensure_collection(pb, body)
except Exception as exc: # pragma: no cover
log.warning("ensure %s: %s", name, exc)
results[name] = False
_ensured = all(results.values()) if results else False
return results
def ensure_once() -> bool:
global _ensured
if _ensured:
return True
results = ensure_all_collections()
ok = all(results.values()) if results else False
_ensured = ok
return ok