Skip to content

Commit 67febb0

Browse files
chipkentclaude
andcommitted
feat: surface a max_connections status received during the handshake
When the account has too many connections open, the server answers auth with a max_connections status and then closes the connection. The client only logged it, so the caller could not tell it from a network drop. Now connect() sets max_connections_reached until a later handshake succeeds and, in raw mode, passes the message to the processor, as it does for statuses after the handshake. Such a handshake does not reset the failure count, so the backoff keeps growing while the limit is hit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 75c9cab commit 67febb0

2 files changed

Lines changed: 86 additions & 3 deletions

File tree

‎massive/websocket/__init__.py‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,8 @@ def __init__(
121121
self._close_requested = threading.Event()
122122
self._close_event: Optional[asyncio.Event] = None
123123
self._close_task: Optional[asyncio.Future] = None
124+
# whether the server said max_connections during the last handshake
125+
self.max_connections_reached = False
124126
self.reconnect_backoff = reconnect_backoff
125127
self.max_reconnect_backoff = max_reconnect_backoff
126128

@@ -147,6 +149,12 @@ async def connect(
147149
4xx or a TLS certificate that cannot be verified, are raised at once.
148150
It returns once `close()` or `request_close()` is called.
149151
152+
If the server sends a `max_connections` status during the handshake
153+
(the account has too many connections open), `max_connections_reached`
154+
is set until a later handshake succeeds, and in raw mode the message is
155+
also passed to `processor`. The server then closes the connection, and
156+
the client reconnects after the backoff.
157+
150158
:param processor: The callback to process messages.
151159
:param close_timeout: How long to wait for handshake when calling .close.
152160
:raises AuthError: If invalid API key is supplied.
@@ -209,7 +217,8 @@ async def _connect(
209217
try:
210218
msg = await s.recv()
211219
logger.debug("connected: %s", msg)
212-
self._log_server_statuses(self.json.loads(msg))
220+
msg_parsed = self.json.loads(msg)
221+
self._log_server_statuses(msg_parsed)
213222
logger.debug("authing...")
214223
await s.send(
215224
self.json.dumps({"action": "auth", "params": self.api_key})
@@ -219,7 +228,14 @@ async def _connect(
219228
logger.debug("authed: %s", auth_msg)
220229
if auth_msg_parsed[0]["status"] == "auth_failed":
221230
raise AuthError(auth_msg_parsed[0]["message"])
222-
failures = 0
231+
self.max_connections_reached = False
232+
for frame, parsed in ((msg, msg_parsed), (auth_msg, auth_msg_parsed)):
233+
if any(m.get("status") == "max_connections" for m in parsed):
234+
self.max_connections_reached = True
235+
if self.raw:
236+
await processor(frame) # type: ignore
237+
if not self.max_connections_reached:
238+
failures = 0
223239
# e.g. max_connections, which the server sends before closing
224240
self._log_server_statuses(auth_msg_parsed)
225241
self._flush_server_errors(force=True)

‎test_websocket/test_reconnect.py‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import json
23
import socket
34
import ssl
45
import threading
@@ -7,7 +8,7 @@
78
from typing import Any, List, Optional
89
from unittest import mock
910

10-
from fake_server import FakeServer
11+
from fake_server import FakeServer, status
1112
from websockets.asyncio.server import ServerConnection
1213
from websockets.datastructures import Headers
1314
from websockets.exceptions import (
@@ -442,6 +443,72 @@ def status(code: int) -> InvalidStatus:
442443
self.assertFalse(WebSocketClient._is_transient(e), repr(e))
443444

444445

446+
class MaxConnectionsTest(unittest.IsolatedAsyncioTestCase):
447+
"""A max_connections status in the reply to auth reaches the caller."""
448+
449+
async def asyncSetUp(self) -> None:
450+
self.server = await FakeServer().start()
451+
self.addAsyncCleanup(self.server.stop)
452+
self.status = status(
453+
"max_connections", "Maximum number of websocket connections exceeded."
454+
)
455+
456+
async def test_raw_processor_receives_it(self) -> None:
457+
self.server.script_auth(self.status, close_code=1008)
458+
c = WebSocketClient(
459+
api_key="key",
460+
feed=self.server.feed,
461+
secure=False,
462+
raw=True,
463+
reconnect_backoff=BACKOFF,
464+
subscriptions=["T.AAPL"],
465+
)
466+
frames: List[Any] = []
467+
468+
async def processor(msg: Any) -> None:
469+
frames.append((json.loads(msg), c.max_connections_reached))
470+
471+
task = asyncio.create_task(c.connect(processor))
472+
# it reconnects after the server closes, and the next handshake succeeds
473+
await self.server.wait_for_connections(1)
474+
await self.server.wait_for_subscriptions({"T.AAPL"})
475+
self.assertEqual(len(self.server.connections), 2)
476+
self.assertEqual(frames[0], ([self.status], True))
477+
self.assertFalse(c.max_connections_reached)
478+
479+
c.request_close()
480+
await asyncio.wait_for(task, 5)
481+
482+
async def test_flag_is_set(self) -> None:
483+
self.server.script_auth(self.status, close_code=1008)
484+
self.server.script_auth(self.status, close_code=1008)
485+
c = WebSocketClient(
486+
api_key="key",
487+
feed=self.server.feed,
488+
secure=False,
489+
reconnect_backoff=0.2,
490+
max_reconnect_backoff=0.2,
491+
)
492+
delays: List[int] = []
493+
delay = c._reconnect_delay
494+
495+
def record(attempt: int) -> float:
496+
delays.append(attempt)
497+
return delay(attempt)
498+
499+
with mock.patch.object(c, "_reconnect_delay", side_effect=record):
500+
task = asyncio.create_task(c.connect(ignore))
501+
await self.server.wait_for(lambda: c.max_connections_reached)
502+
# cleared by the next successful handshake
503+
await self.server.wait_for_connections(1)
504+
await self.server.wait_for(lambda: not c.max_connections_reached)
505+
self.assertEqual(len(self.server.connections), 3)
506+
c.request_close()
507+
await asyncio.wait_for(task, 5)
508+
# a refused handshake is a failed attempt, so the backoff grows
509+
self.assertEqual(delays, [0, 1])
510+
511+
445512
class ReconnectDelayTest(unittest.TestCase):
446513
"""The wait before each consecutive reconnect attempt."""
447514

0 commit comments

Comments
 (0)