Source code for s365b.core.settings_store

"""Typed access to runtime settings stored in the ``setting`` table.

Each settings group is a Pydantic model with a fixed key. Non-secret fields
are stored as JSON in ``value``; secrets go through :class:`SecretBox` into
``secret_enc`` and are never returned by the API.
"""

from __future__ import annotations

import json
from typing import ClassVar

from pydantic import BaseModel
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession

from s365b.core.secrets import SecretBox
from s365b.db.models import Setting


[docs] class SettingsGroup(BaseModel): """Base class for a group of runtime settings. Subclasses set :attr:`key` and give every field a default, so a missing row simply means "defaults". """
[docs] key: ClassVar[str]
[docs] async def load[T: SettingsGroup](session: AsyncSession, model: type[T]) -> T: """Load a settings group, falling back to defaults. Args: session: Open session. model: The settings model. Returns: The settings. """ row = await session.get(Setting, model.key) return model.model_validate(row.value if row else {})
[docs] async def save(session: AsyncSession, settings: SettingsGroup) -> None: """Store a settings group (non-secret fields only). Args: session: Open session; the caller commits. settings: The settings to store. """ value = settings.model_dump(mode="json") await session.execute( insert(Setting) .values(key=settings.key, value=value) .on_conflict_do_update(index_elements=["key"], set_={"value": value}) )
[docs] async def load_secrets(session: AsyncSession, key: str, box: SecretBox) -> dict[str, str]: """Load the secret part of a settings group. Args: session: Open session. key: Settings key. box: Secret box holding the master key. Returns: Secret values by name; empty if none stored. """ row = await session.get(Setting, key) if row is None or not row.secret_enc: return {} data: dict[str, str] = json.loads(box.decrypt(row.secret_enc, f"setting:{key}")) return data
[docs] async def save_secrets( session: AsyncSession, key: str, secrets: dict[str, str], box: SecretBox ) -> None: """Store the secret part of a settings group, replacing what was there. Args: session: Open session; the caller commits. key: Settings key. secrets: Secret values by name. box: Secret box holding the master key. """ enc = box.encrypt(json.dumps(secrets).encode(), f"setting:{key}") await session.execute( insert(Setting) .values(key=key, value={}, secret_enc=enc) .on_conflict_do_update(index_elements=["key"], set_={"secret_enc": enc}) )