|
| 1 | +"""Server-side capture of client (browser/PWA) logs and crashes. |
| 2 | +
|
| 3 | +In a PWA there is no devtools console for the user (or us) to read, so a |
| 4 | +front-end crash is invisible unless the client ships it somewhere. This store is |
| 5 | +that sink: the desktop posts errors, warnings, and debug lines to |
| 6 | +POST /api/client-logs and they land here, readable by an admin via |
| 7 | +GET /api/client-logs. It is the substrate for chasing crashes like the Messages |
| 8 | +app failure (#106 log capture). |
| 9 | +
|
| 10 | +Bounded by design: a crash loop must not grow the table without limit, so every |
| 11 | +insert prunes to the most recent MAX_ROWS rows (a ring buffer), and message/stack |
| 12 | +text is length-capped. |
| 13 | +""" |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import uuid |
| 17 | +from datetime import datetime, timezone |
| 18 | + |
| 19 | +from tinyagentos.base_store import BaseStore |
| 20 | + |
| 21 | +# The levels a client may report. Mirrors console severities plus an explicit |
| 22 | +# "fatal" for an uncaught error / error-boundary crash. |
| 23 | +VALID_LEVELS = frozenset({"fatal", "error", "warn", "info", "debug"}) |
| 24 | + |
| 25 | +MAX_MESSAGE_LEN = 4_000 |
| 26 | +MAX_STACK_LEN = 16_000 |
| 27 | +MAX_SOURCE_LEN = 200 |
| 28 | +MAX_URL_LEN = 1_000 |
| 29 | +MAX_UA_LEN = 500 |
| 30 | +# Ring-buffer cap: keep only the most recent N entries across all users so a |
| 31 | +# crash loop posting on every render cannot grow the DB unbounded. |
| 32 | +MAX_ROWS = 2_000 |
| 33 | + |
| 34 | + |
| 35 | +class ClientLogStore(BaseStore): |
| 36 | + SCHEMA = """ |
| 37 | + CREATE TABLE IF NOT EXISTS client_logs ( |
| 38 | + id TEXT NOT NULL PRIMARY KEY, |
| 39 | + user_id TEXT NOT NULL, |
| 40 | + level TEXT NOT NULL, |
| 41 | + message TEXT NOT NULL, |
| 42 | + source TEXT NOT NULL DEFAULT '', |
| 43 | + url TEXT NOT NULL DEFAULT '', |
| 44 | + stack TEXT NOT NULL DEFAULT '', |
| 45 | + user_agent TEXT NOT NULL DEFAULT '', |
| 46 | + created_at TEXT NOT NULL |
| 47 | + ); |
| 48 | + CREATE INDEX IF NOT EXISTS client_logs_created |
| 49 | + ON client_logs (created_at DESC); |
| 50 | + CREATE INDEX IF NOT EXISTS client_logs_level_created |
| 51 | + ON client_logs (level, created_at DESC); |
| 52 | + """ |
| 53 | + |
| 54 | + async def create( |
| 55 | + self, |
| 56 | + *, |
| 57 | + user_id: str, |
| 58 | + level: str, |
| 59 | + message: str, |
| 60 | + source: str = "", |
| 61 | + url: str = "", |
| 62 | + stack: str = "", |
| 63 | + user_agent: str = "", |
| 64 | + ) -> dict: |
| 65 | + assert self._db is not None |
| 66 | + item_id = str(uuid.uuid4()) |
| 67 | + created_at = datetime.now(timezone.utc).isoformat() |
| 68 | + row = { |
| 69 | + "id": item_id, |
| 70 | + "user_id": user_id, |
| 71 | + "level": level, |
| 72 | + "message": message[:MAX_MESSAGE_LEN], |
| 73 | + "source": source[:MAX_SOURCE_LEN], |
| 74 | + "url": url[:MAX_URL_LEN], |
| 75 | + "stack": stack[:MAX_STACK_LEN], |
| 76 | + "user_agent": user_agent[:MAX_UA_LEN], |
| 77 | + "created_at": created_at, |
| 78 | + } |
| 79 | + await self._db.execute( |
| 80 | + """ |
| 81 | + INSERT INTO client_logs |
| 82 | + (id, user_id, level, message, source, url, stack, user_agent, created_at) |
| 83 | + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) |
| 84 | + """, |
| 85 | + ( |
| 86 | + row["id"], row["user_id"], row["level"], row["message"], |
| 87 | + row["source"], row["url"], row["stack"], row["user_agent"], |
| 88 | + row["created_at"], |
| 89 | + ), |
| 90 | + ) |
| 91 | + # Ring-buffer prune: drop everything older than the newest MAX_ROWS. |
| 92 | + await self._db.execute( |
| 93 | + """ |
| 94 | + DELETE FROM client_logs WHERE id NOT IN ( |
| 95 | + SELECT id FROM client_logs ORDER BY created_at DESC LIMIT ? |
| 96 | + ) |
| 97 | + """, |
| 98 | + (MAX_ROWS,), |
| 99 | + ) |
| 100 | + await self._db.commit() |
| 101 | + return row |
| 102 | + |
| 103 | + async def list_recent( |
| 104 | + self, *, level: str | None = None, limit: int = 200 |
| 105 | + ) -> list[dict]: |
| 106 | + """Most recent entries first, optionally filtered by level. Admin-read.""" |
| 107 | + assert self._db is not None |
| 108 | + limit = max(1, min(limit, 1000)) |
| 109 | + cols = "id, user_id, level, message, source, url, stack, user_agent, created_at" |
| 110 | + if level: |
| 111 | + cursor = await self._db.execute( |
| 112 | + f"SELECT {cols} FROM client_logs WHERE level = ? " |
| 113 | + "ORDER BY created_at DESC LIMIT ?", |
| 114 | + (level, limit), |
| 115 | + ) |
| 116 | + else: |
| 117 | + cursor = await self._db.execute( |
| 118 | + f"SELECT {cols} FROM client_logs ORDER BY created_at DESC LIMIT ?", |
| 119 | + (limit,), |
| 120 | + ) |
| 121 | + rows = await cursor.fetchall() |
| 122 | + keys = cols.split(", ") |
| 123 | + return [dict(zip(keys, r)) for r in rows] |
0 commit comments