@devries-cameron20 / composio-1 / commits / 56e0d781f
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(triggers): handle V3 envelope in realtime subscribe path [SUP-392] (#3567)

## Summary `triggers.subscribe()` crashes with `KeyError: 'nanoId'` on the **first event** for any project configured with webhook version **V3**. The realtime (Pusher) channel now delivers the modern V3 envelope (snake_case: `metadata.trigger_id` / `connected_account_id` / `auth_config_id`, with no top-level `nanoId`), but the realtime parser (`TriggerSubscription._parse_payload`) only understood the **legacy** envelope and accessed `data["metadata"]["nanoId"]` directly — so the very first inbound frame raises inside the Pusher `_on_message` callback and the registered handler is never invoked. The SDK already knows how to normalize the V3 envelope — it does so on the webhook path (`_normalize_v3_payload`) — that logic was simply never wired into the realtime path. This has affected the realtime subscribe path for V3 projects since the V3 trigger payload format was introduced; webhook-version V1/V2 projects are unaffected (they still receive the legacy realtime envelope). ## Changes - Extract the V3 → `TriggerEvent` normalization into a shared module-level helper (`_build_trigger_event_from_v3`) plus an envelope detector (`_is_v3_envelope`); the webhook path's `_normalize_v3_payload` now delegates to it, so webhook and realtime share one source of truth. - `TriggerSubscription._parse_payload` now detects the V3 envelope and normalizes it, and keeps the existing legacy mapping for V1/V2 payloads. - Harden `_parse_payload`: unknown/malformed frames are logged and skipped (return `None`) instead of raising, so a single bad frame can no longer tear down an active subscription. - Add tests covering V3 realtime parsing, legacy realtime parsing, and malformed-frame handling. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? - `ruff check` + `ruff format` (config/ruff.toml) — clean. - `uv run pytest tests/test_triggers.py` — **52 passed** (49 existing + 3 new). - New tests: - `test_parse_payload_v3_realtime_envelope` — a V3 realtime frame parses to a `TriggerEvent` (no `KeyError`). - `test_parse_payload_legacy_envelope` — V1/V2 legacy frame still parses correctly. - `test_parse_payload_malformed_returns_none` — bad/partial frames are skipped, not raised. ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] I ran linters/tests locally and they passed - [ ] I updated documentation as needed - [x] I added tests or explain why not applicable - [ ] I added a changeset if this change affects published packages ## Additional context The realtime envelope is identical in shape to the V3 webhook envelope, so the shared normalizer keeps the two delivery channels consistent. No public API changes. --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: jkomyno <alberto@composio.dev> Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com>

Anshu Garg committed Jun 16, 2026 at 17:09 UTC 56e0d781f312e1d2dc854855edecd708ad93cc5f
2 files changed +461 -178
python/composio/core/models/triggers.py
+202 -177
@@ -431,6 +431,131 @@ class TriggerEventFilters(te.TypedDict):
431 TriggerCallback = t.Callable[[TriggerEvent], None]
432
433
434 +# Realtime trigger frames can carry message bodies / PII, so the raw frame is
435 +# never logged in full — only a bounded preview when it fails to parse.
436 +_MAX_LOGGED_FRAME_CHARS = 512
437 +
438 +
439 +def _truncate_frame(event: str) -> str:
440 + """Return a bounded preview of a raw frame for safe logging."""
441 + if len(event) <= _MAX_LOGGED_FRAME_CHARS:
442 + return event
443 + return f"{event[:_MAX_LOGGED_FRAME_CHARS]}… ({len(event)} chars total)"
444 +
445 +
446 +def _coerce_str(value: t.Any) -> str:
447 + """Coerce a possibly-missing or non-string field to ``str``.
448 +
449 + Mirrors the TS SDK's ``toStringOrDefault`` so realtime/webhook frames that
450 + carry ``None`` or a non-string identity field don't later raise
451 + ``AttributeError`` on ``.lower()`` / ``.split()``. ``None`` maps to "".
452 + """
453 + return "" if value is None else str(value)
454 +
455 +
456 +def _is_v3_envelope(data: t.Any) -> bool:
457 + """Return ``True`` if ``data`` is a modern V3 envelope.
458 +
459 + V3 payloads carry a ``type`` starting with ``composio.`` and a ``metadata``
460 + object, alongside top-level ``id`` and ``data`` keys. The same envelope is
461 + delivered over both the webhook channel and the realtime (Pusher) channel,
462 + so this is used to route either source through the V3 normalizer.
463 + """
464 + if not isinstance(data, dict):
465 + return False
466 + event_type = data.get("type", "")
467 + return (
468 + isinstance(event_type, str)
469 + and event_type.startswith("composio.")
470 + and isinstance(data.get("metadata"), dict)
471 + and "id" in data
472 + and "data" in data
473 + )
474 +
475 +
476 +def _build_trigger_event_from_v3(data: WebhookPayloadV3) -> TriggerEvent:
477 + """Normalize a V3 envelope (webhook or realtime) into a ``TriggerEvent``.
478 +
479 + Trigger frames are identified by their envelope ``type``
480 + (``composio.trigger.message``), not by the presence of every metadata
481 + field. The trigger-specific metadata fields are then read best-effort and
482 + coerced to ``str`` so a frame that omits or mistypes one of them is still
483 + delivered rather than silently demoted to a non-trigger event or raising
484 + ``AttributeError`` on the toolkit-slug split.
485 + """
486 + metadata = data.get("metadata") or {}
487 + event_type = data.get("type", "")
488 +
489 + if event_type == "composio.trigger.message":
490 + trigger_id = _coerce_str(metadata.get("trigger_id"))
491 + trigger_slug = _coerce_str(metadata.get("trigger_slug"))
492 + user_id = _coerce_str(metadata.get("user_id"))
493 + connected_account_id = _coerce_str(metadata.get("connected_account_id"))
494 + auth_config_id = _coerce_str(metadata.get("auth_config_id"))
495 + toolkit_slug = (
496 + trigger_slug.split("_")[0].upper() if "_" in trigger_slug else "UNKNOWN"
497 + )
498 + return t.cast(
499 + TriggerEvent,
500 + {
501 + "id": trigger_id,
502 + "uuid": trigger_id,
503 + "user_id": user_id,
504 + "toolkit_slug": toolkit_slug,
505 + "trigger_slug": trigger_slug,
506 + "metadata": {
507 + "id": trigger_id,
508 + "uuid": trigger_id,
509 + "toolkit_slug": toolkit_slug,
510 + "trigger_slug": trigger_slug,
511 + "trigger_data": None,
512 + "trigger_config": {},
513 + "connected_account": {
514 + "id": connected_account_id,
515 + "uuid": connected_account_id,
516 + "auth_config_id": auth_config_id,
517 + "auth_config_uuid": auth_config_id,
518 + "user_id": user_id,
519 + "status": "ACTIVE",
520 + },
521 + },
522 + "payload": data.get("data", {}),
523 + "original_payload": None,
524 + },
525 + )
526 +
527 + # Non-trigger V3 event (e.g., connection expired)
528 + event_id = _coerce_str(data.get("id"))
529 + return t.cast(
530 + TriggerEvent,
531 + {
532 + "id": event_id,
533 + "uuid": event_id,
534 + "user_id": "",
535 + "toolkit_slug": "COMPOSIO",
536 + "trigger_slug": event_type,
537 + "metadata": {
538 + "id": event_id,
539 + "uuid": event_id,
540 + "toolkit_slug": "COMPOSIO",
541 + "trigger_slug": event_type,
542 + "trigger_data": None,
543 + "trigger_config": {},
544 + "connected_account": {
545 + "id": "",
546 + "uuid": "",
547 + "auth_config_id": "",
548 + "auth_config_uuid": "",
549 + "user_id": "",
550 + "status": "ACTIVE",
551 + },
552 + },
553 + "payload": data.get("data", {}),
554 + "original_payload": data,
555 + },
556 + )
557 +
558 +
559 class TriggerSubscription(Resource):
560 """Trigger subscription."""
561
@@ -460,45 +585,70 @@ class TriggerSubscription(Resource):
585 return _wrap
586
587 def _parse_payload(self, event: str) -> t.Optional[TriggerEvent]:
463 - """Parse event payload."""
588 + """Parse a realtime event payload into a ``TriggerEvent``.
589 +
590 + The realtime (Pusher) channel delivers either the modern V3 envelope
591 + (for projects on webhook version V3) or the legacy envelope (for V1/V2
592 + projects). Both shapes are handled here. Any unrecognized or malformed
593 + frame is logged and skipped (returns ``None``) rather than raising, so a
594 + single bad frame cannot tear down the subscription.
595 + """
596 try:
465 - data = t.cast(_TriggerData, json.loads(event))
597 + data = json.loads(event)
598 except Exception as e:
599 self.logger.warning(f"Error decoding payload: {e}")
600 return None
601
470 - return t.cast(
471 - TriggerEvent,
472 - {
473 - "id": data["metadata"]["nanoId"],
474 - "uuid": data["metadata"]["id"],
475 - "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
476 - "toolkit_slug": data["appName"],
477 - "trigger_slug": data["metadata"]["triggerName"],
478 - "metadata": {
479 - "id": data["metadata"]["nanoId"],
480 - "uuid": data["metadata"]["id"],
481 - "toolkit_slug": data["appName"],
482 - "trigger_slug": data["metadata"]["triggerName"],
483 - "trigger_data": data["metadata"]["triggerData"],
484 - "trigger_config": data["metadata"]["triggerConfig"],
485 - "connected_account": {
486 - "id": data["metadata"]["connection"]["connectedAccountNanoId"],
487 - "uuid": data["metadata"]["connection"]["id"],
488 - "auth_config_id": data["metadata"]["connection"][
489 - "authConfigNanoId"
490 - ],
491 - "auth_config_uuid": data["metadata"]["connection"][
492 - "integrationId"
493 - ],
494 - "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
495 - "status": data["metadata"]["connection"]["status"],
602 + try:
603 + # V3 envelope — same shape as the V3 webhook payload.
604 + if _is_v3_envelope(data):
605 + return _build_trigger_event_from_v3(t.cast(WebhookPayloadV3, data))
606 +
607 + # Legacy envelope (V1/V2 projects).
608 + legacy = t.cast(_TriggerData, data)
609 + return t.cast(
610 + TriggerEvent,
611 + {
612 + "id": legacy["metadata"]["nanoId"],
613 + "uuid": legacy["metadata"]["id"],
614 + "user_id": legacy["metadata"]["connection"]["clientUniqueUserId"],
615 + "toolkit_slug": legacy["appName"],
616 + "trigger_slug": legacy["metadata"]["triggerName"],
617 + "metadata": {
618 + "id": legacy["metadata"]["nanoId"],
619 + "uuid": legacy["metadata"]["id"],
620 + "toolkit_slug": legacy["appName"],
621 + "trigger_slug": legacy["metadata"]["triggerName"],
622 + "trigger_data": legacy["metadata"].get("triggerData"),
623 + "trigger_config": legacy["metadata"]["triggerConfig"],
624 + "connected_account": {
625 + "id": legacy["metadata"]["connection"][
626 + "connectedAccountNanoId"
627 + ],
628 + "uuid": legacy["metadata"]["connection"]["id"],
629 + "auth_config_id": legacy["metadata"]["connection"][
630 + "authConfigNanoId"
631 + ],
632 + "auth_config_uuid": legacy["metadata"]["connection"][
633 + "integrationId"
634 + ],
635 + "user_id": legacy["metadata"]["connection"][
636 + "clientUniqueUserId"
637 + ],
638 + "status": legacy["metadata"]["connection"]["status"],
639 + },
640 },
641 + "payload": legacy.get("payload"),
642 + "original_payload": legacy.get("originalPayload"),
643 },
498 - "payload": data["payload"],
499 - "original_payload": data["originalPayload"],
500 - },
501 - )
644 + )
645 + except Exception as e:
646 + # A single malformed frame must never propagate into pysher's
647 + # dispatch loop (which calls callbacks with no try/except) and tear
648 + # down the subscription, so catch broadly — AttributeError and
649 + # others, not just KeyError/TypeError — and skip the frame.
650 + self.logger.warning(f"Error parsing trigger payload: {e}")
651 + return None
652
653 def _handle_chunked_events(self, event: str) -> None:
654 """Handle chunked events."""
@@ -528,7 +678,16 @@ class TriggerSubscription(Resource):
678 )
679 for name, check in checks:
680 value = filters.get(name)
531 - if value is None or str(value).lower() == check.lower():
681 + if value is None:
682 + # No filter set for this field — nothing to match against.
683 + continue
684 +
685 + # ``check`` is str()-wrapped because realtime frames may carry
686 + # non-string identity fields; an empty event-side value is treated
687 + # as a non-match so synthesized "" fields don't fail open into a
688 + # filter that happens to be "".
689 + check_str = str(check)
690 + if check_str and str(value).lower() == check_str.lower():
691 continue
692
693 self.logger.debug(
@@ -561,7 +720,12 @@ class TriggerSubscription(Resource):
720 """Filter events and call the callback function."""
721 data = self._parse_payload(event=event)
722 if data is None:
564 - self.logger.error(f"Error parsing trigger payload: {event}")
723 + # _parse_payload already logged the specific reason; here we only
724 + # note that the frame was skipped, with a bounded preview so a
725 + # PII-bearing frame isn't dumped in full.
726 + self.logger.error(
727 + f"Skipping unparseable trigger frame: {_truncate_frame(event)}"
728 + )
729 return
730
731 self.logger.debug(
@@ -1092,24 +1256,13 @@ class Triggers(Resource):
1256 f"Failed to parse webhook payload as JSON: {e}"
1257 ) from e
1258
1095 - # Try V3 first (has 'type' starting with 'composio.' and 'metadata' as dict)
1096 - # Metadata shape varies by event type (trigger vs connection events),
1097 - # so we only check that it's a dict here.
1098 - v3_metadata = data.get("metadata") if isinstance(data, dict) else None
1099 - v3_metadata_valid = isinstance(v3_metadata, dict)
1100 - v3_type = data.get("type", "") if isinstance(data, dict) else ""
1101 - if (
1102 - isinstance(data, dict)
1103 - and isinstance(v3_type, str)
1104 - and v3_type.startswith("composio.")
1105 - and v3_metadata_valid
1106 - and "id" in data
1107 - and "data" in data
1108 - ):
1259 + # Try V3 first — same envelope the realtime channel uses, so reuse the
1260 + # shared detector/normalizer to keep the two paths from drifting.
1261 + if _is_v3_envelope(data):
1262 return (
1263 WebhookVersion.V3,
1264 t.cast(WebhookPayloadV3, data),
1112 - self._normalize_v3_payload(t.cast(WebhookPayloadV3, data)),
1265 + _build_trigger_event_from_v3(t.cast(WebhookPayloadV3, data)),
1266 )
1267
1268 # Try V2 (has 'type', 'timestamp', 'data' with nested fields)
@@ -1221,131 +1374,3 @@ class Triggers(Resource):
1374 "original_payload": None,
1375 },
1376 )
1224 -
1225 - def _normalize_v3_payload(self, data: WebhookPayloadV3) -> TriggerEvent:
1226 - """Normalize V3 payload to TriggerEvent format."""
1227 - metadata = data["metadata"]
1228 -
1229 - # Check if this is a trigger event (has trigger-specific metadata fields)
1230 - is_trigger_event = all(
1231 - k in metadata
1232 - for k in (
1233 - "trigger_id",
1234 - "trigger_slug",
1235 - "user_id",
1236 - "connected_account_id",
1237 - "auth_config_id",
1238 - "log_id",
1239 - )
1240 - )
1241 -
1242 - if is_trigger_event:
1243 - trigger_data = t.cast(WebhookTriggerPayloadV3, data)
1244 - trigger_metadata = trigger_data["metadata"]
1245 - return t.cast(
1246 - TriggerEvent,
1247 - {
1248 - "id": trigger_metadata["trigger_id"],
1249 - "uuid": trigger_metadata["trigger_id"],
1250 - "user_id": trigger_metadata["user_id"],
1251 - "toolkit_slug": trigger_metadata["trigger_slug"]
1252 - .split("_")[0]
1253 - .upper()
1254 - if "_" in trigger_metadata["trigger_slug"]
1255 - else "UNKNOWN",
1256 - "trigger_slug": trigger_metadata["trigger_slug"],
1257 - "metadata": {
1258 - "id": trigger_metadata["trigger_id"],
1259 - "uuid": trigger_metadata["trigger_id"],
1260 - "toolkit_slug": trigger_metadata["trigger_slug"]
1261 - .split("_")[0]
1262 - .upper()
1263 - if "_" in trigger_metadata["trigger_slug"]
1264 - else "UNKNOWN",
1265 - "trigger_slug": trigger_metadata["trigger_slug"],
1266 - "trigger_data": None,
1267 - "trigger_config": {},
1268 - "connected_account": {
1269 - "id": trigger_metadata["connected_account_id"],
1270 - "uuid": trigger_metadata["connected_account_id"],
1271 - "auth_config_id": trigger_metadata["auth_config_id"],
1272 - "auth_config_uuid": trigger_metadata["auth_config_id"],
1273 - "user_id": trigger_metadata["user_id"],
1274 - "status": "ACTIVE",
1275 - },
1276 - },
1277 - "payload": trigger_data["data"],
1278 - "original_payload": None,
1279 - },
1280 - )
1281 -
1282 - # Non-trigger V3 event (e.g., connection expired)
1283 - event_type = data.get("type", "")
1284 - return t.cast(
1285 - TriggerEvent,
1286 - {
1287 - "id": data.get("id", ""),
1288 - "uuid": data.get("id", ""),
1289 - "user_id": "",
1290 - "toolkit_slug": "COMPOSIO",
1291 - "trigger_slug": event_type,
1292 - "metadata": {
1293 - "id": data.get("id", ""),
1294 - "uuid": data.get("id", ""),
1295 - "toolkit_slug": "COMPOSIO",
1296 - "trigger_slug": event_type,
1297 - "trigger_data": None,
1298 - "trigger_config": {},
1299 - "connected_account": {
1300 - "id": "",
1301 - "uuid": "",
1302 - "auth_config_id": "",
1303 - "auth_config_uuid": "",
1304 - "user_id": "",
1305 - "status": "ACTIVE",
1306 - },
1307 - },
1308 - "payload": data.get("data", {}),
1309 - "original_payload": data,
1310 - },
1311 - )
1312 -
1313 - def _transform_trigger_data(self, data: _TriggerData) -> TriggerEvent:
1314 - """
1315 - Transform raw trigger data to TriggerEvent format.
1316 -
1317 - :param data: The raw trigger data
1318 - :return: The transformed TriggerEvent
1319 - """
1320 - return t.cast(
1321 - TriggerEvent,
1322 - {
1323 - "id": data["metadata"]["nanoId"],
1324 - "uuid": data["metadata"]["id"],
1325 - "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
1326 - "toolkit_slug": data["appName"],
1327 - "trigger_slug": data["metadata"]["triggerName"],
1328 - "metadata": {
1329 - "id": data["metadata"]["nanoId"],
1330 - "uuid": data["metadata"]["id"],
1331 - "toolkit_slug": data["appName"],
1332 - "trigger_slug": data["metadata"]["triggerName"],
1333 - "trigger_data": data["metadata"].get("triggerData"),
1334 - "trigger_config": data["metadata"]["triggerConfig"],
1335 - "connected_account": {
1336 - "id": data["metadata"]["connection"]["connectedAccountNanoId"],
1337 - "uuid": data["metadata"]["connection"]["id"],
1338 - "auth_config_id": data["metadata"]["connection"][
1339 - "authConfigNanoId"
1340 - ],
1341 - "auth_config_uuid": data["metadata"]["connection"][
1342 - "integrationId"
1343 - ],
1344 - "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
1345 - "status": data["metadata"]["connection"]["status"],
1346 - },
1347 - },
1348 - "payload": data.get("payload"),
1349 - "original_payload": data.get("originalPayload"),
1350 - },
1351 - )
python/tests/test_triggers.py
+259 -1
@@ -12,7 +12,13 @@ import pytest
12 from composio_client import omit
13
14 from composio import exceptions
15 -from composio.core.models.triggers import Triggers, WebhookVersion
15 +from composio.core.models.triggers import (
16 + _MAX_LOGGED_FRAME_CHARS,
17 + Triggers,
18 + TriggerSubscription,
19 + WebhookVersion,
20 + _truncate_frame,
21 +)
22
23
24 class TestTriggers:
@@ -1124,3 +1130,255 @@ class TestVerifyWebhook:
1130 """Test that WebhookPayloadError inherits from TriggerError."""
1131 error = exceptions.WebhookPayloadError("test")
1132 assert isinstance(error, exceptions.TriggerError)
1133 +
1134 +
1135 +class TestTriggerSubscriptionParsing:
1136 + """Tests for realtime (Pusher) payload parsing in TriggerSubscription."""
1137 +
1138 + @pytest.fixture
1139 + def subscription(self):
1140 + """Create a TriggerSubscription with a mock client."""
1141 + return TriggerSubscription(client=Mock())
1142 +
1143 + def test_parse_payload_v3_realtime_envelope(self, subscription):
1144 + """A V3 realtime envelope is parsed (no KeyError: 'nanoId')."""
1145 + event = json.dumps(
1146 + {
1147 + "id": "evt-1",
1148 + "type": "composio.trigger.message",
1149 + "metadata": {
1150 + "log_id": "log-1",
1151 + "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE",
1152 + "trigger_id": "ti_abc",
1153 + "connected_account_id": "ca_abc",
1154 + "auth_config_id": "ac_abc",
1155 + "user_id": "user-1",
1156 + },
1157 + "data": {"subject": "hello"},
1158 + }
1159 + )
1160 +
1161 + result = subscription._parse_payload(event)
1162 +
1163 + assert result is not None
1164 + assert result["id"] == "ti_abc"
1165 + assert result["trigger_slug"] == "GMAIL_NEW_GMAIL_MESSAGE"
1166 + assert result["toolkit_slug"] == "GMAIL"
1167 + assert result["user_id"] == "user-1"
1168 + assert result["payload"] == {"subject": "hello"}
1169 + assert result["metadata"]["connected_account"]["id"] == "ca_abc"
1170 + assert result["metadata"]["connected_account"]["auth_config_id"] == "ac_abc"
1171 +
1172 + def test_parse_payload_legacy_envelope(self, subscription):
1173 + """A legacy (V1/V2) realtime envelope still parses correctly."""
1174 + event = json.dumps(
1175 + {
1176 + "appName": "gmail",
1177 + "payload": {"subject": "hello"},
1178 + "originalPayload": {"raw": 1},
1179 + "metadata": {
1180 + "id": "uuid-1",
1181 + "nanoId": "ti_abc",
1182 + "triggerName": "GMAIL_NEW_GMAIL_MESSAGE",
1183 + "triggerData": "",
1184 + "triggerConfig": {},
1185 + "connection": {
1186 + "id": "conn-uuid",
1187 + "connectedAccountNanoId": "ca_abc",
1188 + "authConfigNanoId": "ac_abc",
1189 + "integrationId": "int-uuid",
1190 + "clientUniqueUserId": "user-1",
1191 + "status": "ACTIVE",
1192 + },
1193 + },
1194 + }
1195 + )
1196 +
1197 + result = subscription._parse_payload(event)
1198 +
1199 + assert result is not None
1200 + assert result["id"] == "ti_abc"
1201 + assert result["toolkit_slug"] == "gmail"
1202 + assert result["trigger_slug"] == "GMAIL_NEW_GMAIL_MESSAGE"
1203 + assert result["metadata"]["connected_account"]["id"] == "ca_abc"
1204 + assert result["original_payload"] == {"raw": 1}
1205 +
1206 + def test_parse_payload_malformed_returns_none(self, subscription):
1207 + """Truly undecodable or unrecognized frames are skipped, not raised."""
1208 + assert subscription._parse_payload("not-json") is None
1209 + assert subscription._parse_payload(json.dumps({"unexpected": True})) is None
1210 +
1211 + def test_parse_payload_legacy_non_dict_metadata_does_not_raise(self, subscription):
1212 + """A legacy frame with a non-dict metadata is skipped, not raised.
1213 +
1214 + Guards the broadened `except Exception` in _parse_payload: such a frame
1215 + must return None rather than propagate into pysher's dispatch loop.
1216 + """
1217 + event = json.dumps({"appName": "gmail", "metadata": "not-a-dict"})
1218 + assert subscription._parse_payload(event) is None
1219 +
1220 + def test_parse_payload_non_trigger_v3_event(self, subscription):
1221 + """A non-trigger composio.* event is normalized as a COMPOSIO event."""
1222 + event = json.dumps(
1223 + {
1224 + "id": "evt-1",
1225 + "type": "composio.connected_account.expired",
1226 + "metadata": {"project_id": "pr_1"},
1227 + "data": {"status": "EXPIRED"},
1228 + }
1229 + )
1230 +
1231 + result = subscription._parse_payload(event)
1232 +
1233 + assert result is not None
1234 + assert result["toolkit_slug"] == "COMPOSIO"
1235 + assert result["trigger_slug"] == "composio.connected_account.expired"
1236 + assert result["original_payload"] == json.loads(event)
1237 +
1238 + def test_parse_payload_trigger_empty_metadata_does_not_raise(self, subscription):
1239 + """A trigger frame with empty metadata is delivered with empty identity."""
1240 + event = json.dumps(
1241 + {
1242 + "id": "evt-1",
1243 + "type": "composio.trigger.message",
1244 + "metadata": {},
1245 + "data": {},
1246 + }
1247 + )
1248 +
1249 + result = subscription._parse_payload(event)
1250 +
1251 + assert result is not None
1252 + assert result["trigger_slug"] == ""
1253 + assert result["toolkit_slug"] == "UNKNOWN"
1254 +
1255 + def test_parse_payload_legacy_missing_optional_fields(self, subscription):
1256 + """A legacy frame missing optional fields is delivered, not dropped."""
1257 + event = json.dumps(
1258 + {
1259 + "appName": "gmail",
1260 + "payload": {"subject": "hello"},
1261 + # originalPayload + triggerData intentionally omitted
1262 + "metadata": {
1263 + "id": "uuid-1",
1264 + "nanoId": "ti_abc",
1265 + "triggerName": "GMAIL_NEW_GMAIL_MESSAGE",
1266 + "triggerConfig": {},
1267 + "connection": {
1268 + "id": "conn-uuid",
1269 + "connectedAccountNanoId": "ca_abc",
1270 + "authConfigNanoId": "ac_abc",
1271 + "integrationId": "int-uuid",
1272 + "clientUniqueUserId": "user-1",
1273 + "status": "ACTIVE",
1274 + },
1275 + },
1276 + }
1277 + )
1278 +
1279 + result = subscription._parse_payload(event)
1280 +
1281 + assert result is not None
1282 + assert result["original_payload"] is None
1283 + assert result["metadata"]["trigger_data"] is None
1284 +
1285 + def test_parse_payload_trigger_keyed_off_type_not_all_metadata(self, subscription):
1286 + """A trigger frame missing one metadata field is still a trigger event.
1287 +
1288 + Detection keys off ``type == "composio.trigger.message"`` rather than
1289 + requiring all six metadata fields, so the event is delivered (not
1290 + silently demoted to a non-trigger COMPOSIO event).
1291 + """
1292 + event = json.dumps(
1293 + {
1294 + "id": "evt-1",
1295 + "type": "composio.trigger.message",
1296 + "metadata": {
1297 + # ``log_id`` intentionally omitted
1298 + "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE",
1299 + "trigger_id": "ti_abc",
1300 + "connected_account_id": "ca_abc",
1301 + "auth_config_id": "ac_abc",
1302 + "user_id": "user-1",
1303 + },
1304 + "data": {"subject": "hello"},
1305 + }
1306 + )
1307 +
1308 + result = subscription._parse_payload(event)
1309 +
1310 + assert result is not None
1311 + assert result["trigger_slug"] == "GMAIL_NEW_GMAIL_MESSAGE"
1312 + assert result["toolkit_slug"] == "GMAIL"
1313 + assert result["user_id"] == "user-1"
1314 +
1315 + def test_parse_payload_non_string_trigger_slug_does_not_raise(self, subscription):
1316 + """A null/non-string trigger_slug must not raise AttributeError (Vector A)."""
1317 + event = json.dumps(
1318 + {
1319 + "id": "evt-1",
1320 + "type": "composio.trigger.message",
1321 + "metadata": {
1322 + "trigger_slug": None,
1323 + "trigger_id": "ti_abc",
1324 + "connected_account_id": "ca_abc",
1325 + "auth_config_id": "ac_abc",
1326 + "user_id": 123,
1327 + "log_id": "log-1",
1328 + },
1329 + "data": {"subject": "hello"},
1330 + }
1331 + )
1332 +
1333 + result = subscription._parse_payload(event)
1334 +
1335 + assert result is not None
1336 + assert result["trigger_slug"] == ""
1337 + assert result["toolkit_slug"] == "UNKNOWN"
1338 + assert result["user_id"] == "123"
1339 +
1340 + @staticmethod
1341 + def _make_event(**overrides):
1342 + """Build a minimal TriggerEvent dict for filter-matching tests."""
1343 + event = {
1344 + "id": "ti_1",
1345 + "uuid": "ti_1",
1346 + "user_id": "user-1",
1347 + "toolkit_slug": "GMAIL",
1348 + "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE",
1349 + "metadata": {
1350 + "id": "ti_1",
1351 + "connected_account": {
1352 + "id": "ca_1",
1353 + "auth_config_id": "ac_1",
1354 + },
1355 + },
1356 + }
1357 + event.update(overrides)
1358 + return event
1359 +
1360 + def test_filters_match_no_filters_matches(self, subscription):
1361 + """An empty filterset matches any event."""
1362 + assert subscription._filters_match(self._make_event(), {}, "cb") is True
1363 +
1364 + def test_filters_match_does_not_crash_on_non_string_event_value(self, subscription):
1365 + """A non-string identity field must not raise AttributeError (Vector B)."""
1366 + event = self._make_event(user_id=123)
1367 + assert subscription._filters_match(event, {"user_id": "123"}, "cb") is True
1368 + assert subscription._filters_match(event, {"user_id": "999"}, "cb") is False
1369 +
1370 + def test_filters_match_empty_event_value_does_not_fail_open(self, subscription):
1371 + """A synthesized empty identity field must not match a "" filter."""
1372 + event = self._make_event(user_id="")
1373 + assert subscription._filters_match(event, {"user_id": ""}, "cb") is False
1374 +
1375 + def test_truncate_frame_bounds_long_frames(self):
1376 + """A long raw frame is truncated so PII-bearing frames aren't dumped."""
1377 + short = "x" * 10
1378 + assert _truncate_frame(short) == short
1379 +
1380 + long = "y" * (_MAX_LOGGED_FRAME_CHARS + 100)
1381 + truncated = _truncate_frame(long)
1382 + assert len(truncated) < len(long)
1383 + assert truncated.startswith("y" * _MAX_LOGGED_FRAME_CHARS)
1384 + assert str(len(long)) in truncated