Coverage for src/copytrading_engine/sources/evidence.py: 88%
41 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""Pure bounds and normalization for source-owned ingress evidence."""
3import json
4import re
5from collections.abc import Sequence
7from pydantic import JsonValue
9from copytrading_engine.shared.payload_capture import CaptureStatus
10from copytrading_engine.shared.raw_message import RawMessage
11from copytrading_engine.sources.application import AttachmentReference
13MAX_SOURCE_EVENT_BYTES = 64 * 1024
14MAX_ATTACHMENTS_PER_MESSAGE = 10
15OMITTED_ATTACHMENT_ID = "__additional_attachments_omitted__"
16_ATTACHMENT_ID = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
17_EVIDENCE_ID = re.compile(r"^[0-9a-f]{32}$")
20def normalized_source_event(event: RawMessage) -> dict[str, JsonValue]:
21 return {
22 "event_type": "raw_message",
23 "content": event.text,
24 "embeds": [],
25 "attachments": [],
26 "attachments_omitted": 0,
27 }
30def bounded_source_event(payload: JsonValue) -> tuple[str | None, CaptureStatus, int]:
31 serialized = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
32 size = len(serialized.encode("utf-8"))
33 if size <= MAX_SOURCE_EVENT_BYTES:
34 return serialized, "complete", size
35 return None, "oversize", size
38def is_evidence_id(value: str) -> bool:
39 return bool(_EVIDENCE_ID.fullmatch(value))
42def bounded_attachments(
43 attachments: Sequence[AttachmentReference],
44) -> tuple[tuple[AttachmentReference, ...], int]:
45 selected = []
46 used_ids: set[str] = set()
47 for index, item in enumerate(attachments[:MAX_ATTACHMENTS_PER_MESSAGE]):
48 candidate = item.attachment_id
49 if not _ATTACHMENT_ID.fullmatch(candidate) or candidate == OMITTED_ATTACHMENT_ID: 49 ↛ 50line 49 didn't jump to line 50 because the condition on line 49 was never true
50 candidate = f"attachment-{index + 1}"
51 base = candidate[:128]
52 identifier = base
53 suffix = 1
54 while identifier in used_ids: 54 ↛ 55line 54 didn't jump to line 55 because the condition on line 54 was never true
55 ending = f"-{suffix}"
56 identifier = base[: 128 - len(ending)] + ending
57 suffix += 1
58 used_ids.add(identifier)
59 filename = "".join(character for character in item.filename if ord(character) >= 32)[:255]
60 content_type = item.content_type[:255] if item.content_type is not None else None
61 selected.append(
62 AttachmentReference(
63 attachment_id=identifier,
64 filename=filename,
65 content_type=content_type,
66 declared_size=item.declared_size,
67 url=item.url,
68 )
69 )
70 return tuple(selected), max(0, len(attachments) - len(selected))