pondsocket-client 0.0.6__tar.gz → 0.0.7__tar.gz

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.
Files changed (20) hide show
  1. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/PKG-INFO +5 -4
  2. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/README.md +3 -2
  3. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/pyproject.toml +1 -1
  4. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/src/pondsocket_client/__init__.py +2 -0
  5. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/src/pondsocket_client/_base.py +96 -19
  6. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/src/pondsocket_client/_channel.py +143 -71
  7. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/src/pondsocket_client/_websocket.py +9 -5
  8. pondsocket_client-0.0.7/src/pondsocket_client/types.py +58 -0
  9. pondsocket_client-0.0.7/tests/test_pondsocket_client_base.py +354 -0
  10. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/tests/test_pondsocket_client_channel.py +300 -3
  11. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/tests/test_pondsocket_client_notfound_adversarial.py +18 -3
  12. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/tests/test_pondsocket_client_reqresp_adversarial.py +3 -1
  13. pondsocket_client-0.0.6/src/pondsocket_client/types.py +0 -35
  14. pondsocket_client-0.0.6/tests/test_pondsocket_client_base.py +0 -134
  15. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/.gitignore +0 -0
  16. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/src/pondsocket_client/client.py +0 -0
  17. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/src/pondsocket_client/py.typed +0 -0
  18. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/src/pondsocket_client/typed.py +0 -0
  19. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/tests/test_pondsocket_client_integration.py +0 -0
  20. {pondsocket_client-0.0.6 → pondsocket_client-0.0.7}/tests/test_pondsocket_client_smoke.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: pondsocket-client
3
- Version: 0.0.6
3
+ Version: 0.0.7
4
4
  Summary: PondSocket Python client — connect to a PondSocket server from Python.
5
5
  Author: eleven-am
6
6
  License: GPL-3.0-or-later
@@ -67,7 +67,7 @@ PondClient(WebSocketClient) (concrete)
67
67
  └── appends query-string params
68
68
  ```
69
69
 
70
- The `Channel` class holds the per-channel state machine (IDLE → JOINING → JOINED → STALLED → CLOSED/DECLINED), a bounded outbound queue (drops oldest on overflow), and a `send_for_response` that correlates inbound replies by `requestId`.
70
+ The `Channel` class holds the per-channel state machine (IDLE → JOINING → JOINED → STALLED → CLOSED/DECLINED), a bounded FIFO outbound queue (raises `ChannelQueueFullError` on overflow), and a `send_for_response` that correlates inbound replies by `requestId`.
71
71
 
72
72
  ## Connection states
73
73
 
@@ -102,7 +102,7 @@ Compared to the Go client (`go/pondsocket-client/`):
102
102
  | Reconnect backoff | linear despite comment | true exponential, capped |
103
103
  | `UNAUTHORIZED` handling | not implemented | → `DECLINED` state |
104
104
  | Connection state | bool (no CONNECTING) | three-state enum |
105
- | Outbound queue | unbounded | bounded, drops oldest |
105
+ | Outbound queue | unbounded | bounded FIFO, raises on overflow |
106
106
  | Join while disconnected | dropped silently | deferred until CONNECTED |
107
107
 
108
108
  The Python client follows the JS client design where the two diverge.
@@ -115,6 +115,7 @@ from pondsocket_client import (
115
115
  Channel,
116
116
  ConnectionState,
117
117
  ClientOptions,
118
+ ChannelQueueFullError,
118
119
  ResponseTimeoutError,
119
120
  )
120
121
  ```
@@ -56,7 +56,7 @@ PondClient(WebSocketClient) (concrete)
56
56
  └── appends query-string params
