4
import hashlib
5
import hmac
6
import json
7
+import threading
8
import time
9
from datetime import datetime, timezone
10
from unittest.mock import Mock, patch
16
from composio import exceptions
17
from composio.core.models.triggers import (
18
_MAX_LOGGED_FRAME_CHARS,
19
+ ComposioSDKTimeoutError,
20
Triggers,
21
TriggerSubscription,
22
WebhookVersion,
23
+ _SubcriptionBuilder,
24
_truncate_frame,
25
)
26
1587
assert len(truncated) < len(long)
1588
assert truncated.startswith("y" * _MAX_LOGGED_FRAME_CHARS)
1589
assert str(len(long)) in truncated
1590
+
1591
+
1592
+class TestTriggerSubscriptionStop:
1593
+ """Tests for TriggerSubscription.stop lifecycle handling."""
1594
+
1595
+ @pytest.fixture
1596
+ def subscription(self):
1597
+ """Create a TriggerSubscription with a mock client."""
1598
+ sub = TriggerSubscription(client=Mock())
1599
+ sub._alive = True
1600
+ return sub
1601
+
1602
+ def test_stop_clears_alive_synchronously(self, subscription):
1603
+ """``_alive`` is cleared before ``stop`` returns, not after disconnect.
1604
+
1605
+ A main thread parked in ``wait_forever`` checks ``_alive`` every
1606
+ second; clearing it synchronously (rather than after a potentially
1607
+ blocking ``disconnect``) lets that loop exit promptly.
1608
+ """
1609
+ disconnect_started = threading.Event()
1610
+
1611
+ def blocking_disconnect():
1612
+ disconnect_started.set()
1613
+ # Block so we can prove _alive was cleared without waiting on
1614
+ # the disconnect.
1615
+ threading.Event().wait(timeout=5)
1616
+
1617
+ subscription._connection = Mock()
1618
+ subscription._connection.disconnect = blocking_disconnect
1619
+
1620
+ subscription.stop()
1621
+
1622
+ # _alive is False the moment stop() returns, even though disconnect
1623
+ # is still running in the background.
1624
+ assert subscription.is_alive() is False
1625
+ assert disconnect_started.wait(timeout=2)
1626
+
1627
+ def test_stop_does_not_block_on_slow_disconnect(self, subscription):
1628
+ """``stop()`` returns even if ``disconnect`` would block forever.
1629
+
1630
+ pysher's ``Connection.disconnect`` joins the websocket thread. When
1631
+ ``stop()`` is called from a callback that pysher dispatches on that
1632
+ same thread, the join deadlocks. Running the disconnect on a daemon
1633
+ thread breaks the reentrancy: ``stop`` returns immediately even when
1634
+ ``disconnect`` never completes.
1635
+ """
1636
+ started = threading.Event()
1637
+ never_set = threading.Event()
1638
+
1639
+ def blocking_disconnect():
1640
+ started.set()
1641
+ # Simulate pysher joining a thread that never finishes (the
1642
+ # deadlock state from the bug report).
1643
+ never_set.wait(timeout=5)
1644
+
1645
+ subscription._connection = Mock()
1646
+ subscription._connection.disconnect = blocking_disconnect
1647
+
1648
+ # If stop() were to call disconnect() inline it would block here.
1649
+ subscription.stop()
1650
+
1651
+ # stop() returned control and the disconnect is running in the
1652
+ # background.
1653
+ assert subscription.is_alive() is False
1654
+ assert started.wait(timeout=2)
1655
+
1656
+
1657
+class TestSubscriptionBuilderConnectTimeout:
1658
+ """Tests for _SubcriptionBuilder.connect timeout teardown."""
1659
+
1660
+ def _make_builder(self, pusher: Mock) -> _SubcriptionBuilder:
1661
+ """Build a _SubcriptionBuilder with a patched pusher factory."""
1662
+ client = Mock()
1663
+ client.base_url = "https://api.example.com"
1664
+ with patch.object(
1665
+ _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
1666
+ ):
1667
+ b = _SubcriptionBuilder(client=client)
1668
+ b.subscription = Mock()
1669
+ b.subscription.is_alive.return_value = False
1670
+ b.internal = Mock()
1671
+ b.internal.get_sdk_realtime_credentials.return_value = Mock(
1672
+ project_id="p", pusher_key="k", pusher_cluster="c"
1673
+ )
1674
+ b._get_connection_handler = Mock( # type: ignore[method-assign]
1675
+ return_value=lambda *a, **k: None
1676
+ )
1677
+ return b
1678
+
1679
+ def test_connect_disconnects_pusher_on_timeout(self):
1680
+ """On timeout, the partially-connected pusher is torn down.
1681
+
1682
+ pysher's connection loop redials every ``reconnect_interval`` until
1683
+ ``disconnect`` is called. If ``connect`` raises without disconnecting,
1684
+ each timed-out attempt leaks a websocket thread for the life of the
1685
+ process. The fix wraps the wait loop in try/except so the timeout
1686
+ path disconnects before re-raising.
1687
+ """
1688
+ pusher = Mock()
1689
+ builder = self._make_builder(pusher)
1690
+ # subscription.is_alive() returns False, so the wait loop never
1691
+ # returns early -> the deadline elapses -> timeout path runs.
1692
+ builder.subscription.is_alive.return_value = False
1693
+
1694
+ with (
1695
+ patch.object(
1696
+ _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
1697
+ ),
1698
+ pytest.raises(ComposioSDKTimeoutError),
1699
+ ):
1700
+ builder.connect(timeout=0.1)
1701
+
1702
+ pusher.disconnect.assert_called_once()
1703
+
1704
+ def test_connect_returns_subscription_without_disconnecting(self):
1705
+ """On success, the pusher stays connected and is attached to the sub."""
1706
+ pusher = Mock()
1707
+ builder = self._make_builder(pusher)
1708
+ builder.subscription.is_alive.return_value = True
1709
+
1710
+ with patch.object(
1711
+ _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
1712
+ ):
1713
+ result = builder.connect(timeout=2.0)
1714
+
1715
+ assert result is builder.subscription
1716
+ pusher.disconnect.assert_not_called()