The web server now runs a scheduler over schedules kept in SQLite
(~/.local/share/receipt-maker, outside the clone). A schedule is a
trigger, a receipt made of blocks, and options:
- Triggers: once, recurring (rrule-based, DST-safe), sun times,
reminders before calendar (ICS) events, RSS/JSON watchers, webhooks
with per-schedule secrets.
- Blocks, rendered fresh as one job: templated notes ({date},
{days_until:..}, rotating {choice}, trigger vars), QR, saved images,
random image, calendar agenda, feed headlines, dividers.
- Rules: quiet hours (hold/skip/ignore), daily cap, pause, catch-up
window for missed runs (never replayed), retries on connect failure
only; a mid-job drop (new PrinterDropped) is never resent.
receipt.py renders through composable Blocks (render_note/image/qr are
wrappers, output unchanged). Print history persists, with Print again.
The page moves to web/ with Print (note/image/QR + paper preview),
Schedules (presets, editor with live preview and next runs), History
and Settings tabs.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
410 lines
15 KiB
Python
410 lines
15 KiB
Python
"""SQLite storage for the web server: schedules, print history, settings and sources.
|
|
|
|
One connection behind a lock: traffic is a person and a scheduler, and it lets
|
|
tests use ":memory:". The file lives outside the clone (RECEIPT_DATA_DIR), so
|
|
deploys and rollbacks never touch it; migrations are additive only, so code
|
|
rolled back by update.sh still reads a newer database.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import secrets
|
|
import sqlite3
|
|
import threading
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
DATA_DIR_ENV = "RECEIPT_DATA_DIR"
|
|
DB_NAME = "receipt.db"
|
|
KEEP_PAYLOADS = 50 # newest runs whose bytes are kept for "Print again"
|
|
KEEP_RUNS = 2000
|
|
|
|
# Numbered schema steps; PRAGMA user_version records how many have run.
|
|
# Only ever append, and only add tables/columns: see the module docstring.
|
|
MIGRATIONS = [
|
|
"""
|
|
CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
CREATE TABLE schedules (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
enabled INTEGER NOT NULL DEFAULT 1,
|
|
spec TEXT NOT NULL,
|
|
next_run_at TEXT,
|
|
last_run_at TEXT,
|
|
last_status TEXT,
|
|
last_message TEXT,
|
|
created_at TEXT NOT NULL,
|
|
updated_at TEXT NOT NULL
|
|
);
|
|
CREATE TABLE runs (
|
|
id TEXT PRIMARY KEY,
|
|
kind TEXT NOT NULL,
|
|
source TEXT NOT NULL,
|
|
schedule_id TEXT,
|
|
name TEXT,
|
|
user TEXT,
|
|
state TEXT NOT NULL,
|
|
message TEXT NOT NULL DEFAULT '',
|
|
error TEXT,
|
|
created_at TEXT NOT NULL,
|
|
finished_at TEXT,
|
|
payload BLOB
|
|
);
|
|
CREATE INDEX runs_created ON runs (created_at);
|
|
CREATE INDEX runs_schedule ON runs (schedule_id, created_at);
|
|
CREATE TABLE trigger_state (
|
|
schedule_id TEXT NOT NULL,
|
|
key TEXT NOT NULL,
|
|
value TEXT NOT NULL,
|
|
PRIMARY KEY (schedule_id, key)
|
|
);
|
|
CREATE TABLE assets (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
data BLOB NOT NULL,
|
|
created_at TEXT NOT NULL
|
|
);
|
|
CREATE TABLE sources (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
kind TEXT NOT NULL,
|
|
url TEXT NOT NULL,
|
|
created_at TEXT NOT NULL
|
|
);
|
|
""",
|
|
]
|
|
|
|
ACTIVE_STATES = ("queued", "printing")
|
|
|
|
|
|
def default_path() -> Path:
|
|
base = os.environ.get(DATA_DIR_ENV) or Path.home() / ".local" / "share" / "receipt-maker"
|
|
return Path(base) / DB_NAME
|
|
|
|
|
|
UTC = timezone.utc # noqa: UP017 - datetime.UTC needs Python 3.11
|
|
|
|
|
|
def utcnow() -> datetime:
|
|
return datetime.now(UTC)
|
|
|
|
|
|
def iso(dt: datetime | None) -> str | None:
|
|
"""UTC ISO-8601 with a Z, the one timestamp format in the database and the API."""
|
|
if dt is None:
|
|
return None
|
|
return dt.astimezone(UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
|
|
|
|
|
|
def parse_iso(value: str | None) -> datetime | None:
|
|
if not value:
|
|
return None
|
|
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
|
|
|
|
def new_id() -> str:
|
|
return secrets.token_hex(8)
|
|
|
|
|
|
class Store:
|
|
def __init__(self, path: Path | str = ":memory:"):
|
|
self.path = str(path)
|
|
if self.path != ":memory:":
|
|
Path(self.path).parent.mkdir(parents=True, exist_ok=True)
|
|
self._lock = threading.RLock()
|
|
self._conn = sqlite3.connect(self.path, check_same_thread=False, isolation_level=None)
|
|
self._conn.row_factory = sqlite3.Row
|
|
self._conn.execute("PRAGMA foreign_keys = ON")
|
|
self.migrate()
|
|
|
|
# --- plumbing ---
|
|
|
|
def _execute(self, sql: str, params: tuple | dict = ()) -> sqlite3.Cursor:
|
|
with self._lock:
|
|
return self._conn.execute(sql, params)
|
|
|
|
def _rows(self, sql: str, params: tuple | dict = ()) -> list[dict]:
|
|
with self._lock:
|
|
return [dict(r) for r in self._conn.execute(sql, params).fetchall()]
|
|
|
|
def _row(self, sql: str, params: tuple | dict = ()) -> dict | None:
|
|
rows = self._rows(sql, params)
|
|
return rows[0] if rows else None
|
|
|
|
def _transaction(self, statements: list[tuple[str, tuple]]) -> None:
|
|
with self._lock:
|
|
self._conn.execute("BEGIN")
|
|
try:
|
|
for sql, params in statements:
|
|
self._conn.execute(sql, params)
|
|
except BaseException:
|
|
self._conn.execute("ROLLBACK")
|
|
raise
|
|
self._conn.execute("COMMIT")
|
|
|
|
@property
|
|
def version(self) -> int:
|
|
return self._execute("PRAGMA user_version").fetchone()[0]
|
|
|
|
def migrate(self) -> None:
|
|
with self._lock:
|
|
version = self.version
|
|
if version >= len(MIGRATIONS):
|
|
return
|
|
if version > 0 and self.path != ":memory:":
|
|
backup = sqlite3.connect(f"{self.path}.bak-v{version}")
|
|
with backup:
|
|
self._conn.backup(backup)
|
|
backup.close()
|
|
for number, script in enumerate(MIGRATIONS[version:], start=version + 1):
|
|
self._conn.executescript(
|
|
f"BEGIN; {script}; PRAGMA user_version = {number}; COMMIT;"
|
|
)
|
|
|
|
# --- settings ---
|
|
|
|
def settings(self) -> dict:
|
|
return {r["key"]: json.loads(r["value"]) for r in self._rows("SELECT * FROM settings")}
|
|
|
|
def save_settings(self, values: dict) -> None:
|
|
self._transaction(
|
|
[
|
|
("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (k, json.dumps(v)))
|
|
for k, v in values.items()
|
|
]
|
|
)
|
|
|
|
# --- schedules ---
|
|
|
|
@staticmethod
|
|
def _schedule(row: dict | None) -> dict | None:
|
|
if row is None:
|
|
return None
|
|
row["enabled"] = bool(row["enabled"])
|
|
row["spec"] = json.loads(row["spec"])
|
|
return row
|
|
|
|
def schedules(self) -> list[dict]:
|
|
rows = self._rows("SELECT * FROM schedules ORDER BY created_at")
|
|
return [self._schedule(r) for r in rows]
|
|
|
|
def schedule(self, schedule_id: str) -> dict | None:
|
|
return self._schedule(self._row("SELECT * FROM schedules WHERE id = ?", (schedule_id,)))
|
|
|
|
def add_schedule(self, name: str, spec: dict, enabled: bool = True) -> dict:
|
|
now = iso(utcnow())
|
|
schedule_id = new_id()
|
|
self._execute(
|
|
"INSERT INTO schedules (id, name, enabled, spec, created_at, updated_at)"
|
|
" VALUES (?, ?, ?, ?, ?, ?)",
|
|
(schedule_id, name, int(enabled), json.dumps(spec), now, now),
|
|
)
|
|
return self.schedule(schedule_id)
|
|
|
|
def update_schedule(self, schedule_id: str, **fields) -> dict | None:
|
|
"""Set columns; spec is stored as JSON. updated_at only moves for user edits."""
|
|
if not fields:
|
|
return self.schedule(schedule_id)
|
|
if "spec" in fields:
|
|
fields["spec"] = json.dumps(fields["spec"])
|
|
if "enabled" in fields:
|
|
fields["enabled"] = int(fields["enabled"])
|
|
allowed = {
|
|
"name", "enabled", "spec", "next_run_at", "last_run_at", "last_status",
|
|
"last_message", "updated_at",
|
|
}
|
|
unknown = set(fields) - allowed
|
|
if unknown:
|
|
raise ValueError(f"unknown schedule fields: {sorted(unknown)}")
|
|
assignments = ", ".join(f"{k} = :{k}" for k in fields) # keys are whitelisted above
|
|
self._execute(
|
|
f"UPDATE schedules SET {assignments} WHERE id = :id", # noqa: S608
|
|
{**fields, "id": schedule_id},
|
|
)
|
|
return self.schedule(schedule_id)
|
|
|
|
def delete_schedule(self, schedule_id: str) -> bool:
|
|
with self._lock:
|
|
deleted = self._execute("DELETE FROM schedules WHERE id = ?", (schedule_id,)).rowcount
|
|
self._execute("DELETE FROM trigger_state WHERE schedule_id = ?", (schedule_id,))
|
|
return bool(deleted)
|
|
|
|
# --- per-schedule trigger state (seen items, fired events, rotations, secrets) ---
|
|
|
|
def state(self, schedule_id: str, key: str, default=None):
|
|
row = self._row(
|
|
"SELECT value FROM trigger_state WHERE schedule_id = ? AND key = ?", (schedule_id, key)
|
|
)
|
|
return default if row is None else json.loads(row["value"])
|
|
|
|
def set_state(self, schedule_id: str, key: str, value) -> None:
|
|
self._execute(
|
|
"INSERT OR REPLACE INTO trigger_state (schedule_id, key, value) VALUES (?, ?, ?)",
|
|
(schedule_id, key, json.dumps(value)),
|
|
)
|
|
|
|
def clear_state(self, schedule_id: str, keep: tuple[str, ...] = ()) -> None:
|
|
marks = ", ".join("?" * len(keep)) or "''"
|
|
self._execute(
|
|
f"DELETE FROM trigger_state WHERE schedule_id = ? AND key NOT IN ({marks})", # noqa: S608
|
|
(schedule_id, *keep),
|
|
)
|
|
|
|
# --- print history ---
|
|
|
|
def add_run(
|
|
self,
|
|
kind: str,
|
|
source: str,
|
|
state: str,
|
|
*,
|
|
run_id: str | None = None,
|
|
schedule_id: str | None = None,
|
|
name: str | None = None,
|
|
user: str | None = None,
|
|
message: str = "",
|
|
error: str | None = None,
|
|
payload: bytes | None = None,
|
|
created_at: datetime | None = None,
|
|
) -> str:
|
|
run_id = run_id or new_id()
|
|
created = created_at or utcnow()
|
|
finished = iso(created) if state not in ACTIVE_STATES else None
|
|
self._transaction(
|
|
[
|
|
(
|
|
"INSERT INTO runs (id, kind, source, schedule_id, name, user, state, message,"
|
|
" error, created_at, finished_at, payload)"
|
|
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
(run_id, kind, source, schedule_id, name, user, state, message, error,
|
|
iso(created), finished, payload),
|
|
),
|
|
(
|
|
"UPDATE runs SET payload = NULL WHERE payload IS NOT NULL AND id NOT IN"
|
|
" (SELECT id FROM runs WHERE payload IS NOT NULL"
|
|
" ORDER BY created_at DESC LIMIT ?)",
|
|
(KEEP_PAYLOADS,),
|
|
),
|
|
(
|
|
"DELETE FROM runs WHERE id NOT IN"
|
|
" (SELECT id FROM runs ORDER BY created_at DESC LIMIT ?)",
|
|
(KEEP_RUNS,),
|
|
),
|
|
]
|
|
)
|
|
return run_id
|
|
|
|
def finish_run(self, run_id: str, state: str, message: str, error: str | None = None) -> None:
|
|
finished = iso(utcnow()) if state not in ACTIVE_STATES else None
|
|
self._execute(
|
|
"UPDATE runs SET state = ?, message = ?, error = ?, finished_at = ? WHERE id = ?",
|
|
(state, message, error, finished, run_id),
|
|
)
|
|
|
|
def fail_interrupted_runs(self) -> int:
|
|
"""Runs left queued/printing by a previous process can't finish any more."""
|
|
return self._execute(
|
|
"UPDATE runs SET state = 'failed', error = 'failed', finished_at = ?,"
|
|
" message = 'The server restarted before this printed.'"
|
|
" WHERE state IN ('queued', 'printing')",
|
|
(iso(utcnow()),),
|
|
).rowcount
|
|
|
|
def runs(
|
|
self,
|
|
limit: int = 50,
|
|
before: str | None = None,
|
|
schedule_id: str | None = None,
|
|
state: str | None = None,
|
|
) -> list[dict]:
|
|
where, params = [], []
|
|
if before:
|
|
where.append("created_at < ?")
|
|
params.append(before)
|
|
if schedule_id:
|
|
where.append("schedule_id = ?")
|
|
params.append(schedule_id)
|
|
if state:
|
|
where.append("state = ?")
|
|
params.append(state)
|
|
clause = f"WHERE {' AND '.join(where)}" if where else ""
|
|
sql = (
|
|
"SELECT id, kind, source, schedule_id, name, user, state, message, error," # noqa: S608
|
|
f" created_at, finished_at, payload IS NOT NULL AS has_payload FROM runs {clause}"
|
|
" ORDER BY created_at DESC, rowid DESC LIMIT ?"
|
|
) # the clause is fixed text; values are bound
|
|
return self._rows(sql, (*params, limit))
|
|
|
|
def run_payload(self, run_id: str) -> tuple[dict, bytes] | None:
|
|
row = self._row("SELECT * FROM runs WHERE id = ?", (run_id,))
|
|
if row is None or row["payload"] is None:
|
|
return None
|
|
payload = row.pop("payload")
|
|
return row, payload
|
|
|
|
def count_runs(
|
|
self, since: datetime, sources: tuple[str, ...], states: tuple[str, ...],
|
|
schedule_id: str | None = None,
|
|
) -> int:
|
|
params: list = [iso(since), *sources, *states]
|
|
extra = ""
|
|
if schedule_id:
|
|
extra = " AND schedule_id = ?"
|
|
params.append(schedule_id)
|
|
sql = (
|
|
"SELECT COUNT(*) FROM runs WHERE created_at >= ?" # noqa: S608
|
|
f" AND source IN ({', '.join('?' * len(sources))})"
|
|
f" AND state IN ({', '.join('?' * len(states))}){extra}"
|
|
) # only placeholders are interpolated
|
|
return self._execute(sql, tuple(params)).fetchone()[0]
|
|
|
|
# --- uploaded images for scheduled receipts ---
|
|
|
|
def add_asset(self, name: str, data: bytes) -> dict:
|
|
asset_id = new_id()
|
|
self._execute(
|
|
"INSERT INTO assets (id, name, data, created_at) VALUES (?, ?, ?, ?)",
|
|
(asset_id, name, data, iso(utcnow())),
|
|
)
|
|
return {"id": asset_id, "name": name, "size": len(data)}
|
|
|
|
def assets(self) -> list[dict]:
|
|
return self._rows(
|
|
"SELECT id, name, length(data) AS size, created_at FROM assets ORDER BY created_at DESC"
|
|
)
|
|
|
|
def asset(self, asset_id: str) -> bytes | None:
|
|
row = self._row("SELECT data FROM assets WHERE id = ?", (asset_id,))
|
|
return None if row is None else row["data"]
|
|
|
|
def delete_asset(self, asset_id: str) -> bool:
|
|
return bool(self._execute("DELETE FROM assets WHERE id = ?", (asset_id,)).rowcount)
|
|
|
|
# --- saved calendar / feed URLs ---
|
|
|
|
def sources(self) -> list[dict]:
|
|
return self._rows("SELECT * FROM sources ORDER BY name COLLATE NOCASE")
|
|
|
|
def source(self, source_id: str) -> dict | None:
|
|
return self._row("SELECT * FROM sources WHERE id = ?", (source_id,))
|
|
|
|
def add_source(self, name: str, kind: str, url: str) -> dict:
|
|
source_id = new_id()
|
|
self._execute(
|
|
"INSERT INTO sources (id, name, kind, url, created_at) VALUES (?, ?, ?, ?, ?)",
|
|
(source_id, name, kind, url, iso(utcnow())),
|
|
)
|
|
return self.source(source_id)
|
|
|
|
def update_source(self, source_id: str, name: str, kind: str, url: str) -> dict | None:
|
|
self._execute(
|
|
"UPDATE sources SET name = ?, kind = ?, url = ? WHERE id = ?",
|
|
(name, kind, url, source_id),
|
|
)
|
|
return self.source(source_id)
|
|
|
|
def delete_source(self, source_id: str) -> bool:
|
|
return bool(self._execute("DELETE FROM sources WHERE id = ?", (source_id,)).rowcount)
|