57
57
  ```
58
58
 
59
- The `Channel` class holds the per-channel state machine (IDLE → JOINING → JOINED → STALLED → CLOSED/DECLINED), a bounded outbound queue (drops oldest on overflow), and a `send_for_response` that correlates inbound replies by `requestId`.
59
+ The `Channel` class holds the per-channel state machine (IDLE → JOINING → JOINED → STALLED → CLOSED/DECLINED), a bounded FIFO outbound queue (raises `ChannelQueueFullError` on overflow), and a `send_for_response` that correlates inbound replies by `requestId`.
60
60
 
61
61
  ## Connection states
62
62
 
@@ -91,7 +91,7 @@ Compared to the Go client (`go/pondsocket-client/`):
91
91
  | Reconnect backoff | linear despite comment | true exponential, capped |
92
92
  | `UNAUTHORIZED` handling | not implemented | → `DECLINED` state |
93
93
  | Connection state | bool (no CONNECTING) | three-state enum |
94
- | Outbound queue | unbounded | bounded, drops oldest |
94
+ | Outbound queue | unbounded | bounded FIFO, raises on overflow |
95
95
  | Join while disconnected | dropped silently | deferred until CONNECTED |
96
96
 
97
97
  The Python client follows the JS client design where the two diverge.
@@ -104,6 +104,7 @@ from pondsocket_client import (
104
104
  Channel,
105
105
  ConnectionState,
106
106
  ClientOptions,
107
+ ChannelQueueFullError,
107
108
  ResponseTimeoutError,
108
109
  )
109
110
  ```
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pondsocket-client"
3
- version = "0.0.6"
3
+ version = "0.0.7"
4
4
  description = "PondSocket Python client — connect to a PondSocket server from Python."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -5,6 +5,7 @@ from importlib.metadata import PackageNotFoundError, version
5
5
  from ._base import BaseClient, ConnectionStateHandler, ErrorHandler
6
6
  from ._channel import (
7
7
  Channel,
8
+ ChannelQueueFullError,
8
9
  ChannelStateHandler,
9
10
  MessageHandler,
10
11
  PresenceHandler,
@@ -41,6 +42,7 @@ __all__ = [
41
42
  "DEFAULT_RESPONSE_TIMEOUT",
42
43
  "BaseClient",
43
44
  "Channel",
45
+ "ChannelQueueFullError",
44
46
  "ChannelStateHandler",
45
47
  "ClientOptions",
46
48
  "ConnectionState",
@@ -2,6 +2,8 @@ from __future__ import annotations
2
2
 
3
3
  import abc
4
4
  import asyncio
5
+ import contextlib
6
+ import math
5
7
  from collections.abc import Callable
6
8
  from typing import TypeAlias, TypeVar
7
9
 
@@ -29,17 +31,31 @@ AssignsT = TypeVar("AssignsT")
29
31
  JoinParamsT = TypeVar("JoinParamsT")
30
32
 
31
33
 
34
+ def _reconnect_delay(options: ClientOptions, attempts: int) -> float:
35
+ base = options.base_reconnect_delay
36
+ maximum = options.max_reconnect_delay
37
+ if attempts <= 0 or base >= maximum:
38
+ return min(base, maximum)
39
+ doublings_to_cap = math.ceil(math.log2(maximum / base))
40
+ if attempts >= doublings_to_cap:
41
+ return maximum
42
+ return float(min(base * (2**attempts), maximum))
43
+
44
+
32
45
  class BaseClient(abc.ABC):
33
46
  __slots__ = (
34
47
  "_broadcaster",
35
48
  "_channels",
49
+ "_connect_generation",
50
+ "_connect_task",
36
51
  "_connection_state",
37
52
  "_disconnecting",
38
53
  "_errors",
54
+ "_lifecycle_generation",
39
55
  "_options",
40
56
  "_reconnect_attempts",
41
57
  "_reconnect_task",
42
- "_tasks",
58
+ "_send_lock",
43
59
  )
44
60
 
45
61
  def __init__(self, options: ClientOptions | None = None) -> None:
@@ -50,10 +66,13 @@ class BaseClient(abc.ABC):
50
66
  ConnectionState.DISCONNECTED
51
67
  )
52
68
  self._errors: Subject[BaseException] = Subject()
69
+ self._lifecycle_generation = 0
70
+ self._connect_generation = 0
71
+ self._connect_task: asyncio.Task[None] | None = None
53
72
  self._reconnect_attempts: int = 0
54
73
  self._reconnect_task: asyncio.Task[None] | None = None
55
74
  self._disconnecting: bool = False
56
- self._tasks: set[asyncio.Task[None]] = set()
75
+ self._send_lock = asyncio.Lock()
57
76
  self._broadcaster.subscribe(self._route_event)
58
77
 
59
78
  @property
@@ -67,7 +86,7 @@ class BaseClient(abc.ABC):
67
86
  self, name: str, params: JoinParams | None = None
68
87
  ) -> Channel:
