Files
Atrium/backend/app/services/settings.py
T

143 lines
6.0 KiB
Python

"""Instance settings as auditable key/value rows — a closed, typed set.
Secrets never live here — they come from the environment. `app_setting` is for choices an
administrator makes in the console and that must be visible in the audit log afterwards.
The set of keys is **closed**: `SPECS` is the whole vocabulary, and a write naming any other key is
refused. An open key/value endpoint lets an administrator (or anything holding an admin session)
park arbitrary strings in a table the console trusts, and a typo silently creates a setting nothing
reads. Rows for keys that are no longer specified are ignored rather than served — and keys starting
with `_` are reserved for internal markers (e.g. `seed.CATALOG_SEEDED`): never specified, never
served, and not to be pruned as "unknown".
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import Availability
from ..errors import ValidationError
from ..models import AppSetting
TEXT, BOOL, CHOICE = "text", "bool", "choice"
@dataclass(frozen=True)
class Spec:
kind: str
default: str
max_length: int = 0
required: bool = False
choices: tuple[str, ...] = ()
SPECS: dict[str, Spec] = {
# What the console calls this instance — the sidebar brand and the page title.
"instance_name": Spec(TEXT, "Atrium", max_length=80, required=True),
# Shown above the launcher on Home. Plain text; the console escapes it.
"welcome_message": Spec(TEXT, "", max_length=500),
# Who to ask about access, shown in the marketplace. Plain text, never rendered as a link.
"support_contact": Spec(TEXT, "", max_length=200),
# Whether launching a module opens a new tab or replaces Atrium. The default is the same tab:
# a module is a path on this same origin, so launching one is navigation, not leaving the site,
# and a tab per module is how someone ends up with four of them open.
"launcher_open_mode": Spec(CHOICE, "same_tab", choices=("new_tab", "same_tab")),
# Whether users may ask for a `selected` module they are not offered.
"allow_access_requests": Spec(BOOL, "true"),
# The availability a newly added module starts with.
"default_availability": Spec(CHOICE, Availability.everyone.value,
choices=tuple(a.value for a in Availability)),
# Whether a firm skill or agent (and each of its later versions) waits for an administrator's
# approval before the firm sees it, or is published at once.
"skills_firm_publish": Spec(CHOICE, "approval", choices=("approval", "direct")),
# Who may export a firm skill or agent as a pack. Your own you may always export.
"skills_firm_export": Spec(CHOICE, "administrator", choices=("administrator", "everyone")),
}
def _typed(spec: Spec, raw: str) -> Any:
return raw == "true" if spec.kind == BOOL else raw
def _normalize(key: str, value: Any) -> str:
"""The stored string for `value`, or ValidationError. Never trusts the caller's type."""
spec = SPECS.get(key)
if spec is None:
raise ValidationError(f"Unknown setting: {key}.")
if spec.kind == BOOL:
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, str) and value.lower() in ("true", "false"):
return value.lower()
raise ValidationError(f"{key} must be true or false.")
if not isinstance(value, str):
raise ValidationError(f"{key} must be text.")
value = value.strip()
if spec.kind == CHOICE:
if value not in spec.choices:
raise ValidationError(f"{key} must be one of: {', '.join(spec.choices)}.")
return value
if spec.required and not value:
raise ValidationError(f"{key} cannot be empty.")
if spec.max_length and len(value) > spec.max_length:
raise ValidationError(f"{key} is longer than {spec.max_length} characters.")
if any(ord(c) < 32 and c not in "\n\t" for c in value):
raise ValidationError(f"{key} contains control characters.")
return value
def _stored(db: DbSession) -> dict[str, str]:
return {r.key: r.value for r in db.scalars(select(AppSetting)).all() if r.key in SPECS}
def get(db: DbSession, key: str) -> Any:
"""The typed value of a specified setting. Unknown keys are a programming error."""
spec = SPECS[key]
row = db.get(AppSetting, key)
return _typed(spec, row.value if row else spec.default)
def public_config(db: DbSession) -> dict[str, Any]:
"""Every setting, typed. None of them are secrets, so any signed-in user may read these."""
stored = _stored(db)
return {k: _typed(s, stored.get(k, s.default)) for k, s in SPECS.items()}
def describe(db: DbSession) -> list[dict]:
"""The settings form, for administrators: value, default and constraints per key."""
stored = _stored(db)
return [{
"key": k, "kind": s.kind,
"value": _typed(s, stored.get(k, s.default)), "default": _typed(s, s.default),
"max_length": s.max_length or None, "required": s.required,
"choices": list(s.choices),
} for k, s in SPECS.items()]
def update(db: DbSession, values: dict[str, Any], *, actor_id=None) -> dict[str, list]:
"""Validate every value first, then write the ones that changed. All or nothing.
Returns `{key: [before, after]}` for the changed keys — the audit diff.
"""
if not values:
raise ValidationError("Nothing to change.")
normalized = {k: _normalize(k, v) for k, v in values.items()}
stored = _stored(db)
changed: dict[str, list] = {}
for key, value in normalized.items():
before = stored.get(key, SPECS[key].default)
if before == value:
continue
row = db.get(AppSetting, key)
if row is None:
db.add(AppSetting(key=key, value=value, updated_by=actor_id))
else:
row.value = value
row.updated_by = actor_id
changed[key] = [before, value]
db.flush()
return changed