diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..d9d3167 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +# The build context is the repository root (poller/Dockerfile): never a secret, never git, never scratch. +**/.env +**/.db-password +**/__pycache__ +.git +.superpowers +cases +out +acces/database.db +acces/utilisateurs.json diff --git a/.gitignore b/.gitignore index 773b3df..420b44f 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ cases/ out/ poller/.env supabase/.temp/ +supabase/.db-password diff --git a/docs/production.md b/docs/production.md index 221b25b..15b8100 100644 --- a/docs/production.md +++ b/docs/production.md @@ -112,10 +112,10 @@ Au clic sur « Generate reply », le LLM peut appeler l'outil `get_customer_acce Le poller (`poller/`, README du dépôt) copie toutes les conversations dans le projet Supabase `Conversations`, toutes les 5 minutes. Maxime lance chaque commande qui porte un secret ; Claude ne voit ni le mot de passe ni les clés. - [ ] **17 provisoire. Sur le PC de Maxime**, comme le service d'accès au point 14. - 1. Créer le projet ; le mot de passe de la base va dans `poller/.env` sans passer par l'écran : - `pw=$(python3 -c 'import secrets; print(secrets.token_urlsafe(24))') && echo "SUPABASE_CONVERSATIONS_DB_PASSWORD=$pw" >> poller/.env && chmod 600 poller/.env && npx --yes supabase@3.2.0 projects create Conversations --org-id bjxgqmujrwsgvokhqoig --region eu-west-1 --db-password "$pw"`. + 1. Créer le projet ; le mot de passe de la base va dans `supabase/.db-password` (hors de git, hors de l'image, jamais dans `poller/.env` que lit le conteneur), sans passer par l'écran : + `(umask 077 && python3 -c 'import secrets; print(secrets.token_urlsafe(24))' > supabase/.db-password) && npx --yes supabase@3.2.0 projects create Conversations --org-id bjxgqmujrwsgvokhqoig --region eu-west-1 --db-password "$(cat supabase/.db-password)"`. Sa `ref` : `npx --yes supabase@3.2.0 projects list`. Ce n'est pas `hhultpvcxerihcgfyuia` (« Support », la base des analystes). - 2. Pousser le schéma : `set -a && . poller/.env && set +a && npx --yes supabase@3.2.0 link --project-ref -p "$SUPABASE_CONVERSATIONS_DB_PASSWORD" && npx --yes supabase@3.2.0 db push -p "$SUPABASE_CONVERSATIONS_DB_PASSWORD"`. + 2. Pousser le schéma : `npx --yes supabase@3.2.0 link --project-ref -p "$(cat supabase/.db-password)" && npx --yes supabase@3.2.0 db push -p "$(cat supabase/.db-password)"`. 3. Compléter `poller/.env` : `SUPABASE_CONVERSATIONS_URL=https://.supabase.co`, `SUPABASE_CONVERSATIONS_KEY=` (Dashboard → Settings → API keys), `LIBREDESK_API_KEY` et `LIBREDESK_API_SECRET`. 4. Le premier tour, à la main, à une heure calme (tout l'historique) : `docker compose -f poller/compose.yml run --rm poller python -u -m poller.poll`. Vérifier que le nombre de lignes de `conversations` correspond au nombre de conversations de LibreDesk. 5. En continu : construire (sur le poste) `docker compose -f poller/compose.yml build`, puis lancer `docker compose -f poller/compose.yml up -d --no-build` ; après 5 minutes, `docker logs libredesk-poller` montre un tour. diff --git a/poller/Dockerfile b/poller/Dockerfile index 91051ce..4f59392 100644 --- a/poller/Dockerfile +++ b/poller/Dockerfile @@ -2,7 +2,7 @@ # LibreDesk through conversations/pomper.py). Version pinned like acces/Dockerfile (2026-11-18). FROM python:3.12.8-slim-bookworm WORKDIR /app -COPY conversations/ /app/conversations/ -COPY poller/ /app/poller/ +COPY conversations/__init__.py conversations/pomper.py conversations/transcript.py /app/conversations/ +COPY poller/__init__.py poller/poll.py /app/poller/ USER nobody CMD ["python", "-u", "-m", "poller.poll", "--every", "300"] diff --git a/poller/poll.py b/poller/poll.py index f346ecd..de4a507 100644 --- a/poller/poll.py +++ b/poller/poll.py @@ -27,7 +27,9 @@ 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 +# 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 @@ -71,6 +73,34 @@ class Supabase: {"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 @@ -79,13 +109,9 @@ def _save_attachments(reader: Lecteur, supabase: Supabase, conv_uuid: str, messa 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}") + 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: @@ -99,27 +125,39 @@ 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") + 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): diff --git a/tests/fake_supabase.py b/tests/fake_supabase.py index 7a8ddae..4626b67 100644 --- a/tests/fake_supabase.py +++ b/tests/fake_supabase.py @@ -12,7 +12,7 @@ class FakeSupabase: 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 + self.fail: dict[str, int | tuple[int, dict]] = {} # path prefix → error code, or (code, body) as Storage does fake = self class Handler(BaseHTTPRequestHandler): @@ -29,9 +29,10 @@ class FakeSupabase: 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(): + for prefix, failure in fake.fail.items(): if url.path.startswith(prefix): - return self._answer(code, {"message": "failure"}) + code, body = failure if isinstance(failure, tuple) else (failure, {"message": "failure"}) + return self._answer(code, body) if url.path.startswith("/rest/v1/"): table = url.path.removeprefix("/rest/v1/") key = KEYS.get(table, "uuid") @@ -42,7 +43,10 @@ class FakeSupabase: 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): + rows = json.loads(raw) + if len({r[key] for r in rows}) < len(rows): # PostgREST: "cannot affect row a second time" + return self._answer(500, {"code": "21000"}) + for row in rows: fake.tables[table][row[key]] = fake.tables[table].get(row[key], {}) | row return self._answer(201) if url.path == "/storage/v1/object/list/attachments": diff --git a/tests/test_guard_poller.py b/tests/test_guard_poller.py index d01c2a2..54c08d3 100644 --- a/tests/test_guard_poller.py +++ b/tests/test_guard_poller.py @@ -21,6 +21,14 @@ class TestGuardPoller(unittest.TestCase): with self.assertRaises(ValueError): Supabase("http://x", "k")._request("POST", "/api/v1/conversations", b"") + def test_secrets_never_in_the_image(self): # the build context is the repository root + ignored = (ROOT / ".dockerignore").read_text().split() + self.assertIn("**/.env", ignored) + self.assertIn(".git", ignored) + + def test_db_password_not_in_the_container_env(self): # poller/.env is the container's env_file + self.assertIsNone(re.search(r"DB_PASSWORD[^\n]*>> poller/\.env", (ROOT / "docs" / "production.md").read_text())) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_poll.py b/tests/test_poll.py index b2ae63b..d3d2317 100644 --- a/tests/test_poll.py +++ b/tests/test_poll.py @@ -81,12 +81,38 @@ class TestPoll(unittest.TestCase): 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 + def test_attachment_refused_by_storage_skipped(self): # Storage answers 400, the real reason in the body + self.sb.fail["/storage/v1/object/attachments/"] = (400, {"statusCode": "413", "code": "EntityTooLarge"}) self.assertEqual(self.run_once(), 2) - self.assertTrue(any("skipped: 413" in l for l in self.lines)) + self.assertTrue(any("skipped: 400 EntityTooLarge" in l for l in self.lines)) self.assertIn("conversations", self.sb.tables["checkpoints"]) + def test_missing_bucket_stops_the_run(self): # not an attachment's fault: never skip and lose them all + self.sb.fail["/storage/v1/object/attachments/"] = (400, {"statusCode": "404", "code": "NoSuchBucket"}) + with self.assertRaises(urllib.error.HTTPError) as cm: + self.run_once() + cm.exception.close() + self.assertNotIn("conversations", self.sb.tables["checkpoints"]) + + def test_non_http_attachment_skipped(self): # Lecteur refuses it (ValueError): skipped, never blocks the runs + self.serve(piece("passwd", "file:///etc/passwd", uuid="a1")) + self.assertEqual(self.run_once(), 2) + self.assertTrue(self.sb.tables["messages"]["m08:00"]["raw"]["attachments"][0]["absent"]) + self.assertIn("conversations", self.sb.tables["checkpoints"]) + + def test_failure_names_the_conversation(self): + self.sb.fail["/rest/v1/messages"] = 500 + with self.assertRaises(urllib.error.HTTPError) as cm: + self.run_once() + cm.exception.close() + self.assertTrue(any("#2" in l and "u2" in l for l in self.lines)) + + def test_same_message_twice_saved_once(self): # a page shift while a long thread is read repeats a message + m = message("09:00") + self.ld.reponses[("GET", "/api/v1/conversations/u1/messages")] = pages([m, dict(m)]) + self.assertEqual(self.run_once(), 2) + self.assertEqual(self.sb.tables["messages"]["m09:00"]["conversation_uuid"], "u1") + 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: