Poller: final review fixes (no secret in the image, Storage's real error read, non-http attachment skipped, failing conversation named, duplicate message saved once)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d80b6face8
commit
b9dddaf221
8 files changed
+121
-34
No files matched your search
+60
-22
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user