phoenix-channels-python-client 0.4.0__py3-none-any.whl → 0.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- phoenix_channels_python_client/__init__.py +3 -1
- phoenix_channels_python_client/client.py +24 -0
- phoenix_channels_python_client/client_types.py +4 -1
- phoenix_channels_python_client/supervisor.py +85 -42
- phoenix_channels_python_client/topic_runtime.py +181 -45
- phoenix_channels_python_client/topic_subscription.py +6 -0
- {phoenix_channels_python_client-0.4.0.dist-info → phoenix_channels_python_client-0.4.2.dist-info}/METADATA +89 -5
- {phoenix_channels_python_client-0.4.0.dist-info → phoenix_channels_python_client-0.4.2.dist-info}/RECORD +11 -11
- {phoenix_channels_python_client-0.4.0.dist-info → phoenix_channels_python_client-0.4.2.dist-info}/WHEEL +1 -1
- {phoenix_channels_python_client-0.4.0.dist-info → phoenix_channels_python_client-0.4.2.dist-info}/licenses/LICENSE +0 -0
- {phoenix_channels_python_client-0.4.0.dist-info → phoenix_channels_python_client-0.4.2.dist-info}/top_level.txt +0 -0
|
@@ -13,18 +13,20 @@ from phoenix_channels_python_client.client import (
|
|
|
13
13
|
ReconnectPolicy,
|
|
14
14
|
TopicLostCallback,
|
|
15
15
|
)
|
|
16
|
+
from phoenix_channels_python_client.client_types import JoinResponseCallback
|
|
16
17
|
from phoenix_channels_python_client.protocol_handler import (
|
|
17
18
|
PhoenixChannelsProtocolVersion,
|
|
18
19
|
PHXProtocolHandler,
|
|
19
20
|
)
|
|
20
21
|
from phoenix_channels_python_client.utils import setup_logging
|
|
21
22
|
|
|
22
|
-
__version__ = "0.4.
|
|
23
|
+
__version__ = "0.4.2"
|
|
23
24
|
__author__ = "Phoenix Channels Python Client"
|
|
24
25
|
|
|
25
26
|
__all__ = [
|
|
26
27
|
"DisconnectCallback",
|
|
27
28
|
"HeartbeatAckCallback",
|
|
29
|
+
"JoinResponseCallback",
|
|
28
30
|
"PHXChannelsClient",
|
|
29
31
|
"PHXProtocolHandler",
|
|
30
32
|
"PhoenixChannelsProtocolVersion",
|
|
@@ -2,6 +2,7 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import logging
|
|
5
|
+
import math
|
|
5
6
|
from collections import deque
|
|
6
7
|
from collections.abc import Awaitable, Callable
|
|
7
8
|
from types import TracebackType
|
|
@@ -99,6 +100,19 @@ def _build_channel_socket_urls(
|
|
|
99
100
|
)
|
|
100
101
|
|
|
101
102
|
|
|
103
|
+
def _validate_heartbeat_threshold(
|
|
104
|
+
interval: float | None, threshold: float | None
|
|
105
|
+
) -> None:
|
|
106
|
+
if threshold is None:
|
|
107
|
+
return
|
|
108
|
+
if not math.isfinite(threshold) or threshold <= 0:
|
|
109
|
+
raise ValueError("heartbeat_dead_threshold_s must be finite and > 0")
|
|
110
|
+
if interval is not None and (not math.isfinite(interval) or threshold <= interval):
|
|
111
|
+
raise ValueError(
|
|
112
|
+
"heartbeat_dead_threshold_s must exceed the finite heartbeat interval"
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
102
116
|
class PHXChannelsClient(SupervisorMixin, TopicRuntimeMixin, ReconnectControllerMixin):
|
|
103
117
|
def __init__( # noqa: PLR0913 # the public options
|
|
104
118
|
self,
|
|
@@ -114,6 +128,7 @@ class PHXChannelsClient(SupervisorMixin, TopicRuntimeMixin, ReconnectControllerM
|
|
|
114
128
|
max_topic_queue_size: int = 1000,
|
|
115
129
|
callback_drain_timeout_s: float = 2.0,
|
|
116
130
|
heartbeat_interval_s: float | None = 30.0,
|
|
131
|
+
heartbeat_dead_threshold_s: float | None = None,
|
|
117
132
|
on_reconnect: ReconnectCallback | None = None,
|
|
118
133
|
on_disconnect: DisconnectCallback | None = None,
|
|
119
134
|
on_heartbeat_ack: HeartbeatAckCallback | None = None,
|
|
@@ -128,6 +143,8 @@ class PHXChannelsClient(SupervisorMixin, TopicRuntimeMixin, ReconnectControllerM
|
|
|
128
143
|
if heartbeat_interval_s is not None and heartbeat_interval_s <= 0:
|
|
129
144
|
raise ValueError("heartbeat_interval_s must be > 0 or None to disable")
|
|
130
145
|
|
|
146
|
+
_validate_heartbeat_threshold(heartbeat_interval_s, heartbeat_dead_threshold_s)
|
|
147
|
+
|
|
131
148
|
if join_timeout_s <= 0:
|
|
132
149
|
raise ValueError("join_timeout_s must be > 0")
|
|
133
150
|
if leave_timeout_s <= 0:
|
|
@@ -170,6 +187,9 @@ class PHXChannelsClient(SupervisorMixin, TopicRuntimeMixin, ReconnectControllerM
|
|
|
170
187
|
self._initial_connection_future: asyncio.Future[None] | None = None
|
|
171
188
|
self._rapid_disconnects: deque[float] = deque()
|
|
172
189
|
self._terminal_error: Exception | None = None
|
|
190
|
+
self._heartbeat_dead_threshold_s = heartbeat_dead_threshold_s
|
|
191
|
+
self._heartbeat_deadline: float | None = None
|
|
192
|
+
self._heartbeat_timeout: asyncio.Timeout | None = None
|
|
173
193
|
self._heartbeat_interval_s = heartbeat_interval_s
|
|
174
194
|
self._heartbeat_task: asyncio.Task[None] | None = None
|
|
175
195
|
self._pending_heartbeat_ref: str | None = None
|
|
@@ -178,6 +198,7 @@ class PHXChannelsClient(SupervisorMixin, TopicRuntimeMixin, ReconnectControllerM
|
|
|
178
198
|
self._on_heartbeat_ack = on_heartbeat_ack
|
|
179
199
|
self._on_topic_lost = on_topic_lost
|
|
180
200
|
self._lifecycle_tasks: set[asyncio.Task[None]] = set()
|
|
201
|
+
self._cleanup_tasks: set[asyncio.Task[None]] = set()
|
|
181
202
|
self._forced_close_pending = False
|
|
182
203
|
|
|
183
204
|
def redact_diagnostic(self, text: str) -> str:
|
|
@@ -195,6 +216,7 @@ class PHXChannelsClient(SupervisorMixin, TopicRuntimeMixin, ReconnectControllerM
|
|
|
195
216
|
self._state == ClientState.CLOSED
|
|
196
217
|
and not self._topic_subscriptions
|
|
197
218
|
and self.connection is None
|
|
219
|
+
and not self._cleanup_tasks
|
|
198
220
|
)
|
|
199
221
|
|
|
200
222
|
async def __aenter__(self) -> Self:
|
|
@@ -253,6 +275,8 @@ class PHXChannelsClient(SupervisorMixin, TopicRuntimeMixin, ReconnectControllerM
|
|
|
253
275
|
await self._unsubscribe_all()
|
|
254
276
|
# Includes on_topic_lost callbacks still running for topics already gone.
|
|
255
277
|
await cancel_and_wait(*self._lifecycle_tasks)
|
|
278
|
+
if self._cleanup_tasks:
|
|
279
|
+
await asyncio.gather(*self._cleanup_tasks)
|
|
256
280
|
await self._stop_supervisor()
|
|
257
281
|
await self._cleanup_connection()
|
|
258
282
|
self._connected_event.clear()
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
from collections.abc import Callable
|
|
3
4
|
from dataclasses import dataclass
|
|
4
5
|
from enum import StrEnum
|
|
5
|
-
from typing import Self
|
|
6
|
+
from typing import Any, Self
|
|
6
7
|
|
|
7
8
|
from pydantic import (
|
|
8
9
|
BaseModel,
|
|
@@ -15,6 +16,8 @@ from pydantic import (
|
|
|
15
16
|
|
|
16
17
|
from phoenix_channels_python_client.exceptions import PHXConnectionError
|
|
17
18
|
|
|
19
|
+
JoinResponseCallback = Callable[[Any], None]
|
|
20
|
+
|
|
18
21
|
|
|
19
22
|
class ClientState(StrEnum):
|
|
20
23
|
CONNECTING = "connecting"
|
|
@@ -94,6 +94,9 @@ class SupervisorMixin:
|
|
|
94
94
|
_initial_connection_future: asyncio.Future[None] | None
|
|
95
95
|
_rapid_disconnects: deque[float]
|
|
96
96
|
_terminal_error: Exception | None
|
|
97
|
+
_heartbeat_dead_threshold_s: float | None
|
|
98
|
+
_heartbeat_deadline: float | None
|
|
99
|
+
_heartbeat_timeout: asyncio.Timeout | None
|
|
97
100
|
_heartbeat_interval_s: float | None
|
|
98
101
|
_heartbeat_task: asyncio.Task[None] | None
|
|
99
102
|
_pending_heartbeat_ref: str | None
|
|
@@ -118,6 +121,17 @@ class SupervisorMixin:
|
|
|
118
121
|
|
|
119
122
|
def _handle_heartbeat_response(self, message: ChannelMessage) -> None:
|
|
120
123
|
if message.ref is not None and message.ref == self._pending_heartbeat_ref:
|
|
124
|
+
if self._heartbeat_dead_threshold_s is not None:
|
|
125
|
+
timer = self._heartbeat_timeout
|
|
126
|
+
now = asyncio.get_running_loop().time()
|
|
127
|
+
if (
|
|
128
|
+
timer is None
|
|
129
|
+
or timer.expired()
|
|
130
|
+
or (deadline := timer.when()) is None
|
|
131
|
+
or now >= deadline
|
|
132
|
+
):
|
|
133
|
+
return
|
|
134
|
+
timer.reschedule(now + self._heartbeat_dead_threshold_s)
|
|
121
135
|
self.logger.debug("Heartbeat acknowledged (ref=%s)", message.ref)
|
|
122
136
|
self._pending_heartbeat_ref = None
|
|
123
137
|
if self._on_heartbeat_ack is not None:
|
|
@@ -149,6 +163,11 @@ class SupervisorMixin:
|
|
|
149
163
|
connection = self.connection
|
|
150
164
|
if connection is None:
|
|
151
165
|
return
|
|
166
|
+
await self._force_close_connection(connection, reason)
|
|
167
|
+
|
|
168
|
+
async def _force_close_connection(
|
|
169
|
+
self, connection: ClientConnection, reason: str
|
|
170
|
+
) -> None:
|
|
152
171
|
if connection.state is not State.OPEN:
|
|
153
172
|
self.logger.debug(
|
|
154
173
|
"Not forcing a close; connection is already %s", connection.state.name
|
|
@@ -157,52 +176,67 @@ class SupervisorMixin:
|
|
|
157
176
|
reason = _truncate_close_reason(reason)
|
|
158
177
|
self.logger.info("Forcing connection close: %s", reason)
|
|
159
178
|
self._forced_close_pending = True
|
|
160
|
-
await connection.close(code=_FORCED_CLOSE_CODE, reason=reason)
|
|
161
|
-
|
|
162
|
-
async def _heartbeat_loop(self, connection: ClientConnection) -> None:
|
|
163
|
-
if self._heartbeat_interval_s is None:
|
|
164
|
-
return
|
|
165
|
-
|
|
166
|
-
self.logger.debug(
|
|
167
|
-
"Starting heartbeat loop (interval=%ss)", self._heartbeat_interval_s
|
|
168
|
-
)
|
|
169
|
-
|
|
170
179
|
try:
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
180
|
+
await connection.close(code=_FORCED_CLOSE_CODE, reason=reason)
|
|
181
|
+
except (Exception, asyncio.CancelledError):
|
|
182
|
+
connection.transport.abort()
|
|
183
|
+
raise
|
|
175
184
|
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
185
|
+
async def _heartbeat_loop(
|
|
186
|
+
self, connection: ClientConnection, deadline: float | None = None
|
|
187
|
+
) -> None:
|
|
188
|
+
timer = asyncio.timeout_at(deadline)
|
|
189
|
+
try:
|
|
190
|
+
async with timer:
|
|
191
|
+
self._heartbeat_timeout = timer
|
|
192
|
+
try:
|
|
193
|
+
await self._send_heartbeats(connection)
|
|
194
|
+
finally:
|
|
195
|
+
self._heartbeat_timeout = None
|
|
196
|
+
except TimeoutError:
|
|
197
|
+
if timer.expired():
|
|
198
|
+
self.logger.warning("Heartbeat acknowledgement deadline expired")
|
|
199
|
+
elif self._heartbeat_dead_threshold_s is not None:
|
|
200
|
+
self.logger.exception("Heartbeat send timed out")
|
|
201
|
+
except Exception:
|
|
202
|
+
if self._heartbeat_dead_threshold_s is None:
|
|
203
|
+
self.logger.debug("Failed to send heartbeat; connection likely closing")
|
|
204
|
+
return
|
|
205
|
+
self.logger.exception("Failed to send heartbeat")
|
|
206
|
+
else:
|
|
207
|
+
return
|
|
182
208
|
|
|
183
|
-
|
|
184
|
-
|
|
209
|
+
if self._heartbeat_dead_threshold_s is not None:
|
|
210
|
+
try:
|
|
211
|
+
await self._force_close_connection(connection, "Heartbeat failed")
|
|
212
|
+
except Exception:
|
|
213
|
+
self.logger.exception("Failed to close heartbeat connection")
|
|
185
214
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
215
|
+
async def _send_heartbeats(self, connection: ClientConnection) -> None:
|
|
216
|
+
interval = self._heartbeat_interval_s
|
|
217
|
+
if interval is None:
|
|
218
|
+
return
|
|
219
|
+
while not self._shutdown_event.is_set():
|
|
220
|
+
await self._wait_for_shutdown_or_timeout(interval)
|
|
221
|
+
if self._shutdown_event.is_set():
|
|
222
|
+
return
|
|
223
|
+
if self._pending_heartbeat_ref is not None:
|
|
224
|
+
if self._heartbeat_dead_threshold_s is not None:
|
|
225
|
+
continue
|
|
226
|
+
self.logger.warning(
|
|
227
|
+
"Heartbeat response not received for ref=%s; server may be "
|
|
228
|
+
"unresponsive",
|
|
229
|
+
self._pending_heartbeat_ref,
|
|
191
230
|
)
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
)
|
|
202
|
-
break
|
|
203
|
-
except asyncio.CancelledError:
|
|
204
|
-
self.logger.debug("Heartbeat loop cancelled")
|
|
205
|
-
raise
|
|
231
|
+
ref = self._deps._generate_ref()
|
|
232
|
+
self._pending_heartbeat_ref = ref
|
|
233
|
+
await self._protocol_handler.send_message(
|
|
234
|
+
connection,
|
|
235
|
+
make_message(
|
|
236
|
+
topic=PHOENIX_TOPIC, event=HEARTBEAT_EVENT, payload={}, ref=ref
|
|
237
|
+
),
|
|
238
|
+
)
|
|
239
|
+
self.logger.debug("Sent heartbeat (ref=%s)", ref)
|
|
206
240
|
|
|
207
241
|
async def _supervisor_loop(self) -> None:
|
|
208
242
|
attempt = 0
|
|
@@ -284,6 +318,12 @@ class SupervisorMixin:
|
|
|
284
318
|
# shutdown() began during the handshake; its own cleanup closes
|
|
285
319
|
# this socket.
|
|
286
320
|
return False
|
|
321
|
+
self._heartbeat_deadline = (
|
|
322
|
+
asyncio.get_running_loop().time() + self._heartbeat_dead_threshold_s
|
|
323
|
+
if self._heartbeat_interval_s is not None
|
|
324
|
+
and self._heartbeat_dead_threshold_s is not None
|
|
325
|
+
else None
|
|
326
|
+
)
|
|
287
327
|
self._conn_generation += 1
|
|
288
328
|
self._connected_event.set()
|
|
289
329
|
self._deps._transition_state(ClientState.CONNECTED)
|
|
@@ -299,7 +339,9 @@ class SupervisorMixin:
|
|
|
299
339
|
# a rejoin is still waiting on one, before cleanup runs.
|
|
300
340
|
routing.add_done_callback(self._fail_joins_when_routing_stops)
|
|
301
341
|
if self._heartbeat_interval_s is not None:
|
|
302
|
-
self._heartbeat_task = asyncio.create_task(
|
|
342
|
+
self._heartbeat_task = asyncio.create_task(
|
|
343
|
+
self._heartbeat_loop(connection, self._heartbeat_deadline)
|
|
344
|
+
)
|
|
303
345
|
|
|
304
346
|
try:
|
|
305
347
|
await self._deps._rejoin_topics(generation)
|
|
@@ -432,6 +474,7 @@ class SupervisorMixin:
|
|
|
432
474
|
]
|
|
433
475
|
self.connection = None
|
|
434
476
|
self._heartbeat_task = None
|
|
477
|
+
self._heartbeat_deadline = None
|
|
435
478
|
self._message_routing_task = None
|
|
436
479
|
self._pending_heartbeat_ref = None
|
|
437
480
|
self._connected_event.clear()
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
|
+
import inspect
|
|
4
5
|
import logging
|
|
5
6
|
from asyncio import Queue
|
|
6
7
|
from collections.abc import Awaitable, Callable, Coroutine
|
|
@@ -9,9 +10,13 @@ from typing import Any, Protocol, cast
|
|
|
9
10
|
from websockets import ClientConnection
|
|
10
11
|
from websockets.exceptions import ConnectionClosed
|
|
11
12
|
|
|
12
|
-
from phoenix_channels_python_client.client_types import
|
|
13
|
+
from phoenix_channels_python_client.client_types import (
|
|
14
|
+
ClientState,
|
|
15
|
+
JoinResponseCallback,
|
|
16
|
+
)
|
|
13
17
|
from phoenix_channels_python_client.exceptions import PHXConnectionError, PHXTopicError
|
|
14
18
|
from phoenix_channels_python_client.phx_messages import (
|
|
19
|
+
CLIENT_LIFECYCLE_EVENTS,
|
|
15
20
|
ChannelEvent,
|
|
16
21
|
ChannelMessage,
|
|
17
22
|
PHXEvent,
|
|
@@ -52,6 +57,16 @@ async def _run_handlers(
|
|
|
52
57
|
await event_handler(message.payload)
|
|
53
58
|
|
|
54
59
|
|
|
60
|
+
def _channel_failure(topic: TopicSubscription, event: ChannelEvent) -> Exception:
|
|
61
|
+
match event:
|
|
62
|
+
case PHXEvent.error:
|
|
63
|
+
return PHXConnectionError(f"Channel for topic {topic.name} crashed")
|
|
64
|
+
case PHXEvent.close:
|
|
65
|
+
return PHXTopicError(f"Channel for topic {topic.name} closed by the server")
|
|
66
|
+
case _:
|
|
67
|
+
raise ValueError("Expected a channel lifecycle event")
|
|
68
|
+
|
|
69
|
+
|
|
55
70
|
class TopicRuntimeMixin:
|
|
56
71
|
logger: logging.Logger
|
|
57
72
|
connection: ClientConnection | None
|
|
@@ -68,12 +83,14 @@ class TopicRuntimeMixin:
|
|
|
68
83
|
callback_drain_timeout_s: float
|
|
69
84
|
_on_topic_lost: Callable[[str, Exception], Awaitable[None]] | None
|
|
70
85
|
_lifecycle_tasks: set[asyncio.Task[None]]
|
|
86
|
+
_cleanup_tasks: set[asyncio.Task[None]]
|
|
71
87
|
|
|
72
88
|
@property
|
|
73
89
|
def _runtime_deps(self) -> _TopicRuntimeDeps:
|
|
74
90
|
return cast(_TopicRuntimeDeps, self)
|
|
75
91
|
|
|
76
92
|
def _set_subscription_ready(self, topic_subscription: TopicSubscription) -> None:
|
|
93
|
+
topic_subscription.established = True
|
|
77
94
|
if not topic_subscription.current_join_ready.done():
|
|
78
95
|
topic_subscription.current_join_ready.set_result(None)
|
|
79
96
|
|
|
@@ -139,7 +156,7 @@ class TopicRuntimeMixin:
|
|
|
139
156
|
)
|
|
140
157
|
|
|
141
158
|
if current_state == TopicProcessingState.WAITING_FOR_JOIN:
|
|
142
|
-
|
|
159
|
+
self._handle_join_response_mode(topic, message)
|
|
143
160
|
continue
|
|
144
161
|
|
|
145
162
|
if current_state == TopicProcessingState.PROCESSING_LEAVE:
|
|
@@ -159,20 +176,52 @@ class TopicRuntimeMixin:
|
|
|
159
176
|
# on_topic_lost on this processor, which shutdown does not cancel.
|
|
160
177
|
self._start_topic_loss(topic, exc)
|
|
161
178
|
|
|
162
|
-
|
|
179
|
+
def _handle_join_response_mode(
|
|
163
180
|
self, topic: TopicSubscription, message: ChannelMessage
|
|
164
181
|
) -> None:
|
|
165
182
|
self.logger.debug(
|
|
166
183
|
"Handling join response for topic %s: %s", topic.name, message
|
|
167
184
|
)
|
|
168
185
|
|
|
169
|
-
if message.event
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
186
|
+
if message.event in CLIENT_LIFECYCLE_EVENTS:
|
|
187
|
+
error = _channel_failure(topic, message.event)
|
|
188
|
+
self._set_future_exception(topic.current_join_ready, error)
|
|
189
|
+
if topic.established:
|
|
190
|
+
if message.event == PHXEvent.error:
|
|
191
|
+
self._start_channel_recovery(topic)
|
|
192
|
+
else:
|
|
193
|
+
self._start_topic_loss(topic, error)
|
|
194
|
+
return
|
|
195
|
+
|
|
196
|
+
if (
|
|
197
|
+
message.event != PHXEvent.reply
|
|
198
|
+
or message.ref != topic.join_ref
|
|
199
|
+
or topic.current_join_ready.done()
|
|
200
|
+
or not self._is_registered(topic)
|
|
201
|
+
or not self._is_on_current_connection(topic)
|
|
202
|
+
or topic.leave_requested.is_set()
|
|
203
|
+
or self._shutdown_event.is_set()
|
|
204
|
+
):
|
|
173
205
|
return
|
|
174
206
|
|
|
175
207
|
if message.payload.get("status") == "ok":
|
|
208
|
+
if (
|
|
209
|
+
topic.on_join_response is not None
|
|
210
|
+
and topic.dropped_message_count != topic.join_drop_baseline
|
|
211
|
+
):
|
|
212
|
+
self._set_future_exception(
|
|
213
|
+
topic.current_join_ready,
|
|
214
|
+
PHXConnectionError("Messages lost before join installation"),
|
|
215
|
+
)
|
|
216
|
+
return
|
|
217
|
+
try:
|
|
218
|
+
self._install_join_response(topic, message.payload.get("response"))
|
|
219
|
+
except (Exception, asyncio.CancelledError) as exc:
|
|
220
|
+
error = PHXTopicError("Join response installation failed")
|
|
221
|
+
self.logger.exception(str(error))
|
|
222
|
+
error.__cause__ = exc
|
|
223
|
+
self._set_future_exception(topic.current_join_ready, error)
|
|
224
|
+
return
|
|
176
225
|
self._set_subscription_ready(topic)
|
|
177
226
|
self.logger.info("Successfully subscribed to topic %s", topic.name)
|
|
178
227
|
return
|
|
@@ -190,17 +239,31 @@ class TopicRuntimeMixin:
|
|
|
190
239
|
"Failed to subscribe to topic %s: %s", topic.name, error_message
|
|
191
240
|
)
|
|
192
241
|
|
|
242
|
+
def _install_join_response(
|
|
243
|
+
self, topic: TopicSubscription, response: object
|
|
244
|
+
) -> None:
|
|
245
|
+
if topic.on_join_response is None:
|
|
246
|
+
return
|
|
247
|
+
result = topic.on_join_response(response)
|
|
248
|
+
if (
|
|
249
|
+
inspect.iscoroutine(result)
|
|
250
|
+
and inspect.getcoroutinestate(result) == inspect.CORO_CREATED
|
|
251
|
+
):
|
|
252
|
+
result.close()
|
|
253
|
+
if result is not None:
|
|
254
|
+
raise TypeError("on_join_response must return None")
|
|
255
|
+
|
|
193
256
|
async def _dispatch_normal_message(
|
|
194
257
|
self, topic: TopicSubscription, message: ChannelMessage
|
|
195
258
|
) -> None:
|
|
259
|
+
if message.event == PHXEvent.reply and message.ref == topic.join_ref:
|
|
260
|
+
return
|
|
196
261
|
match message.event:
|
|
197
262
|
case PHXEvent.error:
|
|
198
263
|
self._mark_channel_errored(topic)
|
|
199
264
|
self._start_channel_recovery(topic)
|
|
200
265
|
case PHXEvent.close:
|
|
201
|
-
error =
|
|
202
|
-
f"Channel for topic {topic.name} closed by the server"
|
|
203
|
-
)
|
|
266
|
+
error = _channel_failure(topic, PHXEvent.close)
|
|
204
267
|
# Synchronous, so a message already queued behind the close
|
|
205
268
|
# is not delivered.
|
|
206
269
|
self._fail_current_join(topic, error)
|
|
@@ -209,15 +272,15 @@ class TopicRuntimeMixin:
|
|
|
209
272
|
await self._handle_normal_message_mode(topic, message)
|
|
210
273
|
|
|
211
274
|
def _mark_channel_errored(self, topic: TopicSubscription) -> None:
|
|
212
|
-
#
|
|
213
|
-
|
|
214
|
-
self._fail_current_join(
|
|
215
|
-
topic, PHXTopicError(f"Channel for topic {topic.name} crashed")
|
|
216
|
-
)
|
|
275
|
+
# Readiness is lost before a queued event can be delivered.
|
|
276
|
+
self._fail_current_join(topic, _channel_failure(topic, PHXEvent.error))
|
|
217
277
|
|
|
218
278
|
def _fail_current_join(self, topic: TopicSubscription, error: Exception) -> None:
|
|
219
279
|
# A new future: the successful join is already done, so failing it in
|
|
220
280
|
# place would leave the topic looking joined.
|
|
281
|
+
if not topic.current_join_ready.done():
|
|
282
|
+
self._set_future_exception(topic.current_join_ready, error)
|
|
283
|
+
return
|
|
221
284
|
topic.current_join_ready = asyncio.get_running_loop().create_future()
|
|
222
285
|
self._set_future_exception(topic.current_join_ready, error)
|
|
223
286
|
|
|
@@ -253,40 +316,67 @@ class TopicRuntimeMixin:
|
|
|
253
316
|
if not task.cancelled() and (error := task.exception()):
|
|
254
317
|
self.logger.error("Channel lifecycle task failed", exc_info=error)
|
|
255
318
|
|
|
256
|
-
def _start_channel_recovery(
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
319
|
+
def _start_channel_recovery(
|
|
320
|
+
self, topic: TopicSubscription, *, generation: int | None = None
|
|
321
|
+
) -> None:
|
|
322
|
+
# A socket rejoin supplies its new generation for an immediate attempt.
|
|
323
|
+
recovery_generation = (
|
|
324
|
+
self._conn_generation if generation is None else generation
|
|
325
|
+
)
|
|
326
|
+
if (
|
|
327
|
+
self._is_recovering(topic)
|
|
328
|
+
or not self._can_recover(topic, recovery_generation)
|
|
329
|
+
or (generation is None and topic.conn_generation != recovery_generation)
|
|
330
|
+
):
|
|
260
331
|
return
|
|
261
332
|
self.logger.info("Recovering channel for topic %s", topic.name)
|
|
262
|
-
topic.recovery_task = self._track_lifecycle_task(
|
|
333
|
+
topic.recovery_task = self._track_lifecycle_task(
|
|
334
|
+
self._recover_channel(
|
|
335
|
+
topic,
|
|
336
|
+
generation=recovery_generation,
|
|
337
|
+
immediate=generation is not None,
|
|
338
|
+
)
|
|
339
|
+
)
|
|
263
340
|
|
|
264
341
|
def _start_topic_loss(self, topic: TopicSubscription, error: Exception) -> None:
|
|
342
|
+
if not topic.established:
|
|
343
|
+
self._set_future_exception(topic.current_join_ready, error)
|
|
344
|
+
return
|
|
265
345
|
# A task of its own, so a slow on_topic_lost holds up nothing else; the
|
|
266
346
|
# loss unregisters the topic, which also cancels its recovery.
|
|
267
347
|
self._track_lifecycle_task(self._lose_topic(topic, error))
|
|
268
348
|
|
|
269
|
-
def _can_recover(self, topic: TopicSubscription) -> bool:
|
|
349
|
+
def _can_recover(self, topic: TopicSubscription, generation: int) -> bool:
|
|
270
350
|
return (
|
|
271
351
|
not self._shutdown_event.is_set()
|
|
272
352
|
and self._should_rejoin(topic)
|
|
273
|
-
and self.
|
|
353
|
+
and self._is_connected()
|
|
354
|
+
and generation == self._conn_generation
|
|
274
355
|
)
|
|
275
356
|
|
|
276
|
-
async def _recover_channel(
|
|
357
|
+
async def _recover_channel(
|
|
358
|
+
self,
|
|
359
|
+
topic: TopicSubscription,
|
|
360
|
+
*,
|
|
361
|
+
generation: int,
|
|
362
|
+
immediate: bool = False,
|
|
363
|
+
) -> None:
|
|
277
364
|
attempt = 0
|
|
278
365
|
# Socket cleanup fails the pending join and cancels this task in one
|
|
279
366
|
# tick; on Python 3.11 the join's failure can arrive instead of the
|
|
280
367
|
# cancel, so both checks must end the loop.
|
|
281
|
-
while self._can_recover(topic):
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
368
|
+
while self._can_recover(topic, generation):
|
|
369
|
+
if immediate:
|
|
370
|
+
immediate = False
|
|
371
|
+
else:
|
|
372
|
+
await self._runtime_deps._wait_for_shutdown_or_timeout(
|
|
373
|
+
self._runtime_deps._channel_rejoin_delay(attempt)
|
|
374
|
+
)
|
|
375
|
+
attempt += 1
|
|
376
|
+
if not self._can_recover(topic, generation):
|
|
286
377
|
return
|
|
287
|
-
attempt += 1
|
|
288
378
|
try:
|
|
289
|
-
await self._rejoin_topic(topic,
|
|
379
|
+
await self._rejoin_topic(topic, generation)
|
|
290
380
|
except PHXTopicError as exc:
|
|
291
381
|
self._start_topic_loss(topic, self._rejoin_rejected(topic, exc))
|
|
292
382
|
return
|
|
@@ -312,7 +402,9 @@ class TopicRuntimeMixin:
|
|
|
312
402
|
def _rejoin_rejected(
|
|
313
403
|
self, topic: TopicSubscription, error: PHXTopicError
|
|
314
404
|
) -> PHXTopicError:
|
|
315
|
-
|
|
405
|
+
failure = PHXTopicError(f"Failed to rejoin topic {topic.name}: {error}")
|
|
406
|
+
failure.__cause__ = error
|
|
407
|
+
return failure
|
|
316
408
|
|
|
317
409
|
async def _lose_topic(self, topic: TopicSubscription, error: Exception) -> None:
|
|
318
410
|
if await self._unregister_topic(topic.name, error=error, only=topic) is None:
|
|
@@ -371,7 +463,7 @@ class TopicRuntimeMixin:
|
|
|
371
463
|
"Processing message during leave for topic %s: %s", topic.name, message
|
|
372
464
|
)
|
|
373
465
|
|
|
374
|
-
if message.event != PHXEvent.reply:
|
|
466
|
+
if message.event != PHXEvent.reply or message.ref != topic.leave_ref:
|
|
375
467
|
self.logger.debug(
|
|
376
468
|
"Ignoring queued message for leaving topic %s", topic.name
|
|
377
469
|
)
|
|
@@ -443,12 +535,29 @@ class TopicRuntimeMixin:
|
|
|
443
535
|
)
|
|
444
536
|
self._complete_pending_futures(topic_subscription, unregister_error)
|
|
445
537
|
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
538
|
+
cleanup = asyncio.create_task(
|
|
539
|
+
self._cleanup_subscription(topic_subscription, asyncio.current_task())
|
|
540
|
+
)
|
|
541
|
+
self._cleanup_tasks.add(cleanup)
|
|
542
|
+
cleanup.add_done_callback(self._finish_cleanup_task)
|
|
543
|
+
await asyncio.shield(cleanup)
|
|
449
544
|
self.logger.info("Unregistered topic %s", topic_name)
|
|
450
545
|
return topic_subscription
|
|
451
546
|
|
|
547
|
+
async def _cleanup_subscription(
|
|
548
|
+
self, topic: TopicSubscription, initiator: asyncio.Task[Any] | None
|
|
549
|
+
) -> None:
|
|
550
|
+
# A recovery removing itself unwinds through its failed join, not a cycle.
|
|
551
|
+
if topic.recovery_task is not initiator:
|
|
552
|
+
await _cancel_unless_current(topic.recovery_task)
|
|
553
|
+
if topic.process_topic_messages_task is not initiator:
|
|
554
|
+
await self._stop_topic_task(topic)
|
|
555
|
+
|
|
556
|
+
def _finish_cleanup_task(self, task: asyncio.Task[None]) -> None:
|
|
557
|
+
self._cleanup_tasks.discard(task)
|
|
558
|
+
if not task.cancelled() and (error := task.exception()):
|
|
559
|
+
self.logger.error("Topic cleanup failed", exc_info=error)
|
|
560
|
+
|
|
452
561
|
def get_current_subscriptions(self) -> dict[str, TopicSubscription]:
|
|
453
562
|
return self._topic_subscriptions.copy()
|
|
454
563
|
|
|
@@ -499,17 +608,27 @@ class TopicRuntimeMixin:
|
|
|
499
608
|
ref=topic_subscription.join_ref,
|
|
500
609
|
join_ref=topic_subscription.join_ref,
|
|
501
610
|
)
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
611
|
+
ready = topic_subscription.current_join_ready
|
|
612
|
+
try:
|
|
613
|
+
await self._send(connection, join_message)
|
|
614
|
+
except PHXConnectionError as error:
|
|
615
|
+
# A reply may already have settled this attempt during send flow control.
|
|
616
|
+
self._set_future_exception(ready, error)
|
|
617
|
+
await asyncio.wait_for(ready, timeout=self.join_timeout_s)
|
|
506
618
|
|
|
507
619
|
async def subscribe_to_topic(
|
|
508
620
|
self,
|
|
509
621
|
topic: str,
|
|
510
622
|
async_callback: Callable[[ChannelMessage], Awaitable[None]] | None = None,
|
|
623
|
+
*,
|
|
624
|
+
on_join_response: JoinResponseCallback | None = None,
|
|
625
|
+
blocks_reconnect: bool = True,
|
|
511
626
|
) -> None:
|
|
512
627
|
self._ensure_can_send("subscribe")
|
|
628
|
+
if inspect.iscoroutinefunction(on_join_response) or inspect.iscoroutinefunction(
|
|
629
|
+
on_join_response.__call__ if callable(on_join_response) else None
|
|
630
|
+
):
|
|
631
|
+
raise PHXTopicError("on_join_response must be synchronous")
|
|
513
632
|
|
|
514
633
|
topic_queue: Queue[ChannelMessage] = Queue(maxsize=self.max_topic_queue_size)
|
|
515
634
|
join_ref = self._generate_ref()
|
|
@@ -521,9 +640,12 @@ class TopicRuntimeMixin:
|
|
|
521
640
|
join_ref=join_ref,
|
|
522
641
|
process_topic_messages_task=None,
|
|
523
642
|
conn_generation=self._conn_generation,
|
|
643
|
+
on_join_response=on_join_response,
|
|
644
|
+
blocks_reconnect=blocks_reconnect,
|
|
524
645
|
)
|
|
525
646
|
|
|
526
647
|
async with self._topics_lock:
|
|
648
|
+
self._ensure_can_send("subscribe")
|
|
527
649
|
if topic in self._topic_subscriptions:
|
|
528
650
|
raise PHXTopicError(f"Topic {topic} already subscribed")
|
|
529
651
|
self._topic_subscriptions[topic] = topic_subscription
|
|
@@ -538,10 +660,11 @@ class TopicRuntimeMixin:
|
|
|
538
660
|
await self._unregister_topic(
|
|
539
661
|
topic,
|
|
540
662
|
error=PHXTopicError(f"Timed out waiting to subscribe to {topic}"),
|
|
663
|
+
only=topic_subscription,
|
|
541
664
|
)
|
|
542
665
|
raise PHXTopicError(f"Timed out waiting to subscribe to {topic}") from exc
|
|
543
|
-
except Exception:
|
|
544
|
-
await self._unregister_topic(topic)
|
|
666
|
+
except (Exception, asyncio.CancelledError):
|
|
667
|
+
await self._unregister_topic(topic, only=topic_subscription)
|
|
545
668
|
raise
|
|
546
669
|
|
|
547
670
|
async def unsubscribe_from_topic(
|
|
@@ -556,15 +679,20 @@ class TopicRuntimeMixin:
|
|
|
556
679
|
if not _allow_disconnected:
|
|
557
680
|
self._ensure_can_send("unsubscribe")
|
|
558
681
|
connection = self.connection if self._state == ClientState.CONNECTED else None
|
|
559
|
-
#
|
|
560
|
-
|
|
561
|
-
|
|
682
|
+
# Pending/recovering processors cannot dispatch a leave acknowledgement.
|
|
683
|
+
complete_locally = (
|
|
684
|
+
connection is None
|
|
685
|
+
or not self._is_current_join_ready(topic_subscription)
|
|
686
|
+
or self._is_recovering(topic_subscription)
|
|
687
|
+
or asyncio.current_task() is topic_subscription.current_callback_task
|
|
688
|
+
)
|
|
562
689
|
|
|
563
690
|
topic_subscription.leave_requested.set()
|
|
564
691
|
|
|
565
692
|
try:
|
|
566
693
|
if connection is not None:
|
|
567
694
|
leave_ref = self._generate_ref()
|
|
695
|
+
topic_subscription.leave_ref = leave_ref
|
|
568
696
|
topic_leave_message = make_message(
|
|
569
697
|
topic=topic,
|
|
570
698
|
event=PHXEvent.leave,
|
|
@@ -585,7 +713,7 @@ class TopicRuntimeMixin:
|
|
|
585
713
|
f"Timed out waiting to unsubscribe from {topic}"
|
|
586
714
|
) from exc
|
|
587
715
|
finally:
|
|
588
|
-
await self._unregister_topic(topic)
|
|
716
|
+
await self._unregister_topic(topic, only=topic_subscription)
|
|
589
717
|
|
|
590
718
|
def add_event_handler(
|
|
591
719
|
self,
|
|
@@ -688,11 +816,17 @@ class TopicRuntimeMixin:
|
|
|
688
816
|
subscriptions = list(self._topic_subscriptions.values())
|
|
689
817
|
|
|
690
818
|
for topic_subscription in subscriptions:
|
|
819
|
+
if not topic_subscription.blocks_reconnect:
|
|
820
|
+
continue
|
|
691
821
|
try:
|
|
692
822
|
await self._rejoin_topic(topic_subscription, generation)
|
|
693
823
|
except Exception as exc: # noqa: BLE001 # handled per topic
|
|
694
824
|
await self._handle_rejoin_failure(topic_subscription, exc)
|
|
695
825
|
|
|
826
|
+
for topic_subscription in subscriptions:
|
|
827
|
+
if not topic_subscription.blocks_reconnect:
|
|
828
|
+
self._start_channel_recovery(topic_subscription, generation=generation)
|
|
829
|
+
|
|
696
830
|
async def _rejoin_topic(
|
|
697
831
|
self, topic_subscription: TopicSubscription, generation: int
|
|
698
832
|
) -> None:
|
|
@@ -717,6 +851,7 @@ class TopicRuntimeMixin:
|
|
|
717
851
|
def _should_rejoin(self, topic_subscription: TopicSubscription) -> bool:
|
|
718
852
|
return (
|
|
719
853
|
self._is_registered(topic_subscription)
|
|
854
|
+
and topic_subscription.established
|
|
720
855
|
and not topic_subscription.leave_requested.is_set()
|
|
721
856
|
)
|
|
722
857
|
|
|
@@ -733,6 +868,7 @@ class TopicRuntimeMixin:
|
|
|
733
868
|
asyncio.get_running_loop().create_future()
|
|
734
869
|
)
|
|
735
870
|
self._drain_topic_queue(topic_subscription)
|
|
871
|
+
topic_subscription.join_drop_baseline = topic_subscription.dropped_message_count
|
|
736
872
|
topic_subscription.process_topic_messages_task = asyncio.create_task(
|
|
737
873
|
self._process_topic_messages(topic_subscription.name)
|
|
738
874
|
)
|
|
@@ -7,6 +7,7 @@ from dataclasses import dataclass, field
|
|
|
7
7
|
from enum import StrEnum
|
|
8
8
|
from typing import Any
|
|
9
9
|
|
|
10
|
+
from phoenix_channels_python_client.client_types import JoinResponseCallback
|
|
10
11
|
from phoenix_channels_python_client.phx_messages import (
|
|
11
12
|
CLIENT_LIFECYCLE_EVENTS,
|
|
12
13
|
ChannelEvent,
|
|
@@ -36,6 +37,11 @@ class TopicSubscription:
|
|
|
36
37
|
event_handlers: dict[ChannelEvent, Callable[[dict[str, Any]], Awaitable[None]]] = (
|
|
37
38
|
field(default_factory=dict)
|
|
38
39
|
)
|
|
40
|
+
on_join_response: JoinResponseCallback | None = None
|
|
41
|
+
blocks_reconnect: bool = True
|
|
42
|
+
established: bool = False
|
|
43
|
+
join_drop_baseline: int = 0
|
|
44
|
+
leave_ref: str | None = None
|
|
39
45
|
conn_generation: int = 0
|
|
40
46
|
dropped_message_count: int = 0
|
|
41
47
|
current_callback_task: Task[None] | None = None
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: phoenix-channels-python-client
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.2
|
|
4
4
|
Summary: A Python client library for connecting to Phoenix Channels
|
|
5
5
|
Author: Phoenix Channels Python Client
|
|
6
6
|
License-Expression: MIT
|
|
@@ -19,6 +19,7 @@ Requires-Dist: websockets>=14.2
|
|
|
19
19
|
Provides-Extra: dev
|
|
20
20
|
Requires-Dist: pytest; extra == "dev"
|
|
21
21
|
Requires-Dist: pytest-asyncio>=1.4; extra == "dev"
|
|
22
|
+
Requires-Dist: looptime<0.10,>=0.7; extra == "dev"
|
|
22
23
|
Requires-Dist: pytest-cov; extra == "dev"
|
|
23
24
|
Requires-Dist: pre-commit>=3.0.0; extra == "dev"
|
|
24
25
|
Requires-Dist: commitizen>=3.13.0; extra == "dev"
|
|
@@ -27,6 +28,7 @@ Requires-Dist: ruff; extra == "dev"
|
|
|
27
28
|
Provides-Extra: test
|
|
28
29
|
Requires-Dist: pytest; extra == "test"
|
|
29
30
|
Requires-Dist: pytest-asyncio>=1.4; extra == "test"
|
|
31
|
+
Requires-Dist: looptime<0.10,>=0.7; extra == "test"
|
|
30
32
|
Dynamic: license-file
|
|
31
33
|
|
|
32
34
|
# Phoenix Channels Python Client
|
|
@@ -295,18 +297,20 @@ Everything after `api_key` is keyword-only:
|
|
|
295
297
|
| `protocol_version` | `V2` | Phoenix Channels protocol version |
|
|
296
298
|
| `auto_reconnect` | `True` | Reconnect and rejoin topics after a disconnect |
|
|
297
299
|
| `reconnect_policy` | `ReconnectPolicy()` | Backoff and close-code handling (see below) |
|
|
298
|
-
| `heartbeat_interval_s` | `30.0` | Heartbeat period; `None` disables heartbeats |
|
|
300
|
+
| `heartbeat_interval_s` | `30.0` | Heartbeat period; `None` disables heartbeats and timeout enforcement |
|
|
301
|
+
| `heartbeat_dead_threshold_s` | `None` | Optional finite positive acknowledgement-silence limit, greater than the enabled finite interval |
|
|
299
302
|
| `join_timeout_s` | `10.0` | Wait for a join reply |
|
|
300
303
|
| `leave_timeout_s` | `5.0` | Wait for a leave reply |
|
|
301
304
|
| `max_topic_queue_size` | `1000` | Per-topic buffer; the oldest message is dropped when full |
|
|
302
305
|
| `callback_drain_timeout_s` | `2.0` | How long the message being handled (its message handler, then its event handler) may finish before a rejoin cancels it; queued messages are dropped |
|
|
303
|
-
| `on_reconnect` | `None` | `async () -> None`, called after
|
|
306
|
+
| `on_reconnect` | `None` | `async () -> None`, called after required first-attempt reconciliation |
|
|
304
307
|
| `on_disconnect` | `None` | `async (error: Exception \| None) -> None`; `None` on a clean close |
|
|
305
308
|
| `on_heartbeat_ack` | `None` | Synchronous `() -> None`; runs on the message path, so keep it fast |
|
|
306
309
|
| `on_topic_lost` | `None` | `async (topic: str, error: Exception) -> None`, called when the client drops a topic you didn't unsubscribe |
|
|
307
310
|
| `additional_headers` | `None` | Extra handshake headers sent on every (re)connect |
|
|
308
311
|
|
|
309
|
-
Exceptions raised in callbacks are logged, not raised.
|
|
312
|
+
Exceptions raised in ordinary message and lifecycle callbacks are logged, not raised.
|
|
313
|
+
Join-response installation failures instead fail the join (see below).
|
|
310
314
|
|
|
311
315
|
## Connection Lifecycle and Errors
|
|
312
316
|
|
|
@@ -346,7 +350,21 @@ The client drops the topic and calls `on_topic_lost(topic, error)` once when the
|
|
|
346
350
|
|
|
347
351
|
### Heartbeats
|
|
348
352
|
|
|
349
|
-
The client sends a `heartbeat` on the `phoenix` topic every `heartbeat_interval_s`.
|
|
353
|
+
The client sends a `heartbeat` on the `phoenix` topic every `heartbeat_interval_s`. By default, missed replies log warnings and sending continues with a new reference each interval.
|
|
354
|
+
|
|
355
|
+
Set `heartbeat_dead_threshold_s` to enable closure after acknowledgement silence:
|
|
356
|
+
|
|
357
|
+
```python
|
|
358
|
+
client = PHXChannelsClient(
|
|
359
|
+
websocket_url, api_key,
|
|
360
|
+
heartbeat_interval_s=30.0,
|
|
361
|
+
heartbeat_dead_threshold_s=60.0,
|
|
362
|
+
)
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
The deadline starts when each socket is adopted, including during rejoin and reconnect callbacks. Only a matching pending reply received strictly before expiry renews it, before `on_heartbeat_ack` runs. Enabled enforcement keeps one outstanding heartbeat, skipping sends until it is acknowledged or expires. WebSocket Pong and unrelated messages do not renew it. Rejoin completion grants no additional grace.
|
|
366
|
+
|
|
367
|
+
Expiry or heartbeat send failure force-closes that socket; the supervisor handles cleanup and reconnect/rejoin according to `auto_reconnect` and the existing policy. The deadline bounds close initiation; the transport has its own close-handshake timeout. `heartbeat_interval_s=None` disables heartbeat activity even with a threshold, but a supplied threshold must still be finite and positive. Long thresholds do not prevent the server from applying its own inactivity timeout.
|
|
350
368
|
|
|
351
369
|
## Logging
|
|
352
370
|
|
|
@@ -402,3 +420,69 @@ headers, frame bodies, user/topic identities, and untrusted server error details
|
|
|
402
420
|
Logs retain static lifecycle descriptions, native connection states,
|
|
403
421
|
and exception types. Application data and caller-visible errors are not changed;
|
|
404
422
|
applications remain responsible for logs outside this connection-owned boundary.
|
|
423
|
+
|
|
424
|
+
### Ordered join responses
|
|
425
|
+
|
|
426
|
+
Use the optional keyword-only `on_join_response` hook to install a snapshot from
|
|
427
|
+
initial joins, socket rejoins and same-socket channel recovery:
|
|
428
|
+
|
|
429
|
+
```python
|
|
430
|
+
state = None
|
|
431
|
+
|
|
432
|
+
def install_snapshot(response):
|
|
433
|
+
global state
|
|
434
|
+
state = validate_snapshot(response)
|
|
435
|
+
|
|
436
|
+
await client.subscribe_to_topic(
|
|
437
|
+
"room:123", on_message, on_join_response=install_snapshot
|
|
438
|
+
)
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
`JoinResponseCallback` is exported from the package. The hook receives the decoded
|
|
442
|
+
successful `payload.response`; a missing response is `None`. The transport adds no
|
|
443
|
+
application schema or empty snapshot. Installation runs synchronously before
|
|
444
|
+
`is_topic_joined()` becomes true, subscribe completes, or later deltas deliver.
|
|
445
|
+
Subscribe returns `None`. Success admits the subscription; a later disconnect or
|
|
446
|
+
channel failure can already have changed its current readiness when the caller
|
|
447
|
+
resumes.
|
|
448
|
+
|
|
449
|
+
Hooks must be short, nonblocking and return `None`. Do not await, perform I/O,
|
|
450
|
+
wait on locks, defer installation, or change task/client lifecycle inside them.
|
|
451
|
+
Async callables, awaitable results and other non-`None` results fail admission.
|
|
452
|
+
The join timeout bounds reply waiting and cannot preempt synchronous code. Hook
|
|
453
|
+
exceptions (including directly raised `CancelledError`) fail with `PHXTopicError`
|
|
454
|
+
and preserve their cause; arbitrary prior hook effects are not rolled back.
|
|
455
|
+
Initial failure belongs to the caller. An established subscription whose installer
|
|
456
|
+
fails is removed and reported once through `on_topic_lost`.
|
|
457
|
+
|
|
458
|
+
Initial cancellation, timeout and leave remove the exact subscription. Physical
|
|
459
|
+
cleanup remains owned if its waiter is canceled again, and shutdown awaits it.
|
|
460
|
+
Never-established subscriptions are not adopted by automatic recovery. Recorded
|
|
461
|
+
queue loss before a hook-enabled installation fails the attempt transiently;
|
|
462
|
+
steady-state queues still drop their oldest message at capacity. There is no
|
|
463
|
+
replay guarantee. A fresh client must install a fresh snapshot after process loss.
|
|
464
|
+
|
|
465
|
+
Join replies match request refs on both protocols. V2 also filters stale channel
|
|
466
|
+
generations by `join_ref`. V1 cannot reliably fence unsolicited events/lifecycle
|
|
467
|
+
frames from older channels; it does not provide V2 event-generation isolation.
|
|
468
|
+
|
|
469
|
+
### Optional reconnect participation
|
|
470
|
+
|
|
471
|
+
`subscribe_to_topic(topic, async_callback=None, *, on_join_response=None,
|
|
472
|
+
blocks_reconnect=True) -> None` preserves required recovery by default. Required
|
|
473
|
+
topics reconcile their first socket-rejoin attempt sequentially before
|
|
474
|
+
`on_reconnect`; transient failures continue through existing recovery/backoff.
|
|
475
|
+
The barrier does not wait for eventual success of every required topic.
|
|
476
|
+
|
|
477
|
+
Set `blocks_reconnect=False` for optional subscriptions. After required first
|
|
478
|
+
attempts, their existing per-topic recovery tasks perform an immediate join and
|
|
479
|
+
retry transient failures with the existing backoff. Required event delivery and
|
|
480
|
+
`on_reconnect` do not wait for optional replies, old callback drains or retries.
|
|
481
|
+
This option cannot isolate synchronous code that blocks the event loop. Explicit
|
|
482
|
+
initial subscribe always waits for its own join response and installation.
|
|
483
|
+
|
|
484
|
+
`on_reconnect` conveys no optional readiness or registration-absence guarantee.
|
|
485
|
+
Check `is_topic_joined()` for current readiness and use `on_topic_lost` to replace
|
|
486
|
+
permanently rejected optional subscriptions; do not blindly resubscribe them
|
|
487
|
+
from `on_reconnect`. Leave, shutdown and another socket disconnect cancel/await
|
|
488
|
+
the owned recovery; obsolete generations cannot install or revive a replacement.
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
phoenix_channels_python_client/__init__.py,sha256=
|
|
1
|
+
phoenix_channels_python_client/__init__.py,sha256=U7e0kRYKad0m3hB-dGHHw72cAp2yFmcD1dEy7y9MUsg,944
|
|
2
2
|
phoenix_channels_python_client/authentication.py,sha256=r_UtblJDKr0ynUyxf_WDoMdErDcqvKD8y_iip-PLR-0,1353
|
|
3
|
-
phoenix_channels_python_client/client.py,sha256=
|
|
3
|
+
phoenix_channels_python_client/client.py,sha256=TM0glWR-k9nscbeXZhSbpwjP1f_hwvmBf6RFKGKWP0Q,12413
|
|
4
4
|
phoenix_channels_python_client/client_state_machine.py,sha256=pjIHK55C4MZII_xnEOZXfiJ6drNrLcC0EPtWXRRGUuY,1090
|
|
5
|
-
phoenix_channels_python_client/client_types.py,sha256=
|
|
5
|
+
phoenix_channels_python_client/client_types.py,sha256=VFfOcV3gtse6_FXbZ8Rv3VgNH0UWw17t-AxSjK8zSA0,2725
|
|
6
6
|
phoenix_channels_python_client/diagnostics.py,sha256=vaf3pDIZvRTNh1QZCVgPKPAlQaonl9of1JQ5Ow7Cvf8,3987
|
|
7
7
|
phoenix_channels_python_client/exceptions.py,sha256=_fS9Zfn751WmykTnDCcJjGpVCRrUqgqPUpTI3B-xzF0,217
|
|
8
8
|
phoenix_channels_python_client/phx_messages.py,sha256=F_uW79oNaJm6Mpm9wtSrLIJL0KVPQMRA7E5l0-S6j0Q,1614
|
|
9
9
|
phoenix_channels_python_client/protocol_handler.py,sha256=J5kHCcFVltwQH-4PJZxsQA0NTQE7jqjvZ8jmP5tWN54,8967
|
|
10
10
|
phoenix_channels_python_client/reconnect_controller.py,sha256=N7LUIbSzptGOqIwSlYROLm1nZklL_i53i9nID0ytJ_w,13120
|
|
11
11
|
phoenix_channels_python_client/shutdown_signals.py,sha256=qbcfJnp7pBcu07WolZyJyqNarFaUb0f7GaasqZGvi9E,4067
|
|
12
|
-
phoenix_channels_python_client/supervisor.py,sha256=
|
|
13
|
-
phoenix_channels_python_client/topic_runtime.py,sha256=
|
|
14
|
-
phoenix_channels_python_client/topic_subscription.py,sha256=
|
|
12
|
+
phoenix_channels_python_client/supervisor.py,sha256=Y486DE6At_C0BbZxQn3Y37_PMhpry49ygXwrOnZGoGw,22020
|
|
13
|
+
phoenix_channels_python_client/topic_runtime.py,sha256=zSccUxUZ1UVcawHR--OTNaXCR64Wn0WQhXuhyNnoizo,36414
|
|
14
|
+
phoenix_channels_python_client/topic_subscription.py,sha256=CMlBbXB6fLiFe3XQYmrrvrKVQ6T4YVmSSieL-oYFLY8,2783
|
|
15
15
|
phoenix_channels_python_client/utils.py,sha256=YFo2N2h9UJ9vcSYUCGfbElsEVgyc3vM2103t8bZdEd8,2204
|
|
16
|
-
phoenix_channels_python_client-0.4.
|
|
17
|
-
phoenix_channels_python_client-0.4.
|
|
18
|
-
phoenix_channels_python_client-0.4.
|
|
19
|
-
phoenix_channels_python_client-0.4.
|
|
20
|
-
phoenix_channels_python_client-0.4.
|
|
16
|
+
phoenix_channels_python_client-0.4.2.dist-info/licenses/LICENSE,sha256=zwqkIClV_fMWOC0Auvd0DYqZMLL0-hIqeKd6tygE39g,1064
|
|
17
|
+
phoenix_channels_python_client-0.4.2.dist-info/METADATA,sha256=e7-FH4z4uC9RybopdTPghXaRvmNh7jcXyb_NufC4wjs,22444
|
|
18
|
+
phoenix_channels_python_client-0.4.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
19
|
+
phoenix_channels_python_client-0.4.2.dist-info/top_level.txt,sha256=ZYXMGCOeev4cyNU9XvNGHKt1wOgVkFHaS9TlwDa4eDU,31
|
|
20
|
+
phoenix_channels_python_client-0.4.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|