Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(nodes): add the Dodo Payments webhook trigger
trohitg64948f9db66f
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.mdindex f783a77c..4b065b30 100644--- a/docs-internal/plugin_system.md+++ b/docs-internal/plugin_system.md@@ -1322,7 +1322,7 @@ Drop-in HMAC schemes covering the major providers:| Class | Header | Algorithm | Used by ||---|---|---|---|| `StripeVerifier` | `Stripe-Signature: t=…,v1=…` | HMAC-SHA256 over `t.body` | Stripe |-| `StandardWebhooksVerifier` | `webhook-id` / `webhook-timestamp` / `webhook-signature` | HMAC-SHA256 base64 over `id.ts.body`; a `webhook-timestamp` more than 5 minutes from now is refused (the spec's replay window) | Svix-backed providers (Resend, Clerk, Loops, …) |+| `StandardWebhooksVerifier` | `webhook-id` / `webhook-timestamp` / `webhook-signature` | HMAC-SHA256 base64 over `id.ts.body`; a `webhook-timestamp` more than 5 minutes from now is refused (the spec's replay window) | Dodo Payments (`dodoPaymentsReceive`); also fits Svix-backed providers (Resend, Clerk, Loops, …) || `GitHubVerifier` | `X-Hub-Signature-256: sha256=…` | HMAC-SHA256 over body | GitHub || `HmacVerifier` | configurable header + prefix | HMAC-SHA256 over body | generic fallback |diff --git a/server/constants.py b/server/constants.pyindex c19e39e1..fb1b8412 100644--- a/server/constants.py+++ b/server/constants.py@@ -361,6 +361,7 @@ EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset("discordReceive","discordInteraction","stripeReceive",+ "dodoPaymentsReceive","twitterReceive","workflowTrigger","chatTrigger",@@ -411,6 +412,7 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset("discordReceive","discordInteraction","stripeReceive",+ "dodoPaymentsReceive","workflowTrigger","chatTrigger","taskTrigger",diff --git a/server/nodes/dodo_payments/__init__.py b/server/nodes/dodo_payments/__init__.pyindex 3248aca8..6bb667bc 100644--- a/server/nodes/dodo_payments/__init__.py+++ b/server/nodes/dodo_payments/__init__.py@@ -1,27 +1,45 @@"""Plugins for the 'payments' palette group — Dodo Payments via the officialdodopayments SDK.-``dodoPaymentsAction`` (AI tool ``dodo_payments_action``): typed payment,-subscription, customer, checkout and refund operations, ``call`` for any SDK-endpoint, and ``list_operations`` to discover them. Auth is the API key saved-in Credentials -> Dodo Payments, whose mode (test or live) validation finds.+* ``dodoPaymentsAction`` (AI tool ``dodo_payments_action``): typed payment,+ subscription, customer, checkout and refund operations, ``call`` for any+ SDK endpoint, and ``list_operations`` to discover them.+* ``dodoPaymentsReceive``: fires on each verified webhook delivery to+ ``/webhook/dodo-payments``, on a canvas Run and deployed.++Auth is the API key saved in Credentials -> Dodo Payments, whose mode (test+or live) validation finds, plus the webhook signing secret for the trigger.The SDK is imported lazily (``_sdk.py``), so the plugin registers and thecredentials modal answers even without it."""from __future__ import annotations+from services.deployment.canary_registry import register_canary_trigger_type+from services.events import register_webhook_sourcefrom services.node_output_schemas import register_output_schemafrom services.ws_handler_registry import register_option_loaderfrom ._credentials import DodoPaymentsCredential+from ._events import DODO_PAYMENTS_EVENT_RECEIVED_TYPEfrom ._sdk import load_dodo_payments_endpoints+from ._source import DodoPaymentsWebhookSource, get_webhook_sourcefrom .dodo_payments_action import DodoPaymentsActionNode, DodoPaymentsActionOutput+from .dodo_payments_receive import DodoPaymentsReceiveNode, DodoPaymentsReceiveOutput+register_webhook_source(get_webhook_source())+# Opt the trigger into the Temporal listener path. The second argument must+# equal the type on every envelope the source emits: it becomes the EventType+# the Visibility query matches, and a mismatch is silent.+register_canary_trigger_type(DodoPaymentsReceiveNode.type, DODO_PAYMENTS_EVENT_RECEIVED_TYPE)register_output_schema("dodoPaymentsAction", DodoPaymentsActionOutput)+register_output_schema("dodoPaymentsReceive", DodoPaymentsReceiveOutput)register_option_loader("dodoPaymentsEndpoints", load_dodo_payments_endpoints)__all__ = ["DodoPaymentsActionNode","DodoPaymentsCredential",+ "DodoPaymentsReceiveNode",+ "DodoPaymentsWebhookSource",+ "get_webhook_source",]diff --git a/server/nodes/dodo_payments/_events.py b/server/nodes/dodo_payments/_events.pynew file mode 100644index 00000000..7bf0dfdb--- /dev/null+++ b/server/nodes/dodo_payments/_events.py@@ -0,0 +1,60 @@+"""CloudEvents factory and the dispatch wrapper for Dodo Payments webhook+deliveries.++Three things here are load-bearing.++**Every Dodo event travels under one CloudEvents type.** A deployed trigger+listens for exactly one type: ``register_canary_trigger_type`` records one+string per node type, and both the listener's ``EventType`` Search Attribute+and the workflow controller's ``on_event`` match it exactly. The Dodo type+(``payment.succeeded``, ``subscription.renewed``, ...) rides in ``subject``+and in ``data["event_type"]``, which is where the node's filter reads it.++**``WebhookSource.handle`` does not reach deployed listeners.** It feeds the+in-process event waiter, which serves a canvas Run and the Temporal-off+deploy path. Deployed triggers on Temporal are reached only by+``services.events.dispatch.emit``, hence :func:`emit_dodo_payments_event`.++**Nothing is broadcast to the browser.** ``emit`` would otherwise send the+envelope to every connected socket; a payment event carries a customer's+name and email, and no client consumes it, so only the workflows hear it.+"""++from __future__ import annotations++from typing import Any, Mapping++from services.events.envelope import WorkflowEvent++# The exact string ``register_canary_trigger_type`` records for dodoPaymentsReceive.+DODO_PAYMENTS_EVENT_RECEIVED_TYPE = "com.opencompany.dodo_payments.event.received"+++def dodo_payments_event_received(data: Mapping[str, Any]) -> WorkflowEvent:+ """One verified Dodo delivery.++ The id is the delivery's ``webhook-id``, which stays the same when Dodo+ retries a delivery, so the deployed listener drops a retry as a+ duplicate. ``workflow_id`` stays unset: a Dodo event is meant to reach+ every deployment that carries the trigger.+ """+ return WorkflowEvent(+ id=str(data.get("event_id") or ""),+ source=f"dodopayments://{data.get('business_id') or 'default'}",+ type=DODO_PAYMENTS_EVENT_RECEIVED_TYPE,+ subject=str(data.get("event_type") or "") or None,+ data=dict(data),+ )+++async def emit_dodo_payments_event(event: WorkflowEvent) -> None:+ from services.events.dispatch import emit++ await emit(event, broadcast=False)+++__all__ = [+ "DODO_PAYMENTS_EVENT_RECEIVED_TYPE",+ "dodo_payments_event_received",+ "emit_dodo_payments_event",+]diff --git a/server/nodes/dodo_payments/_source.py b/server/nodes/dodo_payments/_source.pynew file mode 100644index 00000000..9b4f885e--- /dev/null+++ b/server/nodes/dodo_payments/_source.py@@ -0,0 +1,86 @@+"""Dodo Payments webhook source: the HTTP receiver behind+``POST /webhook/dodo-payments``.++Dodo signs every delivery per Standard Webhooks+(https://docs.dodopayments.com/developer-resources/webhooks): the+``webhook-id``, ``webhook-timestamp`` and ``webhook-signature`` headers, an+HMAC-SHA256 under the endpoint's ``whsec_`` secret saved in Credentials ->+Dodo Payments. ``StandardWebhooksVerifier`` checks it, refusing a timestamp+outside the spec's five-minute window, and the base ``WebhookSource`` fails+closed: 503 without a secret, 400 on a bad signature. The source then shapes+the event into the trigger's output and hands it to both the canvas-Run+waiter and deployed listeners.++A module-level singleton (``get_webhook_source``) plugs into the framework+registry from ``__init__.py``, so reloading the package re-registers the+same instance.+"""++from __future__ import annotations++from typing import Any, Dict, Optional++from fastapi import Request++from services.events import StandardWebhooksVerifier, WebhookSource, WorkflowEvent++from ._credentials import WEBHOOK_KEY_FIELD, DodoPaymentsCredential+from ._events import dodo_payments_event_received, emit_dodo_payments_event+++def shape_dodo_payments_event(payload: Dict[str, Any], *, event_id: str) -> Dict[str, Any]:+ """Flatten one Dodo delivery (``{business_id, type, timestamp, data}``)+ into the trigger's output.++ Shaped here rather than in the node's ``shape_output``: a deployed trigger+ hands downstream nodes ``event.data`` verbatim, so shaping on the node+ would make Run and deploy disagree about the fields.+ """+ data = payload.get("data")+ if not isinstance(data, dict):+ data = {}+ return {+ "event_id": event_id,+ "event_type": payload.get("type") or "unknown",+ "business_id": payload.get("business_id"),+ "timestamp": payload.get("timestamp"),+ "payload_type": data.get("payload_type"),+ "data": data,+ }+++class DodoPaymentsWebhookSource(WebhookSource):+ """HTTP receiver for Dodo Payments webhook deliveries."""++ type = "dodo_payments.webhook"+ path = "dodo-payments"+ verifier = StandardWebhooksVerifier+ secret_field = WEBHOOK_KEY_FIELD+ credential = DodoPaymentsCredential++ async def shape(self, request: Request, body: bytes, payload: dict) -> WorkflowEvent:+ # The verifier has already required the header.+ return dodo_payments_event_received(+ shape_dodo_payments_event(payload, event_id=request.headers.get("webhook-id") or "")+ )++ async def handle(self, request: Request) -> WorkflowEvent:+ # The base class verifies the signature, shapes the event and wakes a+ # waiting canvas Run (and the Temporal-off deploy path). Deployed+ # triggers on Temporal are reached only through emit.+ event = await super().handle(request)+ await emit_dodo_payments_event(event)+ return event+++_webhook: Optional[DodoPaymentsWebhookSource] = None+++def get_webhook_source() -> DodoPaymentsWebhookSource:+ global _webhook+ if _webhook is None:+ _webhook = DodoPaymentsWebhookSource()+ return _webhook+++__all__ = ["DodoPaymentsWebhookSource", "get_webhook_source", "shape_dodo_payments_event"]diff --git a/server/nodes/dodo_payments/dodo_payments_receive.py b/server/nodes/dodo_payments/dodo_payments_receive.pynew file mode 100644index 00000000..b9b48482--- /dev/null+++ b/server/nodes/dodo_payments/dodo_payments_receive.py@@ -0,0 +1,95 @@+"""Dodo Payments Receive — fires when DodoPaymentsWebhookSource accepts a+verified webhook delivery."""++from __future__ import annotations++from typing import Any, Callable, Dict, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.events import BaseTriggerParams, WebhookTriggerNode, WorkflowEvent+from services.events.envelope import event_type_matches++from ._credentials import WEBHOOK_KEY_FIELD, DodoPaymentsCredential+from ._events import DODO_PAYMENTS_EVENT_RECEIVED_TYPE+from ._source import DodoPaymentsWebhookSource+++class DodoPaymentsReceiveParams(BaseTriggerParams):+ event_type_filter: str = Field(+ default="all",+ description=(+ "Dodo event type to match: 'all', an exact type such as 'payment.succeeded', "+ "or a prefix such as 'subscription.*'"+ ),+ )+++class DodoPaymentsReceiveOutput(BaseModel):+ event_id: Optional[str] = None+ event_type: Optional[str] = None+ business_id: Optional[str] = None+ timestamp: Optional[str] = None+ payload_type: Optional[str] = None+ data: Optional[dict] = None++ model_config = ConfigDict(extra="allow")+++class DodoPaymentsReceiveNode(WebhookTriggerNode):+ type = "dodoPaymentsReceive"+ display_name = "Dodo Payments Receive"+ subtitle = "Webhook Event"+ group = ("payments", "trigger")+ description = "Trigger a workflow when Dodo Payments sends a webhook event (payments, refunds, disputes, subscriptions, ...)"+ component_kind = "trigger"+ handles = ({"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},)+ credentials = (DodoPaymentsCredential,)+ webhook_source = DodoPaymentsWebhookSource+ # The canvas Run's waiter key, and the type the source dispatches. Left+ # unset, the base class would derive the source's own type+ # ("dodo_payments.webhook"), which no envelope carries.+ event_type = DODO_PAYMENTS_EVENT_RECEIVED_TYPE+ Params = DodoPaymentsReceiveParams+ Output = DodoPaymentsReceiveOutput++ def build_filter(self, params: DodoPaymentsReceiveParams) -> Callable[[Any], bool]:+ """Match on the shaped event the source emits.++ Both callers hand the predicate the envelope's ``data``: the event+ waiter on a canvas Run (and the Temporal-off deploy path), and+ ``evaluate_trigger_filter_activity`` on a deployed Temporal listener.+ The base filter rebuilds an envelope from what it receives, which+ would raise on every Dodo event and, deployed, fail open. Every Dodo+ event shares one CloudEvents type, so the Dodo type is read from+ ``data["event_type"]``.+ """+ pattern = (params.event_type_filter or "all").strip()++ def matches(event: Any) -> bool:+ data = event.data if isinstance(event, WorkflowEvent) else event+ return isinstance(data, dict) and event_type_matches(str(data.get("event_type") or ""), pattern)++ return matches++ async def _check_precondition(self) -> Optional[str]:+ """Without a key and a webhook secret, every delivery is refused with+ 503 and a canvas Run would wait for nothing: say so at once."""+ try:+ secrets = await DodoPaymentsCredential.resolve()+ except PermissionError:+ return "Add the Dodo Payments API key in Credentials -> Dodo Payments, then its webhook secret."+ if not secrets.get(WEBHOOK_KEY_FIELD):+ return (+ "Save the webhook secret (whsec_...) in Credentials -> Dodo Payments: Dodo signs every "+ "delivery to /webhook/dodo-payments with it."+ )+ return None++ def shape_output(self, event: WorkflowEvent) -> Dict:+ """Unwrap the shaped event, which is what the deployed path emits, so+ a canvas Run and a deployed run see the same fields."""+ return event.data if isinstance(event.data, dict) else {}+++__all__ = ["DodoPaymentsReceiveNode", "DodoPaymentsReceiveOutput", "DodoPaymentsReceiveParams"]diff --git a/server/tests/nodes/test_dodo_payments.py b/server/tests/nodes/test_dodo_payments.pyindex 2235acaf..800a47e2 100644--- a/server/tests/nodes/test_dodo_payments.py+++ b/server/tests/nodes/test_dodo_payments.py@@ -1,19 +1,26 @@-"""Contract tests for the Dodo Payments action node (``dodoPaymentsAction``).+"""Contract tests for the Dodo Payments plugin: the action node+(``dodoPaymentsAction``) and the webhook trigger (``dodoPaymentsReceive``).The node calls Dodo through the official ``dodopayments`` SDK; every SDK touchlives in ``nodes/dodo_payments/_sdk.py``. These tests run the real SDK andintercept its HTTP traffic with respx, so requests are built exactly as theSDK builds them and nothing touches the network. Base URLs come from the-SDK's own ``ENVIRONMENTS``.+SDK's own ``ENVIRONMENTS``. Webhook deliveries are signed the Standard+Webhooks way, as Dodo signs them."""from __future__ import annotations+import asyncio+import base64+import hashlib+import hmacimport inspectimport jsonimport reimport subprocessimport sys+import timeimport typingfrom pathlib import Pathfrom typing import get_args@@ -23,6 +30,7 @@ import httpximport pytestimport respxfrom dodopayments import ENVIRONMENTS+from fastapi import HTTPExceptionfrom tests.nodes._mocks import patched_container@@ -30,7 +38,10 @@ pytestmark = pytest.mark.node_contractimport nodes.dodo_payments as dodo_pkg # noqa: E402from nodes.dodo_payments import _sdk, dodo_payments_action # noqa: E402-from nodes.dodo_payments._credentials import MODE_FIELD, MODES, DodoPaymentsCredential # noqa: E402+from nodes.dodo_payments._credentials import MODE_FIELD, MODES, WEBHOOK_KEY_FIELD, DodoPaymentsCredential # noqa: E402+from nodes.dodo_payments._events import DODO_PAYMENTS_EVENT_RECEIVED_TYPE # noqa: E402+from nodes.dodo_payments._source import get_webhook_source, shape_dodo_payments_event # noqa: E402+from nodes.dodo_payments.dodo_payments_receive import DodoPaymentsReceiveNode, DodoPaymentsReceiveParams # noqa: E402from services.node_registry import get_node_class # noqa: E402from services.plugin.credential import CREDENTIAL_REGISTRY # noqa: E402from services.ws_handler_registry import get_option_loader # noqa: E402@@ -730,3 +741,256 @@ class TestCatalogueAndAssets:assert re.fullmatch(r"#[0-9a-fA-F]{6}", meta["color"])assert "<svg" in (PLUGIN_DIR / "icon.svg").read_text(encoding="utf-8")assert DodoPaymentsCredential.get_icon_path() == PLUGIN_DIR / "dodo_payments.svg"+++# ============================================================================+# Dodo Payments Receive — the webhook source+# ============================================================================++WEBHOOK_RAW = b"dodo-webhook-signing-key"+WEBHOOK_SECRET = "whsec_" + base64.b64encode(WEBHOOK_RAW).decode()+++def _payload(event_type: str = "payment.succeeded") -> dict:+ """A delivery as Dodo posts it."""+ return {+ "business_id": "bus_1",+ "type": event_type,+ "timestamp": "2026-10-15T08:00:00Z",+ "data": {"payload_type": "Payment", "payment_id": "pay_1", "total_amount": 900},+ }+++def _delivery(event_type: str = "payment.succeeded", *, msg_id: str = "msg_1", key: bytes = WEBHOOK_RAW, sent_at=None):+ body = json.dumps(_payload(event_type)).encode()+ stamp = str(int(time.time()) if sent_at is None else sent_at)+ signature = base64.b64encode(hmac.new(key, f"{msg_id}.{stamp}.".encode() + body, hashlib.sha256).digest()).decode()+ return body, {"webhook-id": msg_id, "webhook-timestamp": stamp, "webhook-signature": f"v1,{signature}"}+++def _request(body: bytes, headers: dict):+ """An object with the two attributes WebhookSource.handle reads."""++ class Request:+ pass++ request = Request()+ request.headers = headers++ async def read():+ return body++ request.body = read+ return request+++def _secrets(**overrides):+ secrets = {"api_key": "k", MODE_FIELD: "test_mode", WEBHOOK_KEY_FIELD: WEBHOOK_SECRET, **overrides}+ return patch.object(DodoPaymentsCredential, "resolve", AsyncMock(return_value={k: v for k, v in secrets.items() if v}))+++class TestWebhookSource:+ def test_registered_at_its_path(self):+ from services.events import WEBHOOK_SOURCES++ assert WEBHOOK_SOURCES["dodo-payments"] is get_webhook_source()++ def test_a_delivery_is_flattened_for_the_trigger(self):+ assert shape_dodo_payments_event(_payload(), event_id="msg_1") == {+ "event_id": "msg_1",+ "event_type": "payment.succeeded",+ "business_id": "bus_1",+ "timestamp": "2026-10-15T08:00:00Z",+ "payload_type": "Payment",+ "data": {"payload_type": "Payment", "payment_id": "pay_1", "total_amount": 900},+ }++ async def test_a_signed_delivery_reaches_the_waiter_and_the_listeners(self):+ body, headers = _delivery("subscription.renewed")+ with (+ _secrets(),+ patch("services.event_waiter.dispatch") as waiter,+ patch("services.events.dispatch.emit", new=AsyncMock()) as emit,+ ):+ event = await get_webhook_source().handle(_request(body, headers))++ (dispatched,) = waiter.call_args.args+ assert dispatched is event+ emit.assert_awaited_once()+ # Payment events carry customer details and no client reads them, so+ # they go to the workflows only, never to every connected socket.+ assert emit.await_args.args == (event,)+ assert emit.await_args.kwargs == {"broadcast": False}+ # The webhook-id stays the same across retried deliveries, so a+ # deployed listener drops a retry as a duplicate.+ assert event.id == "msg_1"+ assert event.type == DODO_PAYMENTS_EVENT_RECEIVED_TYPE+ assert event.subject == "subscription.renewed"+ assert event.source == "dodopayments://bus_1"+ assert event.workflow_id is None++ @pytest.mark.parametrize(+ "delivery",+ [+ pytest.param(lambda: _delivery(key=b"another-key"), id="wrong-key"),+ pytest.param(lambda: _delivery(sent_at=int(time.time()) - 3600), id="replayed-an-hour-later"),+ ],+ )+ async def test_an_unverifiable_delivery_is_refused(self, delivery):+ body, headers = delivery()+ with _secrets(), patch("services.events.dispatch.emit", new=AsyncMock()) as emit:+ with pytest.raises(HTTPException) as refused:+ await get_webhook_source().handle(_request(body, headers))++ assert refused.value.status_code == 400+ emit.assert_not_awaited()++ async def test_without_a_secret_deliveries_wait(self):+ body, headers = _delivery()+ with _secrets(**{WEBHOOK_KEY_FIELD: ""}), patch("services.events.dispatch.emit", new=AsyncMock()) as emit:+ with pytest.raises(HTTPException) as refused:+ await get_webhook_source().handle(_request(body, headers))++ assert refused.value.status_code == 503+ emit.assert_not_awaited()+++# ============================================================================+# Dodo Payments Receive — the node+# ============================================================================+++class TestReceiveFilter:+ """Both callers hand the filter the envelope's ``data``: the event waiter+ on a canvas Run, and ``evaluate_trigger_filter_activity`` once deployed."""++ def _filter(self, pattern: str):+ return DodoPaymentsReceiveNode().build_filter(DodoPaymentsReceiveParams(event_type_filter=pattern))++ def _data(self, event_type: str) -> dict:+ return shape_dodo_payments_event(_payload(event_type), event_id="msg_1")++ def test_all_matches_anything(self):+ assert self._filter("all")(self._data("refund.failed")) is True++ def test_exact_and_prefix_patterns(self):+ exact = self._filter("payment.succeeded")+ prefix = self._filter("subscription.*")+ assert exact(self._data("payment.succeeded")) is True+ assert exact(self._data("payment.failed")) is False+ assert prefix(self._data("subscription.cancelled")) is True+ assert prefix(self._data("payment.succeeded")) is False++ def test_an_envelope_is_accepted_and_junk_is_not(self):+ from nodes.dodo_payments._events import dodo_payments_event_received++ envelope = dodo_payments_event_received(self._data("dispute.opened"))+ assert self._filter("dispute.*")(envelope) is True+ assert self._filter("all")("not a payload") is False++ def test_shape_output_is_the_shaped_delivery(self):+ from nodes.dodo_payments._events import dodo_payments_event_received++ data = self._data("payment.succeeded")+ assert DodoPaymentsReceiveNode().shape_output(dodo_payments_event_received(data)) == data+++class TestPrecondition:+ async def test_without_a_key(self):+ with patch.object(DodoPaymentsCredential, "resolve", AsyncMock(side_effect=PermissionError("No API key"))):+ message = await DodoPaymentsReceiveNode()._check_precondition()+ assert "API key" in message++ async def test_without_a_webhook_secret(self):+ with _secrets(**{WEBHOOK_KEY_FIELD: ""}):+ message = await DodoPaymentsReceiveNode()._check_precondition()+ assert "webhook secret" in message++ async def test_ready(self):+ with _secrets():+ assert await DodoPaymentsReceiveNode()._check_precondition() is None+++class TestCanvasRunResolves:+ """End to end through the real event waiter: ``execute`` registers a+ waiter keyed on the CloudEvents type, ``handle`` dispatches a signed+ delivery."""++ async def _run(self, params: dict, event_type: str):+ from services import event_waiter++ node = DodoPaymentsReceiveNode()+ body, headers = _delivery(event_type)+ with _secrets(), patch("services.events.dispatch.emit", new=AsyncMock()):+ task = asyncio.create_task(node.execute("dodo-run-node", params, None))+ # Let execute register its waiter before the delivery arrives.+ for _ in range(20):+ if any(w.node_id == "dodo-run-node" for w in event_waiter._waiters.values()):+ break+ await asyncio.sleep(0)+ await get_webhook_source().handle(_request(body, headers))+ try:+ return await asyncio.wait_for(asyncio.shield(task), timeout=0.5)+ except asyncio.TimeoutError:+ return None+ finally:+ event_waiter.cancel_for_node("dodo-run-node")+ if not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ async def test_a_matching_delivery_resolves_the_run(self):+ result = await self._run({"event_type_filter": "payment.*"}, "payment.succeeded")+ assert result is not None, "the canvas Run never resolved"+ assert result["success"] is True, result+ assert result["result"]["event_id"] == "msg_1"+ assert result["result"]["event_type"] == "payment.succeeded"+ assert result["result"]["data"]["payment_id"] == "pay_1"++ async def test_a_filtered_delivery_leaves_the_run_waiting(self):+ assert await self._run({"event_type_filter": "refund.*"}, "payment.succeeded") is None+++class TestDeployedPath:+ def test_the_trigger_is_deployable(self):+ """find_trigger_nodes filters on these sets: a trigger missing from+ them is silently ignored at deploy."""+ from constants import EVENT_TRIGGER_TYPES, WORKFLOW_TRIGGER_TYPES++ assert "dodoPaymentsReceive" in WORKFLOW_TRIGGER_TYPES+ assert "dodoPaymentsReceive" in EVENT_TRIGGER_TYPES++ async def test_the_canary_type_matches_every_emitted_envelope(self):+ from services.deployment.canary_registry import cloudevent_type_for++ assert cloudevent_type_for("dodoPaymentsReceive") == DODO_PAYMENTS_EVENT_RECEIVED_TYPE+ assert DodoPaymentsReceiveNode.event_type == DODO_PAYMENTS_EVENT_RECEIVED_TYPE+ for event_type in ("payment.succeeded", "refund.failed", "subscription.plan_changed"):+ body, headers = _delivery(event_type)+ event = await get_webhook_source().shape(_request(body, headers), body, _payload(event_type))+ assert event.type == DODO_PAYMENTS_EVENT_RECEIVED_TYPE+ assert event.subject == event_type++ @pytest.mark.parametrize(+ ("pattern", "event_type", "admitted"),+ [("payment.*", "payment.failed", True), ("payment.*", "refund.succeeded", False)],+ )+ async def test_the_deployed_filter_applies(self, pattern, event_type, admitted):+ """The deployed listener runs the node's filter through this activity,+ which admits the event whenever the filter raises."""+ from services.temporal.activities import evaluate_trigger_filter_activity++ result = await evaluate_trigger_filter_activity(+ {+ "node_type": "dodoPaymentsReceive",+ "filter_params": {"event_type_filter": pattern},+ "event_data": shape_dodo_payments_event(_payload(event_type), event_id="msg_1"),+ }+ )+ assert result is admitted++ def test_both_nodes_and_their_output_schemas_are_registered(self):+ from services.node_output_schemas import NODE_OUTPUT_SCHEMAS++ assert get_node_class("dodoPaymentsReceive") is DodoPaymentsReceiveNode+ assert {"dodoPaymentsAction", "dodoPaymentsReceive"} <= set(NODE_OUTPUT_SCHEMAS)