From 271c230635b386f56f1be14f7c93d2595d9bd72b Mon Sep 17 00:00:00 2001 From: maxime Date: Tue, 24 Nov 2026 16:45:48 +0100 Subject: [PATCH] Poller: the LibreDesk conversations into Supabase, one run or in a loop (read-only on LibreDesk) Co-Authored-By: Claude Opus 5.5 --- poller/__init__.py | 0 poller/poll.py | 163 +++++++++++++++++++++++++++++++++++++ tests/fake_supabase.py | 67 +++++++++++++++ tests/test_guard_poller.py | 26 ++++++ tests/test_poll.py | 147 +++++++++++++++++++++++++++++++++ 5 files changed, 403 insertions(+) create mode 100644 poller/__init__.py create mode 100644 poller/poll.py create mode 100644 tests/fake_supabase.py create mode 100644 tests/test_guard_poller.py create mode 100644 tests/test_poll.py diff --git a/poller/__init__.py b/poller/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/poller/poll.py b/poller/poll.py new file mode 100644 index 0000000..c692358 --- /dev/null +++ b/poller/poll.py @@ -0,0 +1,163 @@ +"""Polls the LibreDesk conversations into Supabase (docs/superpowers/specs/2026-11-24-conversations-supabase-design.md): +the tables conversations and messages (LibreDesk's response kept as is in raw, private notes included), the attachments in +the private bucket attachments, under /. + +LibreDesk is only read, through conversations.pomper.Lecteur (GET only, its key goes only to LibreDesk). Supabase is +written through its REST API (PostgREST, Storage), with the service_role key, which goes only to Supabase. + +A run: the conversations updated since the checkpoint of the last complete run (table checkpoints) minus MARGE, the most +recent first; everything the first time. Each conversation and its messages are upserted: running again never makes a +duplicate. The checkpoint is written only at the end of a complete run: an interrupted run is taken up by the next one. + +LIBREDESK_URL=… LIBREDESK_API_KEY=… LIBREDESK_API_SECRET=… SUPABASE_CONVERSATIONS_URL=… SUPABASE_CONVERSATIONS_KEY=… + python3 -m poller.poll [--every SECONDS] +""" +import argparse +import json +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from datetime import datetime, timezone +from typing import Callable + +from conversations.pomper import MARGE, PERDUE, Lecteur, _date, recentes + +BUCKET = "attachments" +CHECKPOINT = "conversations" +REFUSED = {400, 413} # an attachment Storage refuses (too big, for example): skipped, noted, never blocks the next runs +KEYS = {"checkpoints": "name"} # the primary key of each table; uuid by default + + +class Supabase: + """The client of Supabase, restricted to its REST API (tables and Storage).""" + + def __init__(self, url: str, key: str): + self.url, self._key = url.rstrip("/"), key + + def _request(self, method: str, path: str, body: bytes | None = None, headers: dict | None = None) -> bytes: + if not path.startswith(("/rest/v1/", "/storage/v1/")): + raise ValueError(f"not a Supabase path: {path}") + r = urllib.request.Request(self.url + path, data=body, method=method) + r.add_header("apikey", self._key) + if self._key.startswith("eyJ"): # an old JWT key; a new sb_secret_ key goes only in apikey + r.add_header("Authorization", f"Bearer {self._key}") + for k, v in ({"Content-Type": "application/json"} | (headers or {})).items(): + r.add_header(k, v) + with urllib.request.urlopen(r, timeout=60) as answer: + return answer.read() + + def checkpoint(self) -> datetime | None: + rows = json.loads(self._request("GET", f"/rest/v1/checkpoints?name=eq.{CHECKPOINT}&select=until")) + return _date(rows[0]["until"]) if rows else None + + def write_checkpoint(self, t: datetime) -> None: + self.upsert("checkpoints", [{"name": CHECKPOINT, "until": t.isoformat()}]) + + def upsert(self, table: str, rows: list[dict]) -> None: + self._request("POST", f"/rest/v1/{table}?on_conflict={KEYS.get(table, 'uuid')}", + json.dumps(rows, ensure_ascii=False).encode(), + {"Prefer": "resolution=merge-duplicates,return=minimal"}) + + def objects(self, folder: str) -> set[str]: + """The names of the files under / in the bucket.""" + body = json.dumps({"prefix": f"{folder}/", "limit": 1000}).encode() + return {o["name"] for o in json.loads(self._request("POST", f"/storage/v1/object/list/{BUCKET}", body))} + + def put(self, key: str, content: bytes, type_: str) -> None: + self._request("POST", f"/storage/v1/object/{BUCKET}/{urllib.parse.quote(key)}", content, + {"Content-Type": type_, "x-upsert": "true"}) + + +def _save_attachments(reader: Lecteur, supabase: Supabase, conv_uuid: str, messages: list[dict], log) -> int: + """Uploads the attachments missing from the bucket; each one's url (signed, it expires) becomes its key.""" + present, n = supabase.objects(conv_uuid), 0 + for m in messages: + for i, a in enumerate(m.get("attachments") or []): + name = a.get("uuid") or f"{m['uuid']}-{i}" + key, url = f"{conv_uuid}/{name}", a.get("url") or "" + if url and name not in present: + try: + supabase.put(key, reader.lire(url), a.get("content_type") or "application/octet-stream") + except urllib.error.HTTPError as e: + e.close() + if e.code not in (REFUSED if e.url.startswith(supabase.url) else PERDUE): + raise # a passing failure: the run stops, the next one takes it up + log(f" attachment {key} skipped: {e.code}") + a["url"], a["absent"] = "", True + continue + if url: + m["content"] = (m.get("content") or "").replace(url.replace("&", "&"), url).replace(url, key) + a["url"] = key + n += 1 + return n + + +def poll_once(reader: Lecteur, supabase: Supabase, log=print) -> int: + """One run; returns the number of conversations saved.""" + start, checkpoint, n = datetime.now(timezone.utc), supabase.checkpoint(), 0 + for c in recentes(reader, checkpoint - MARGE if checkpoint else None): + messages = reader.messages(c["uuid"]) + n_attachments = _save_attachments(reader, supabase, c["uuid"], messages, log) + raw = {k: v for k, v in c.items() if k != "previous_conversations"} + ref = c.get("reference_number") + supabase.upsert("conversations", [{ + "uuid": c["uuid"], "reference_number": None if ref is None else str(ref), "subject": c.get("subject"), + "status": c.get("status"), "inbox_name": c.get("inbox_name"), + "contact_email": (c.get("contact") or {}).get("email"), "created_at": c.get("created_at"), + "updated_at": c["updated_at"], "raw": raw}]) + if messages: + supabase.upsert("messages", [{ + "uuid": m["uuid"], "conversation_uuid": c["uuid"], "type": m.get("type"), + "sender_type": m.get("sender_type"), "private": m.get("private"), "created_at": m.get("created_at"), + "raw": m} for m in messages]) + log(f"#{ref} {c.get('subject') or ''}: {len(messages)} messages, {n_attachments} attachments") + n += 1 + supabase.write_checkpoint(start) # only after a complete run + log(f"{n} conversation(s) saved") + return n + + +def _describe(e: Exception) -> str: + """An error for the log, without the signature of an attachment URL.""" + if isinstance(e, urllib.error.HTTPError): + return f"{e.code} on {e.url.split('?')[0]}" + if isinstance(e, urllib.error.URLError): + return f"unreachable: {e.reason}" + return f"{type(e).__name__}: {e}".split("?")[0] + + +def loop(run: Callable[[], int], every: int, log=print, sleep=time.sleep) -> None: + """run() forever, every `every` seconds; a failed run is noted and the next one starts again.""" + while True: + try: + run() + except Exception as e: # noqa: BLE001 — the poller must outlive a failed run + log(f"run failed: {_describe(e)}") + sleep(every) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--every", type=int, help="seconds between two runs; without it, a single run") + a = p.parse_args() + names = ("LIBREDESK_API_KEY", "LIBREDESK_API_SECRET", "SUPABASE_CONVERSATIONS_URL", "SUPABASE_CONVERSATIONS_KEY") + missing = [n for n in names if not os.environ.get(n)] + if missing: + sys.exit("missing variables: " + ", ".join(missing)) + reader = Lecteur(os.environ.get("LIBREDESK_URL", "https://helpdesk.sensima.ch"), + os.environ["LIBREDESK_API_KEY"], os.environ["LIBREDESK_API_SECRET"]) + supabase = Supabase(os.environ["SUPABASE_CONVERSATIONS_URL"], os.environ["SUPABASE_CONVERSATIONS_KEY"]) + log = lambda line: print(line, flush=True) # noqa: E731 + if a.every: + loop(lambda: poll_once(reader, supabase, log), a.every, log) + try: + poll_once(reader, supabase, log) + except Exception as e: # noqa: BLE001 + sys.exit(_describe(e)) + + +if __name__ == "__main__": + main() diff --git a/tests/fake_supabase.py b/tests/fake_supabase.py new file mode 100644 index 0000000..7a8ddae --- /dev/null +++ b/tests/fake_supabase.py @@ -0,0 +1,67 @@ +"""A fake Supabase (http.server): PostgREST upserts and reads of the checkpoint, Storage list and upload, kept in memory.""" +import json +import threading +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +KEYS = {"checkpoints": "name"} # the primary key of each table; uuid by default + + +class FakeSupabase: + def __init__(self): + self.tables: dict[str, dict[str, dict]] = {"conversations": {}, "messages": {}, "checkpoints": {}} + self.objects: dict[str, bytes] = {} + self.requests: list[tuple[str, str, dict]] = [] # (method, path with query, headers with lower-case names) + self.fail: dict[str, int] = {} # path prefix → error code to return + fake = self + + class Handler(BaseHTTPRequestHandler): + def _answer(self, code: int, body=None): + text = json.dumps(body if body is not None else {}).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(text))) + self.end_headers() + self.wfile.write(text) + + def _handle(self): + n = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(n) if n else b"" + fake.requests.append((self.command, self.path, {k.lower(): v for k, v in self.headers.items()})) + url = urllib.parse.urlsplit(self.path) + for prefix, code in fake.fail.items(): + if url.path.startswith(prefix): + return self._answer(code, {"message": "failure"}) + if url.path.startswith("/rest/v1/"): + table = url.path.removeprefix("/rest/v1/") + key = KEYS.get(table, "uuid") + if self.command == "GET": + q = urllib.parse.parse_qs(url.query) + rows = list(fake.tables[table].values()) + for col, vals in q.items(): + if vals[0].startswith("eq."): + rows = [r for r in rows if str(r.get(col)) == vals[0][3:]] + return self._answer(200, rows) + for row in json.loads(raw): + fake.tables[table][row[key]] = fake.tables[table].get(row[key], {}) | row + return self._answer(201) + if url.path == "/storage/v1/object/list/attachments": + prefix = json.loads(raw)["prefix"] + return self._answer(200, [{"name": k[len(prefix):]} for k in fake.objects if k.startswith(prefix)]) + if url.path.startswith("/storage/v1/object/attachments/"): + fake.objects[urllib.parse.unquote(url.path.removeprefix("/storage/v1/object/attachments/"))] = raw + return self._answer(200, {"Key": url.path}) + return self._answer(404, {"message": "not found"}) + + do_GET = do_POST = do_PUT = do_DELETE = _handle + + def log_message(self, *_): + pass + + self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self._server.server_address[1]}" + threading.Thread(target=self._server.serve_forever, daemon=True).start() + + def stop(self): + self._server.shutdown() + self._server.server_close() diff --git a/tests/test_guard_poller.py b/tests/test_guard_poller.py new file mode 100644 index 0000000..d01c2a2 --- /dev/null +++ b/tests/test_guard_poller.py @@ -0,0 +1,26 @@ +"""The poller reads LibreDesk only through conversations.pomper.Lecteur (GET only) and writes only to Supabase.""" +import re +import unittest +from pathlib import Path + +from poller.poll import Supabase + +ROOT = Path(__file__).resolve().parents[1] + + +class TestGuardPoller(unittest.TestCase): + def test_never_a_libredesk_route(self): + files = list((ROOT / "poller").glob("*.py")) + self.assertTrue(files) + for f in files: + self.assertNotIn("/api/v1/", f.read_text(), f.name) + + def test_writes_only_to_supabase(self): + text = (ROOT / "poller" / "poll.py").read_text() + self.assertEqual(set(re.findall(r'"(/[a-z]+/v1/)', text)) - {"/rest/v1/", "/storage/v1/"}, set()) + with self.assertRaises(ValueError): + Supabase("http://x", "k")._request("POST", "/api/v1/conversations", b"") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_poll.py b/tests/test_poll.py new file mode 100644 index 0000000..b2ae63b --- /dev/null +++ b/tests/test_poll.py @@ -0,0 +1,147 @@ +import io +import unittest +import urllib.error + +from conversations.pomper import Lecteur +from fake_supabase import FakeSupabase +from faux_libredesk import FauxLibreDesk +from poller.poll import Supabase, loop, poll_once +from test_pomper import conv, message, pages, piece + +LIST = ("GET", "/api/v1/conversations/all") + + +def stop(_): + raise StopIteration + + +class TestPoll(unittest.TestCase): + def setUp(self): + self.ld, self.s3, self.sb = FauxLibreDesk(), FauxLibreDesk(), FakeSupabase() + for f in (self.ld.arreter, self.s3.arreter, self.sb.stop): + self.addCleanup(f) + self.lines = [] + self.s3.reponses[("GET", "/x.png")] = b"PNG" + self.serve(piece("photo.png", f"{self.s3.url}/x.png?X-Amz-Signature=secret", uuid="a1")) + + def serve(self, attachment): + convs = [conv("2", "u2", "2026-11-18T12:00:00Z"), conv("1", "u1", "2026-11-16T12:00:00Z")] + img = f'' + msgs = {"u2": [message("08:00", [attachment], contenu=img)], "u1": [message("09:00")]} + self.ld.reponses[LIST] = pages(convs) + for c in convs: + self.ld.reponses[("GET", f"/api/v1/conversations/{c['uuid']}/messages")] = pages(msgs[c["uuid"]]) + + def run_once(self, key="sb_secret_x"): + return poll_once(Lecteur(self.ld.url, "k", "s"), Supabase(self.sb.url, key), log=self.lines.append) + + def libredesk_paths(self): + return [p.split("?")[0] for _, p, _ in self.ld.requetes] + + def test_first_run_everything(self): + self.assertEqual(self.run_once(), 2) + convs = self.sb.tables["conversations"] + self.assertEqual(set(convs), {"u2", "u1"}) + self.assertNotIn("previous_conversations", convs["u2"]["raw"]) + self.assertEqual(convs["u2"]["contact_email"], "j@x.ch") + self.assertEqual(convs["u2"]["reference_number"], "2") + self.assertEqual(self.sb.objects["u2/a1"], b"PNG") + m = self.sb.tables["messages"]["m08:00"] + self.assertEqual(m["conversation_uuid"], "u2") + self.assertEqual(m["raw"]["attachments"][0]["url"], "u2/a1") + self.assertEqual(m["raw"]["content"], '') # the signed URL expires: replaced by the key + self.assertIn("conversations", self.sb.tables["checkpoints"]) + + def test_second_run_no_duplicates(self): + self.run_once() + self.sb.tables["checkpoints"].clear() # no checkpoint: everything is read again + self.run_once() + self.assertEqual(len(self.sb.tables["conversations"]), 2) + self.assertEqual(len(self.sb.tables["messages"]), 2) + self.assertEqual(len(self.s3.requetes), 1) # the attachment downloaded once + + def test_incremental(self): + self.sb.tables["checkpoints"]["conversations"] = {"name": "conversations", "until": "2026-11-18T10:00:00+00:00"} + self.assertEqual(self.run_once(), 1) + self.assertEqual(set(self.sb.tables["conversations"]), {"u2"}) + self.assertNotIn("/api/v1/conversations/u1/messages", self.libredesk_paths()) + self.assertNotEqual(self.sb.tables["checkpoints"]["conversations"]["until"], "2026-11-18T10:00:00+00:00") + + def test_failure_checkpoint_unchanged(self): + self.sb.fail["/rest/v1/messages"] = 500 + with self.assertRaises(urllib.error.HTTPError) as cm: + self.run_once() + cm.exception.close() + self.assertNotIn("conversations", self.sb.tables["checkpoints"]) + + def test_lost_attachment_skipped(self): + self.s3.reponses[("GET", "/x.png")] = 404 + self.assertEqual(self.run_once(), 2) + self.assertTrue(self.sb.tables["messages"]["m08:00"]["raw"]["attachments"][0]["absent"]) + self.assertTrue(any("skipped: 404" in l for l in self.lines)) + self.assertIn("conversations", self.sb.tables["checkpoints"]) + + def test_attachment_refused_by_storage_skipped(self): + self.sb.fail["/storage/v1/object/attachments/"] = 413 + self.assertEqual(self.run_once(), 2) + self.assertTrue(any("skipped: 413" in l for l in self.lines)) + self.assertIn("conversations", self.sb.tables["checkpoints"]) + + def test_other_storage_error_stops_the_run(self): # a passing failure: the next run starts again + self.sb.fail["/storage/v1/object/attachments/"] = 500 + with self.assertRaises(urllib.error.HTTPError) as cm: + self.run_once() + cm.exception.close() + self.assertNotIn("conversations", self.sb.tables["checkpoints"]) + + def test_attachment_without_uuid(self): + self.serve(piece("photo.png", f"{self.s3.url}/x.png", uuid=None)) + self.run_once() + self.assertIn("u2/m08:00-0", self.sb.objects) + + def test_keys_each_to_its_own(self): + self.run_once() + for _, _, h in self.sb.requests: + self.assertEqual(h.get("apikey"), "sb_secret_x") + self.assertNotIn("authorization", h) + self.assertTrue(all("sb_secret_x" not in str(h) for h in self.ld.entetes + self.s3.entetes)) + self.assertTrue(all("token k:s" not in str(h) for h in self.s3.entetes)) + + def test_jwt_also_in_authorization(self): + self.run_once(key="eyJabc") + self.assertEqual(self.sb.requests[0][2]["authorization"], "Bearer eyJabc") + + def test_no_write_to_libredesk(self): + self.run_once() + self.assertEqual(self.ld.ecritures(), []) + + def test_loop_continues_after_error(self): + calls = [] + + def run(): + calls.append(1) + if len(calls) == 1: + raise urllib.error.URLError("down") + return 0 + + def sleep(_): + if len(calls) >= 2: + raise StopIteration + + with self.assertRaises(StopIteration): + loop(run, 300, self.lines.append, sleep) + self.assertEqual(len(calls), 2) + self.assertTrue(any("down" in l for l in self.lines)) + + def test_log_without_signature(self): + def run(): + raise urllib.error.HTTPError("https://s3/x.png?X-Amz-Signature=secret", 500, "", {}, io.BytesIO()) + + with self.assertRaises(StopIteration): + loop(run, 300, self.lines.append, stop) + self.assertTrue(any("https://s3/x.png" in l for l in self.lines)) + self.assertFalse(any("secret" in l for l in self.lines)) + + +if __name__ == "__main__": + unittest.main()