69
88
  existing = self._channels.get(name)
70
- if existing is not None and existing.channel_state.value not in ("CLOSED", "DECLINED"):
89
+ if existing is not None and not existing._is_replaceable():
71
90
  return existing
72
91
  channel = Channel(
73
92
  name=name,
@@ -99,26 +118,68 @@ class BaseClient(abc.ABC):
99
118
  self._disconnecting = False
100
119
  if self.get_state() != ConnectionState.DISCONNECTED:
101
120
  return
121
+ current_task = asyncio.current_task()
122
+ if current_task is None:
123
+ raise RuntimeError("connect() must run in an asyncio task")
124
+ self._lifecycle_generation += 1
125
+ generation = self._lifecycle_generation
126
+ self._connect_generation = generation
127
+ self._connect_task = current_task
102
128
  self._connection_state.publish(ConnectionState.CONNECTING)
103
129
  try:
104
130
  await self._open_transport()
131
+ except asyncio.CancelledError:
132
+ if generation == self._lifecycle_generation:
133
+ await self._close_transport()
134
+ self._connection_state.publish(ConnectionState.DISCONNECTED)
135
+ raise
105
136
  except Exception as exc:
106
- self._errors.publish(exc)
107
- self._connection_state.publish(ConnectionState.DISCONNECTED)
108
- self._schedule_reconnect()
137
+ if generation == self._lifecycle_generation and not self._disconnecting:
138
+ self._errors.publish(exc)
139
+ self._connection_state.publish(ConnectionState.DISCONNECTED)
140
+ self._schedule_reconnect()
141
+ else:
142
+ if generation != self._lifecycle_generation or self._disconnecting:
143
+ await self._close_transport()
144
+ self._connection_state.publish(ConnectionState.DISCONNECTED)
145
+ finally:
146
+ if self._connect_task is current_task:
147
+ self._connect_task = None
109
148
 
110
149
  async def disconnect(self) -> None:
111
150
  self._disconnecting = True
112
- if self._reconnect_task is not None and not self._reconnect_task.done():
113
- self._reconnect_task.cancel()
114
- self._reconnect_task = None
115
- await self._close_transport()
116
- self._connection_state.publish(ConnectionState.DISCONNECTED)
151
+ self._lifecycle_generation += 1
152
+ connect_task = self._connect_task
153
+ if (
154
+ connect_task is not None
155
+ and connect_task is not asyncio.current_task()
156
+ and not connect_task.done()
157
+ ):
158
+ connect_task.cancel()
159
+ await asyncio.gather(connect_task, return_exceptions=True)
160
+ reconnect_task = self._reconnect_task
161
+ self._reconnect_task = None
162
+ if reconnect_task is not None and not reconnect_task.done():
163
+ reconnect_task.cancel()
164
+ with contextlib.suppress(asyncio.CancelledError):
165
+ await reconnect_task
166
+ channel_tasks: list[asyncio.Task[None]] = []
117
167
  for channel in list(self._channels.values()):
118
- channel._force_close()
168
+ task = channel._force_close()
169
+ if task is not None and task is not asyncio.current_task():
170
+ channel_tasks.append(task)
171
+ if channel_tasks:
172
+ await asyncio.gather(*channel_tasks, return_exceptions=True)
119
173
  self._channels.clear()
174
+ await self._close_transport()
175
+ self._connection_state.publish(ConnectionState.DISCONNECTED)
120
176
 
121
177
  def _mark_connected(self) -> None:
178
+ if (
179
+ self._disconnecting
180
+ or self._connect_generation != self._lifecycle_generation
181
+ ):
182
+ return
122
183
  self._reconnect_attempts = 0
123
184
  self._connection_state.publish(ConnectionState.CONNECTED)
124
185
 
@@ -128,6 +189,13 @@ class BaseClient(abc.ABC):
128
189
  self._schedule_reconnect()
129
190
 
130
191
  def _handle_inbound_text(self, text: str) -> None:
192
+ messages = [line for line in text.splitlines() if line.strip()]
193
+ if not messages:
194
+ messages = [text]
195
+ for message in messages:
196
+ self._handle_inbound_message(message)
197
+
198
+ def _handle_inbound_message(self, text: str) -> None:
131
199
  try:
132
200
  import json
133
201
 
@@ -156,16 +224,18 @@ class BaseClient(abc.ABC):
156
224
  return
157
225
  if self._reconnect_task is not None and not self._reconnect_task.done():
158
226
  return
159
- delay = min(
160
- self._options.base_reconnect_delay * (2 ** self._reconnect_attempts),
161
- self._options.max_reconnect_delay,
162
- )
227
+ delay = _reconnect_delay(self._options, self._reconnect_attempts)
163
228
  self._reconnect_attempts += 1
164
229
  self._reconnect_task = asyncio.create_task(self._reconnect_after(delay))
165
230
  self._reconnect_task.add_done_callback(self._on_reconnect_task_done)
166
231
 
167
- def _on_reconnect_task_done(self, _task: asyncio.Task[None]) -> None:
168
- self._reconnect_task = None
232
+ def _on_reconnect_task_done(self, task: asyncio.Task[None]) -> None:
233
+ if self._reconnect_task is task:
234
+ self._reconnect_task = None
235
+ if not task.cancelled():
236
+ error = task.exception()
237
+ if error is not None:
238
+ self._errors.publish(error)
169
239
 
170
240
  async def _reconnect_after(self, delay: float) -> None:
171
241
  try:
@@ -177,7 +247,14 @@ class BaseClient(abc.ABC):
177
247
  await self.connect()
178
248
 
179
249
  async def _publish_outbound(self, message: ClientMessage) -> None:
180
- await self._send_outbound(message)
250
+ async with self._send_lock:
251
+ if self.get_state() != ConnectionState.CONNECTED:
252
+ raise ConnectionError("transport is not connected")
253
+ try:
254
+ await self._send_outbound(message)
255
+ except Exception as exc:
256
+ self._errors.publish(exc)
257
+ raise
181
258
 
182
259
  @abc.abstractmethod
183
260
  async def _open_transport(self) -> None: ...
@@ -4,7 +4,7 @@ import asyncio
4
4
  import contextlib
5
5
  from collections import deque
6
6
  from collections.abc import Callable
7
- from typing import Any, TypeAlias
7
+ from typing import TypeAlias
8
8
 
9
9
  from pondsocket_common import (
10
10
  BehaviorSubject,
@@ -39,20 +39,29 @@ class ResponseTimeoutError(Exception):
39
39
  pass
40
40
 
41
41
 
42
+ class ChannelQueueFullError(Exception):
43
+ pass
44
+
45
+
42
46
  class Channel:
43
47
  __slots__ = (
44
48
  "_closed",
49
+ "_closing",
45
50
  "_connection_state",
46
51
  "_connection_unsub",
52
+ "_drain_task",
47
53
  "_events",
54
+ "_join_generation",
55
+ "_join_request_id",
56
+ "_max_queue_size",
48
57
  "_params",
58
+ "_pending_join",
49
59
  "_pending_responses",
50
60
  "_presence",
51
61
  "_publisher",
52
62
  "_queue",
53
63
  "_response_timeout",
54
64
  "_state",
55
- "_tasks",
56
65
  "name",
57
66
  )
58
67
 
@@ -73,20 +82,22 @@ class Channel:
73
82
  self._state: BehaviorSubject[ChannelState] = BehaviorSubject(ChannelState.IDLE)
74
83
  self._events: Subject[ChannelEvent] = Subject()
75
84
  self._presence: list[PondPresence] = []
76
- self._queue: deque[ClientMessage] = deque(maxlen=max_queue_size)
85
+ self._join_generation = 0
86
+ self._join_request_id: str | None = None
87
+ if max_queue_size <= 0:
88
+ raise ValueError("max_queue_size must be greater than zero")
89
+ self._max_queue_size = max_queue_size
90
+ self._queue: deque[ClientMessage] = deque()
91
+ self._pending_join: ClientMessage | None = None
77
92
  self._pending_responses: dict[str, asyncio.Future[PondMessage]] = {}
78
93
  self._response_timeout = response_timeout
79
- self._tasks: set[asyncio.Task[None]] = set()
94
+ self._drain_task: asyncio.Task[None] | None = None
80
95
  self._closed = False
96
+ self._closing = False
81
97
  self._connection_unsub: Unsubscribe = self._connection_state.subscribe(
82
98
  self.handle_connection_state
83
99
  )
84
100
 
85
- def _spawn(self, coro: Any) -> None:
86
- task = asyncio.create_task(coro)
87
- self._tasks.add(task)
88
- task.add_done_callback(self._tasks.discard)
89
-
90
101
  @property
91
102
  def channel_state(self) -> ChannelState:
92
103
  value = self._state.value
@@ -97,17 +108,17 @@ class Channel:
97
108
  return list(self._presence)
98
109
 
99
110
  def join(self) -> None:
100
- if self._closed:
111
+ if self._closed or self._closing:
101
112
  return
102
113
  state = self.channel_state
103
114
  if state in (ChannelState.JOINING, ChannelState.JOINED, ChannelState.DECLINED):
104
115
  return
105
116
  self._state.publish(ChannelState.JOINING)
106
- msg = self._build_join_message()
107
- self._enqueue_or_send(msg)
117
+ self._prepare_join()
118
+ self._ensure_drain()
108
119
 
109
120
  def leave(self) -> None:
110
- if self._closed:
121
+ if self._closed or self._closing:
111
122
  return
112
123
  msg = ClientMessage(
113
124
  action=ClientActions.LEAVE_CHANNEL,
@@ -116,14 +127,18 @@ class Channel:
116
127
  requestId=uuid(),
117
128
  payload={},
118
129
  )
119
- if self._connection_state.value == ConnectionState.CONNECTED:
120
- self._spawn(self._publish(msg))
130
+ self._closing = True
121
131
  self._state.publish(ChannelState.CLOSED)
122
- self._closed = True
123
- self._teardown()
132
+ self._pending_join = None
133
+ self._queue.clear()
134
+ if self._connection_state.value != ConnectionState.CONNECTED:
135
+ self._finish_close()
136
+ return
137
+ self._queue.append(msg)
138
+ self._ensure_drain()
124
139
 
125
140
  def send_message(self, event: str, payload: PondMessage | None = None) -> None:
126
- if self._closed:
141
+ if self._closed or self._closing:
127
142
  return
128
143
  msg = ClientMessage(
129
144
  action=ClientActions.BROADCAST,
@@ -132,7 +147,7 @@ class Channel:
132
147
  requestId=uuid(),
133
148
  payload=dict(payload or {}),
134
149
  )
135
- self._enqueue_or_send(msg)
150
+ self._enqueue(msg)
136
151
 
137
152
  async def send_for_response(
138
153
  self,
@@ -141,7 +156,7 @@ class Channel:
141
156
  *,
142
157
  wait: float | None = None,
143
158
  ) -> PondMessage:
144
- if self._closed:
159
+ if self._closed or self._closing:
145
160
  raise ResponseTimeoutError("channel is closed")
146
161
  request_id = uuid()
147
162
  loop = asyncio.get_running_loop()
@@ -154,7 +169,11 @@ class Channel:
154
169
  requestId=request_id,
155
170
  payload=dict(payload or {}),
156
171
  )
157
- self._enqueue_or_send(msg)
172
+ try:
173
+ self._enqueue(msg)
174
+ except Exception:
175
+ self._pending_responses.pop(request_id, None)
176
+ raise
158
177
  wait_seconds = wait if wait is not None else self._response_timeout
159
178
  try:
160
179
  return await asyncio.wait_for(fut, timeout=wait_seconds)
@@ -164,9 +183,10 @@ class Channel:
164
183
  ) from e
