Files
aimsight-libredesk/poller/poll.py
T

204 lines
9.8 KiB
Python

"""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 <conversation uuid>/<attachment uuid>.
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"
# An attachment Storage refuses (too big, a type or a name it does not take): skipped, noted, never blocks the next runs.
# Storage answers 400 for nearly every error, the real one in the body: a missing bucket must stop the run, not lose them all.
REFUSED_STATUS, REFUSED_CODES = {"413", "415"}, {"EntityTooLarge", "InvalidMimeType", "InvalidKey"}
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 <folder>/ 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 _upload(reader: Lecteur, supabase: Supabase, key: str, url: str, type_: str) -> str:
"""Copies one attachment from LibreDesk to the bucket; returns why it is skipped, or "" once it is there. A passing
failure (any other error) is raised: the run stops, the next one takes it up."""
try:
content = reader.lire(url)
except urllib.error.HTTPError as e:
e.close()
if e.code not in PERDUE:
raise
return str(e.code)
except ValueError as e: # an address Lecteur refuses (not http): never fetched
return str(e)
try:
supabase.put(key, content, type_)
except urllib.error.HTTPError as e:
try:
body = json.loads(e.read() or b"{}")
except ValueError:
body = {}
e.close()
if e.code != 413 and str(body.get("statusCode")) not in REFUSED_STATUS and body.get("code") not in REFUSED_CODES:
raise
return f"{e.code} {body.get('code') or ''}".strip()
except ValueError as e: # a content type http.client refuses as a header
return str(e)
return ""
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:
reason = _upload(reader, supabase, key, url, a.get("content_type") or "application/octet-stream")
if reason:
log(f" attachment {key} skipped: {reason}")
a["url"], a["absent"] = "", True
continue
if url:
m["content"] = (m.get("content") or "").replace(url.replace("&", "&amp;"), 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):
ref = c.get("reference_number")
try:
n_attachments, n_messages = _save_conversation(reader, supabase, c, log)
except Exception:
log(f"failed on conversation #{ref} {c['uuid']}")
raise
log(f"#{ref} {c.get('subject') or ''}: {n_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 _save_conversation(reader: Lecteur, supabase: Supabase, c: dict, log) -> tuple[int, int]:
"""One conversation, its messages and attachments; returns the numbers of attachments and messages."""
# a page shift while a long thread is read can repeat a message: twice in one upsert, PostgREST refuses it all
messages = list({m["uuid"]: m for m in reader.messages(c["uuid"])}.values())
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])
return n_attachments, len(messages)
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)}")
if isinstance(e, urllib.error.HTTPError):
e.close()
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()