Files
webmail-client/backend/app/plugins/kv.py
T

64 lines
2.3 KiB
Python
Raw Normal View History

"""Namespaced key/value store handed to plugins (SPEC §11 ``plugin_kv``).
A :class:`PluginKv` is bound to one (plugin, user_id) slice of the core
``plugin_kv`` table; values are arbitrary JSON. This is the light-state store
every plugin gets — heavy plugins use their own ``plg_``-prefixed tables (§11.1).
"""
from __future__ import annotations
import uuid
from typing import Any
from sqlalchemy import delete, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from app.db import session_scope
from app.models import PluginKv
class PluginKvStore:
"""CRUD over one plugin's per-user KV slice. Instantiate via ``sdk.kv(user_id)``."""
def __init__(self, plugin: str, user_id: uuid.UUID) -> None:
self._plugin = plugin
self._user_id = user_id
async def get(self, key: str, default: Any = None) -> Any:
async with session_scope() as session:
row = await session.get(PluginKv, (self._plugin, self._user_id, key))
return row.value if row is not None else default
async def set(self, key: str, value: Any) -> None:
"""Upsert ``key`` -> ``value`` (JSON-serialisable)."""
stmt = (
pg_insert(PluginKv)
.values(plugin=self._plugin, user_id=self._user_id, key=key, value=value)
.on_conflict_do_update(
index_elements=[PluginKv.plugin, PluginKv.user_id, PluginKv.key],
set_={"value": value},
)
)
async with session_scope() as session:
await session.execute(stmt)
async def delete(self, key: str) -> None:
async with session_scope() as session:
await session.execute(
delete(PluginKv).where(
PluginKv.plugin == self._plugin,
PluginKv.user_id == self._user_id,
PluginKv.key == key,
)
)
async def items(self) -> dict[str, Any]:
"""Return every key/value in this plugin+user slice."""
async with session_scope() as session:
rows = await session.execute(
select(PluginKv.key, PluginKv.value).where(
PluginKv.plugin == self._plugin, PluginKv.user_id == self._user_id
)
)
return dict(rows.all()) # type: ignore[arg-type]