165
184
  finally:
166
185
  self._pending_responses.pop(request_id, None)
186
+ self._remove_queued_request(request_id)
167
187
 
168
188
  def handle_event(self, event: ChannelEvent) -> None:
169
- if self._closed:
189
+ if self._closed or self._closing:
170
190
  return
171
191
  if isinstance(event, PresenceMessage):
172
192
  self._presence = [dict(p) for p in event.payload.presence]
@@ -181,10 +201,14 @@ class Channel:
181
201
  return
182
202
  if event.action == ServerActions.SYSTEM:
183
203
  if event.event == Events.ACKNOWLEDGE.value:
204
+ if not self._is_current_join_response(event.request_id):
205
+ return
184
206
  self._acknowledge()
185
207
  return
186
208
  if event.event in (Events.UNAUTHORIZED.value, Events.NOT_FOUND.value):
187
209
  if self.channel_state in (ChannelState.JOINING, ChannelState.STALLED):
210
+ if not self._is_current_join_response(event.request_id):
211
+ return
188
212
  self._decline()
189
213
  return
190
214
  if self.channel_state == ChannelState.JOINED:
@@ -194,25 +218,20 @@ class Channel:
194
218
  if self._closed:
195
219
  return
196
220
  if state == ConnectionState.CONNECTED:
