nomadro/apps/taro/api/store.py

74 lines
3.4 KiB
Python

"""Taro-only persistence. No imports, credentials or connections to production services."""
import json
import sqlite3
from contextlib import contextmanager
from pathlib import Path
ROOT = Path(__file__).resolve().parent
DEFAULT_DB = ROOT / 'data' / 'preview.sqlite3'
class Store:
def __init__(self, database=DEFAULT_DB):
self.database = Path(database).resolve()
self.database.parent.mkdir(parents=True, exist_ok=True)
self.seed = json.loads((ROOT / 'seed/catalog.json').read_text(encoding='utf8'))
with self.connect() as db:
db.execute('CREATE TABLE IF NOT EXISTS documents (key TEXT PRIMARY KEY, value TEXT NOT NULL)')
for key, value in [('config', self.seed['config']), ('catalogs', self.seed['catalogs'])]:
db.execute('INSERT OR IGNORE INTO documents VALUES (?, ?)', (key, json.dumps(value)))
@contextmanager
def connect(self):
connection = sqlite3.connect(self.database, timeout=10)
try:
with connection:
yield connection
finally:
connection.close()
def get(self, key):
with self.connect() as db:
row = db.execute('SELECT value FROM documents WHERE key=?', (key,)).fetchone()
return json.loads(row[0]) if row else None
def put(self, key, value):
with self.connect() as db:
db.execute('INSERT INTO documents VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',
(key, json.dumps(value, ensure_ascii=False)))
return value
def save_config(self, config, expected_version):
with self.connect() as db:
db.execute('BEGIN IMMEDIATE')
current = json.loads(db.execute("SELECT value FROM documents WHERE key='config'").fetchone()[0])
if current['version'] != expected_version:
raise ValueError('version_conflict')
config = {**config, 'version': current['version'] + 1}
# Preview has no live payment or account bridge provider.
config['flags'] = {**config.get('flags', {}), 'payEnabled': False, 'vipWebBridgeEnabled': False}
db.execute("UPDATE documents SET value=? WHERE key='config'", (json.dumps(config, ensure_ascii=False),))
return config
def update_catalog(self, name, value):
with self.connect() as db:
db.execute('BEGIN IMMEDIATE')
catalogs = json.loads(db.execute("SELECT value FROM documents WHERE key='catalogs'").fetchone()[0])
catalogs[name] = value
db.execute("UPDATE documents SET value=? WHERE key='catalogs'", (json.dumps(catalogs, ensure_ascii=False),))
def append_message(self, channel, item):
key = 'messages:' + channel
with self.connect() as db:
db.execute('BEGIN IMMEDIATE')
row = db.execute('SELECT value FROM documents WHERE key=?', (key,)).fetchone()
items = json.loads(row[0]) if row else []
if item.get('clientId'):
existing = next((row for row in items if row.get('clientId') == item['clientId']), None)
if existing:
return existing
item = {**item, 'seq': len(items) + 1}
db.execute('INSERT INTO documents VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',
(key, json.dumps([*items, item], ensure_ascii=False)))
return item