Poller: the LibreDesk conversations into Supabase, one run or in a loop (read-only on LibreDesk)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-24 16:45:48 +01:00
1 parent b0b7e3411d
commit 271c230635
5 files changed
+403

No files matched your search

+67
View File
@@ -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()
+26
View File
@@ -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()
+147
View File
@@ -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'<img src="{attachment["url"]}">'
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"], '<img src="u2/a1">') # 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()