197
- if self.channel_state == ChannelState.STALLED:
198
- msg = self._build_join_message()
199
- self._spawn(self._publish(msg))
200
- return
201
- if self.channel_state == ChannelState.JOINING:
202
- self._drain_queued_joins()
221
+ if (
222
+ self.channel_state in (ChannelState.JOINING, ChannelState.STALLED)
223
+ and self._pending_join is None
224
+ ):
225
+ self._prepare_join()
226
+ if self._closing or self.channel_state in (
227
+ ChannelState.JOINING,
228
+ ChannelState.STALLED,
229
+ ):
230
+ self._ensure_drain()
203
231
  elif state == ConnectionState.DISCONNECTED:
204
- if self.channel_state == ChannelState.JOINED:
232
+ if self.channel_state in (ChannelState.JOINING, ChannelState.JOINED):
205
233
  self._state.publish(ChannelState.STALLED)
206
234
 
207
- def _drain_queued_joins(self) -> None:
208
- remaining: deque[ClientMessage] = deque(maxlen=self._queue.maxlen)
209
- for msg in self._queue:
210
- if msg.action == ClientActions.JOIN_CHANNEL:
211
- self._spawn(self._publish(msg))
212
- else:
213
- remaining.append(msg)
214
- self._queue = remaining
215
-
216
235
  def on_channel_state_change(self, callback: ChannelStateHandler) -> Unsubscribe:
217
236
  return self._state.subscribe(callback)
218
237
 
@@ -266,46 +285,88 @@ class Channel:
266
285
  payload=dict(self._params),
267
286
  )
268
287
 
269
- def _enqueue_or_send(self, msg: ClientMessage) -> None:
270
- if (
271
- self._connection_state.value == ConnectionState.CONNECTED
272
- and self.channel_state == ChannelState.JOINED
273
- ):
274
- self._spawn(self._publish(msg))
275
- return
276
- is_join = msg.action == ClientActions.JOIN_CHANNEL
277
- if self._connection_state.value == ConnectionState.CONNECTED and is_join:
278
- self._spawn(self._publish(msg))
279
- return
288
+ def _prepare_join(self) -> None:
289
+ msg = self._build_join_message()
290
+ self._join_generation += 1
291
+ self._join_request_id = msg.request_id
292
+ self._pending_join = msg
293
+
294
+ def _is_current_join_response(self, request_id: str) -> bool:
295
+ return self._join_request_id is not None and request_id == self._join_request_id
296
+
297
+ def _enqueue(self, msg: ClientMessage) -> None:
298
+ if len(self._queue) >= self._max_queue_size:
299
+ raise ChannelQueueFullError(
300
+ f"channel {self.name!r} outbound queue is full "
301
+ f"(max {self._max_queue_size})"
302
+ )
280
303
  self._queue.append(msg)
304
+ self._ensure_drain()
305
+
306
+ def _remove_queued_request(self, request_id: str) -> None:
307
+ self._queue = deque(
308
+ msg for msg in self._queue if msg.request_id != request_id
309
+ )
281
310
 
282
- def _flush_queue(self) -> None:
283
- if not self._queue:
311
+ def _ensure_drain(self) -> None:
312
+ if self._closed:
284
313
  return
285
- pending = list(self._queue)
286
- self._queue.clear()
287
- for msg in pending:
288
- self._spawn(self._publish(msg))
314
+ if self._drain_task is not None and not self._drain_task.done():
315
+ return
316
+ self._drain_task = asyncio.create_task(self._drain())
317
+ self._drain_task.add_done_callback(self._on_drain_done)
318
+
319
+ def _on_drain_done(self, task: asyncio.Task[None]) -> None:
320
+ if self._drain_task is task:
321
+ self._drain_task = None
322
+ if not task.cancelled():
323
+ task.exception()
324
+
325
+ async def _drain(self) -> None:
326
+ while not self._closed:
327
+ if self._connection_state.value != ConnectionState.CONNECTED:
328
+ return
329
+ if self._pending_join is not None:
330
+ msg = self._pending_join
331
+ try:
332
+ await self._publisher(msg)
333
+ except asyncio.CancelledError:
334
+ raise
335
+ except Exception:
336
+ return
337
+ if self._pending_join is msg:
338
+ self._pending_join = None
339
+ continue
340
+ if not self._queue:
341
+ return
342
+ if not self._closing and self.channel_state != ChannelState.JOINED:
343
+ return
344
+ msg = self._queue[0]
345
+ try:
346
+ await self._publisher(msg)
347
+ except asyncio.CancelledError:
348
+ raise
349
+ except Exception:
350
+ return
351
+ if self._queue and self._queue[0] is msg:
352
+ self._queue.popleft()
353
+ if msg.action == ClientActions.LEAVE_CHANNEL:
354
+ self._finish_close()
355
+ return
289
356
 
290
357
  def _acknowledge(self) -> None:
291
358
  if self.channel_state not in (ChannelState.JOINING, ChannelState.STALLED):
292
359
  return
360
+ self._join_request_id = None
293
361
  self._state.publish(ChannelState.JOINED)
294
- self._flush_queue()
362
+ self._ensure_drain()
295
363
 
296
364
  def _decline(self) -> None:
297
365
  self._state.publish(ChannelState.DECLINED)
298
- self._queue.clear()
299
- for fut in self._pending_responses.values():
300
- if not fut.done():
301
- fut.cancel()
302
- self._pending_responses.clear()
303
-
304
- async def _publish(self, msg: ClientMessage) -> None:
305
- try:
306
- await self._publisher(msg)
307
- except Exception:
308
- return
366
+ self._join_request_id = None
367
+ self._pending_join = None
368
+ self._closed = True
369
+ self._teardown()
309
370
 
310
371
  def _teardown(self) -> None:
311
372
  with contextlib.suppress(Exception):
@@ -317,21 +378,32 @@ class Channel:
317
378
  self._queue.clear()
318
379
  self._events.close()
319
380
 
320
- def _force_close(self) -> None:
381
+ def _finish_close(self) -> None:
382
+ self._closed = True
383
+ self._closing = False
384
+ self._teardown()
385
+
386
+ def _force_close(self) -> asyncio.Task[None] | None:
321
387
  if self._closed:
322
- return
388
+ return self._drain_task
323
389
  self._state.publish(ChannelState.CLOSED)
324
390
  self._closed = True
391
+ self._closing = False
392
+ task = self._drain_task
393
+ if task is not None and not task.done() and task is not asyncio.current_task():
394
+ task.cancel()
325
395
  self._teardown()
396
+ return task
326
397
 
327
398
  def _close_state_subject(self) -> None:
328
399
  self._state.close()
329
400
 
330
-
331
- _publisher_alias: Any = Publisher
401
+ def _is_replaceable(self) -> bool:
402
+ return self._closed or self.channel_state == ChannelState.DECLINED
332
403
 
333
404
  __all__ = [
334
405
  "Channel",
406
+ "ChannelQueueFullError",
335
407
  "ChannelStateHandler",
336
408
  "MessageHandler",
337
409
  "PresenceHandler",
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import abc
4
4
  import asyncio
5
+ import contextlib
5
6
  import json
6
7
  from typing import TYPE_CHECKING
7
8
 
@@ -38,16 +39,19 @@ class WebSocketClient(BaseClient, abc.ABC):
38
39
  self._recv_task = asyncio.create_task(self._receive_loop())
39
40
 
40
41
  async def _close_transport(self) -> None:
41
- if self._recv_task is not None and not self._recv_task.done():
42
- self._recv_task.cancel()
43
- self._recv_task = None
42
+ recv_task = self._recv_task
43
+ self._recv_task = None
44
+ if recv_task is not None and not recv_task.done():
45
+ recv_task.cancel()
46
+ with contextlib.suppress(asyncio.CancelledError):
47
+ await recv_task
44
48
  socket = self._socket
45
49
  self._socket = None
46
50
  if socket is not None:
47
51
  try:
48
52
  await socket.close()
49
- except Exception:
50
- return
53
+ except Exception as exc:
54
+ self._errors.publish(exc)
51
55
 
52
56
  async def _send_outbound(self, message: ClientMessage) -> None:
53
57
  socket = self._socket