pybluecurrent 0.4.0__tar.gz → 0.4.1__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 (49) hide show
  1. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/CHANGELOG.md +10 -0
  2. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/PKG-INFO +1 -1
  3. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/_version.py +3 -3
  4. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/client.py +46 -31
  5. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent.egg-info/PKG-INFO +1 -1
  6. pybluecurrent-0.4.1/src/pybluecurrent.egg-info/scm_version.json +8 -0
  7. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fake_socket.py +11 -0
  8. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/test_offline.py +113 -11
  9. pybluecurrent-0.4.0/src/pybluecurrent.egg-info/scm_version.json +0 -8
  10. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/.github/workflows/publish.yaml +0 -0
  11. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/.github/workflows/test.yaml +0 -0
  12. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/.gitignore +0 -0
  13. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/.pre-commit-config.yaml +0 -0
  14. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/LICENSE +0 -0
  15. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/README.md +0 -0
  16. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/pyproject.toml +0 -0
  17. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/setup.cfg +0 -0
  18. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/__init__.py +0 -0
  19. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/cli/__init__.py +0 -0
  20. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/cli/transactions.py +0 -0
  21. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/enums.py +0 -0
  22. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/exceptions.py +0 -0
  23. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/models.py +0 -0
  24. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/py.typed +0 -0
  25. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent/utilities.py +0 -0
  26. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent.egg-info/SOURCES.txt +0 -0
  27. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent.egg-info/dependency_links.txt +0 -0
  28. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent.egg-info/entry_points.txt +0 -0
  29. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent.egg-info/requires.txt +0 -0
  30. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent.egg-info/scm_file_list.json +0 -0
  31. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/src/pybluecurrent.egg-info/top_level.txt +0 -0
  32. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/conftest.py +0 -0
  33. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fake_rest.py +0 -0
  34. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/account.json +0 -0
  35. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/charge_cards.json +0 -0
  36. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/charge_point_settings.json +0 -0
  37. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/charge_point_status.json +0 -0
  38. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/charge_point_status_socket_two.json +0 -0
  39. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/charge_point_statuses.json +0 -0
  40. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/charge_points.json +0 -0
  41. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/error_forbidden.json +0 -0
  42. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/grid_status.json +0 -0
  43. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/sustainability_status.json +0 -0
  44. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/fixtures/transactions.json +0 -0
  45. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/models_check.py +0 -0
  46. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/test_cli.py +0 -0
  47. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/test_client.py +0 -0
  48. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/test_enums.py +0 -0
  49. {pybluecurrent-0.4.0 → pybluecurrent-0.4.1}/tests/test_utilities.py +0 -0
@@ -5,6 +5,15 @@ All notable changes to this project are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
  This project is pre-1.0: breaking changes may land in minor releases.
7
7
 
8
+ ## [0.4.1] - 2026-09-12
9
+
10
+ ### Fixed
11
+
12
+ - Automatic reconnection no longer stops for good after an abnormal disconnect. A connection that dropped without a proper close, or a reconnect attempt whose handshake was refused (for example during backend maintenance) or timed out, used to end the reconnect loop and leave the client disconnected; it now retries with backoff as intended.
13
+ - A reconnect attempt whose login or handshake goes unanswered now waits the maximum backoff before logging in again, as intended, instead of retrying on the normal schedule.
14
+ - When the client stops reconnecting for any reason, it is now marked as closed, so calls fail with `ConnectionLost` rather than running into a dead connection, and closing the client always releases its HTTP client.
15
+ - A received frame that is valid JSON but not an object is now skipped, instead of failing the calls awaiting a reply.
16
+
8
17
  ## [0.4.0] - 2026-09-11
9
18
 
10
19
  ### Added
@@ -84,6 +93,7 @@ This project is pre-1.0: breaking changes may land in minor releases.
84
93
  - `get_account` returns `first_login_app` as a `datetime` (previously a `date`).
85
94
  - Internal: switched tooling to Ruff and ty, added a Python 3.10–3.13 CI matrix, and moved to PyPI trusted publishing (OIDC).
86
95
 
96
+ [0.4.1]: https://github.com/rogiervandergeer/pybluecurrent/compare/0.4.0...0.4.1
87
97
  [0.4.0]: https://github.com/rogiervandergeer/pybluecurrent/compare/0.3.0...0.4.0
88
98
  [0.3.0]: https://github.com/rogiervandergeer/pybluecurrent/compare/0.2.0...0.3.0
89
99
  [0.2.0]: https://github.com/rogiervandergeer/pybluecurrent/compare/0.1.1...0.2.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybluecurrent
3
- Version: 0.4.0
3
+ Version: 0.4.1
4
4
  Summary: Python client for BlueCurrent charge points.
5
5
  Author-email: Rogier van der Geer <rogier@vander-geer.nl>
6
6
  License: MIT
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.4.0'
22
- __version_tuple__ = version_tuple = (0, 4, 0)
21
+ __version__ = version = '0.4.1'
22
+ __version_tuple__ = version_tuple = (0, 4, 1)
23
23
 
24
- __commit_id__ = commit_id = 'gf95de5f79'
24
+ __commit_id__ = commit_id = 'g94f4b103b'
@@ -1,7 +1,7 @@
1
- from asyncio import CancelledError, Event, Lock, Queue, Task, create_task, get_running_loop, sleep, wait, wait_for
1
+ from asyncio import Event, Lock, Queue, Task, create_task, get_running_loop, sleep, wait, wait_for
2
2
  from asyncio import TimeoutError as AsyncTimeoutError
3
3
  from collections import defaultdict, deque
4
- from contextlib import asynccontextmanager, suppress
4
+ from contextlib import asynccontextmanager
5
5
  from datetime import date, time
6
6
  from json import JSONDecodeError, dumps, loads
7
7
  from logging import getLogger
@@ -13,7 +13,7 @@ from asyncio_multisubscriber_queue import MultisubscriberQueue
13
13
  from httpx import AsyncClient, HTTPStatusError
14
14
  from sjcl import SJCL
15
15
  from websockets.asyncio.client import ClientConnection, connect
16
- from websockets.exceptions import ConnectionClosed
16
+ from websockets.exceptions import ConnectionClosed, WebSocketException
17
17
 
18
18
  from pybluecurrent._version import __version__
19
19
  from pybluecurrent.enums import Weekday
@@ -94,8 +94,9 @@ def _normalize_charge_point(data: dict[str, Any]) -> None:
94
94
  data["plug_and_charge_charge_card"] = None
95
95
 
96
96
 
97
- # Identity sentinel broadcast on the queue when the receive handler exits, so in-flight _receive
98
- # waiters wake immediately instead of blocking until their own deadline.
97
+ # Identity sentinel broadcast on the queue when the receive handler exits, and again once the client
98
+ # is closed for good, so in-flight _receive waiters wake immediately instead of blocking until their
99
+ # own deadline.
99
100
  _CONNECTION_CLOSED = object()
100
101
 
101
102
  # Frame fields masked before a received message is logged, so a token never reaches the logs.
@@ -186,12 +187,12 @@ class BlueCurrentClient:
186
187
  logger.debug("Closing BlueCurrent connection")
187
188
  self._shutting_down = True
188
189
  self._closed = self._closed or ConnectionLost("Client is shutting down.")
189
- self._connected.set() # release any gated waiter so it sees _closed
190
190
  if self._supervisor is not None:
191
- # Stop the supervisor first so it can't race a reconnect against the teardown below.
191
+ # Stop the supervisor first so it can't race a reconnect against the teardown below; its
192
+ # finally wakes every waiter. wait(), not `await`: a crashed supervisor must not re-raise
193
+ # here and skip the teardown.
192
194
  self._supervisor.cancel()
193
- with suppress(CancelledError):
194
- await self._supervisor
195
+ await wait({self._supervisor})
195
196
  self._supervisor = None
196
197
  await self._teardown(exc_type, exc_val, exc_tb)
197
198
 
@@ -220,9 +221,10 @@ class BlueCurrentClient:
220
221
  async def _teardown_transport(self, exc_type=None, exc_val=None, exc_tb=None) -> None:
221
222
  """Close the websocket transport (handler + socket) but keep the httpx client so REST keeps working."""
222
223
  if self.consumer is not None:
223
- self.consumer.cancel() # stop the handler and await it so its exception is retrieved
224
- with suppress(CancelledError):
225
- await self.consumer
224
+ self.consumer.cancel()
225
+ # wait(), not `await`: a handler that died of a dropped connection must not re-raise its
226
+ # error here (_on_handler_done logs it), which would kill the reconnect supervisor.
227
+ await wait({self.consumer})
226
228
  if self.connection is not None:
227
229
  try:
228
230
  await self.connection.__aexit__(exc_type, exc_val, exc_tb)
@@ -245,7 +247,11 @@ class BlueCurrentClient:
245
247
  if task.cancelled():
246
248
  return
247
249
  exc = task.exception()
248
- if exc is not None:
250
+ if isinstance(exc, ConnectionClosed):
251
+ # A connection dropping without a close handshake is routine, and the supervisor logs
252
+ # the reconnect: a stack trace here would make every network blip look like a crash.
253
+ logger.debug("Websocket connection closed: %r", exc)
254
+ elif exc is not None:
249
255
  logger.error("Websocket receive handler exited", exc_info=exc)
250
256
 
251
257
  def _on_supervisor_done(self, task: Task) -> None:
@@ -268,6 +274,7 @@ class BlueCurrentClient:
268
274
 
269
275
  async def _supervise(self) -> None:
270
276
  """Own the connection for the client's lifetime: reconnect after drops until told to stop."""
277
+ reason: BlueCurrentException = ConnectionLost("Reconnect supervisor stopped unexpectedly.")
271
278
  try:
272
279
  while not self._shutting_down:
273
280
  await self._wait_for_drop()
@@ -278,18 +285,21 @@ class BlueCurrentClient:
278
285
  await self._teardown_transport()
279
286
  if self._now() - self._last_connect >= self.reconnect_stable_period:
280
287
  self._backoff = self.reconnect_initial_backoff # stable uptime → reset (flap guard)
281
- try:
282
- await self._reconnect_with_backoff()
283
- except _GiveUp as give_up:
284
- await self._teardown_transport() # release the giving-up attempt's partial transport
285
- logger.error("Reconnect abandoned: %s", give_up.reason)
286
- self._closed = give_up.reason
287
- self._connected.set() # wake blocked waiters so they immediately re-raise _closed
288
- return
288
+ await self._reconnect_with_backoff()
289
289
  logger.info("Reconnected")
290
290
  self._connected.set()
291
+ except _GiveUp as give_up:
292
+ await self._teardown_transport() # release the giving-up attempt's partial transport
293
+ logger.error("Reconnect abandoned: %s", give_up.reason)
294
+ reason = give_up.reason
291
295
  finally:
292
- self._connected.set() # never leave a waiter blocked forever
296
+ # However the supervisor ends (given up, shut down, or crashed), nobody reconnects any
297
+ # more: latch the client closed (an earlier reason wins) and wake every waiter — gated
298
+ # calls through _connected, queue subscribers through a sentinel sent after _closed, so
299
+ # it reads as final. The broadcast never suspends: every subscriber queue is unbounded.
300
+ self._closed = self._closed or reason
301
+ self._connected.set()
302
+ await self.queue.put(_CONNECTION_CLOSED)
293
303
 
294
304
  async def _wait_for_drop(self) -> None:
295
305
  """Block until the current handler task finishes (the connection dropped)."""
@@ -317,15 +327,17 @@ class BlueCurrentClient:
317
327
  raise _GiveUp(exc) # bad credentials are permanent — never retry
318
328
  except _GiveUp:
319
329
  raise # gave up (from _note_login_attempt)
320
- except (OSError, ConnectionClosed, ConnectionLost) as exc:
321
- logger.debug("Reconnect attempt failed: %r", exc)
322
- await self._teardown_transport() # transport failure: keep the token and retry
323
- self._grow_backoff()
324
- except (RequestTimeout, BlueCurrentException) as exc:
325
- # auth/hello rejected: the token may be stale, so log in again next attempt
330
+ except (OSError, WebSocketException, AsyncTimeoutError, BlueCurrentException) as exc:
331
+ # One clause, so the outcome no longer depends on the order in which an exception
332
+ # hierarchy is caught: RequestTimeout is a BlueCurrentException *and*, through
333
+ # TimeoutError, an OSError. A transport failure (the socket dropped, the handshake
334
+ # was refused — e.g. a 5xx during maintenance — or it timed out, which is a distinct
335
+ # asyncio.TimeoutError on Python 3.10) keeps the token; a login or hello that was
336
+ # rejected or went unanswered may mean a stale token, so log in again next attempt.
326
337
  logger.debug("Reconnect attempt failed: %r", exc)
327
- self.token = None
328
338
  await self._teardown_transport()
339
+ if isinstance(exc, BlueCurrentException) and not isinstance(exc, ConnectionLost):
340
+ self.token = None
329
341
  if isinstance(exc, RequestTimeout):
330
342
  self._backoff = self.reconnect_max_backoff # a timed-out login backs off hardest
331
343
  else:
@@ -1116,8 +1128,11 @@ class BlueCurrentClient:
1116
1128
  try:
1117
1129
  decoded = loads(message)
1118
1130
  except JSONDecodeError:
1119
- # A single malformed frame is a transient wire artifact; log it and keep going.
1120
- logger.warning("Discarding malformed (non-JSON) frame: %r", message)
1131
+ decoded = None
1132
+ if not isinstance(decoded, dict):
1133
+ # A single malformed frame — not JSON, or JSON that is not an object, and so no
1134
+ # reply to anything — is a transient wire artifact: log it and keep going.
1135
+ logger.warning("Discarding malformed frame: %r", message)
1121
1136
  continue
1122
1137
  logger.debug("Received message: %s", _redact(decoded))
1123
1138
  await self.queue.put(decoded)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybluecurrent
3
- Version: 0.4.0
3
+ Version: 0.4.1
4
4
  Summary: Python client for BlueCurrent charge points.
5
5
  Author-email: Rogier van der Geer <rogier@vander-geer.nl>
6
6
  License: MIT
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "0.4.1",
3
+ "distance": 0,
4
+ "node": "g94f4b103b276336db56e2d48187622d185ac8d76",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-09-12"
8
+ }
@@ -75,6 +75,15 @@ class FakeSocket:
75
75
  self.closed = True
76
76
  self._outbound.put_nowait(_DISCONNECT)
77
77
 
78
+ def fail(self, error: BaseException) -> None:
79
+ """Signal an unclean disconnect: the ``async for`` in ``_handler`` raises ``error``.
80
+
81
+ A real socket raises ``ConnectionClosedError`` when the connection drops without a proper
82
+ close handshake (for example close code 1006), rather than ending the iteration cleanly.
83
+ """
84
+ self.closed = True
85
+ self._outbound.put_nowait(error)
86
+
78
87
  def __aiter__(self) -> "FakeSocket":
79
88
  return self
80
89
 
@@ -82,6 +91,8 @@ class FakeSocket:
82
91
  frame = await self._outbound.get()
83
92
  if frame is _DISCONNECT:
84
93
  raise StopAsyncIteration
94
+ if isinstance(frame, BaseException):
95
+ raise frame
85
96
  return frame
86
97
 
87
98
  # -- client -> server -------------------------------------------------
@@ -1,9 +1,11 @@
1
1
  import logging
2
- from asyncio import CancelledError, create_task, gather, sleep
2
+ from asyncio import CancelledError, Event, create_task, gather, sleep, wait_for
3
+ from asyncio import TimeoutError as AsyncTimeoutError
3
4
  from contextlib import suppress
4
5
  from datetime import date, datetime, time
5
6
  from unittest.mock import ANY
6
7
 
8
+ from asyncio_multisubscriber_queue import MultisubscriberQueue
7
9
  from fake_rest import FakeRest, make_fake_async_client
8
10
  from fake_socket import (
9
11
  FAKE_CUSTOMER_ID,
@@ -17,9 +19,10 @@ from fake_socket import (
17
19
  )
18
20
  from models_check import assert_model
19
21
  from pytest import MonkeyPatch, mark, raises
22
+ from websockets.exceptions import ConnectionClosedError, InvalidHandshake
20
23
 
21
24
  from pybluecurrent import BlueCurrentClient, Weekday
22
- from pybluecurrent.client import _redact
25
+ from pybluecurrent.client import _CONNECTION_CLOSED, _redact
23
26
  from pybluecurrent.client import logger as client_logger
24
27
  from pybluecurrent.exceptions import AuthenticationFailed, BlueCurrentException, ConnectionLost, RequestTimeout
25
28
  from pybluecurrent.models import (
@@ -138,15 +141,19 @@ class TestOfflineTransport:
138
141
  assert (await first)["value"] == 1
139
142
  assert (await second)["value"] == 1
140
143
 
141
- async def test_non_json_frame_is_skipped(self, offline_client: BlueCurrentClient, fake_socket: FakeSocket):
142
- # A malformed frame is logged and skipped; the handler survives and still delivers later frames.
144
+ @mark.parametrize("frame", ["this is not json", "[1, 2]", "42"], ids=["non-json", "array", "scalar"])
145
+ async def test_malformed_frame_is_skipped(
146
+ self, offline_client: BlueCurrentClient, fake_socket: FakeSocket, frame: str
147
+ ):
148
+ # A frame that is not JSON, or is JSON but not an object, is logged and skipped; the handler
149
+ # survives, the waiting call is unharmed, and later frames still arrive.
143
150
  consumer = offline_client.consumer
144
151
  assert consumer is not None
145
152
  task = create_task(offline_client._receive("PONG"))
146
153
  await sleep(0)
147
- fake_socket.feed("this is not json")
154
+ fake_socket.feed(frame)
148
155
  fake_socket.feed({"object": "PONG", "value": 1})
149
- assert (await task)["value"] == 1
156
+ assert (await wait_for(task, 1))["value"] == 1
150
157
  assert not consumer.done()
151
158
 
152
159
 
@@ -858,10 +865,35 @@ def _validate_count(*sockets):
858
865
  return sum(m.get("command") == "VALIDATE_PASSWORD" for s in sockets for m in s.sent)
859
866
 
860
867
 
868
+ class _RecordingQueue(MultisubscriberQueue):
869
+ """A broadcast queue noting, for each connection-closed sentinel, whether the client was closed yet.
870
+
871
+ A waiter only learns the final state from a sentinel sent *after* ``_closed`` is set; one sent
872
+ before it reads as a transient drop, after which the waiter blocks for good.
873
+ """
874
+
875
+ def __init__(self, client: BlueCurrentClient) -> None:
876
+ super().__init__()
877
+ self.client = client
878
+ self.closed_at_sentinel: list[bool] = []
879
+
880
+ async def put(self, data):
881
+ if data is _CONNECTION_CLOSED:
882
+ self.closed_at_sentinel.append(self.client._closed is not None)
883
+ await super().put(data)
884
+
885
+
861
886
  class TestReconnect:
862
887
  """The auto-reconnect supervisor (auto_reconnect=True), driven by a reconnecting fake transport."""
863
888
 
864
- async def test_transparent_reconnect_reuses_token(self, monkeypatch: MonkeyPatch, fake_rest: FakeRest):
889
+ @mark.parametrize(
890
+ "drop",
891
+ [FakeSocket.close, lambda socket: socket.fail(ConnectionClosedError(None, None))],
892
+ # An unclean drop (no close handshake, close code 1006) ends the socket's iteration with an
893
+ # error instead of cleanly — which used to kill the supervisor, so nothing reconnected.
894
+ ids=["clean", "unclean"],
895
+ )
896
+ async def test_transparent_reconnect_reuses_token(self, monkeypatch: MonkeyPatch, fake_rest: FakeRest, drop):
865
897
  first, second = FakeSocket(), FakeSocket()
866
898
  second.on("GET_GRID_STATUS", {"object": "GRID_STATUS", "data": {"id": "GRID-2"}})
867
899
  client, _ = _setup_reconnecting(
@@ -869,11 +901,12 @@ class TestReconnect:
869
901
  )
870
902
  async with client:
871
903
  token = client.token
872
- first.close()
904
+ drop(first)
873
905
  await _wait_until(lambda: client.socket is second and client._connected.is_set())
874
906
  assert client.token == token # reused the cached token — no re-login
875
907
  assert _validate_count(second) == 0
876
- assert (await client.get_grid_status("A"))["id"] == "GRID-2"
908
+ assert (await wait_for(client.get_grid_status("A"), 1))["id"] == "GRID-2"
909
+ assert client.httpx_client is None # and the teardown still ran to the end
877
910
 
878
911
  async def test_inflight_call_fails_then_client_recovers(self, monkeypatch: MonkeyPatch, fake_rest: FakeRest):
879
912
  first, second = FakeSocket(), FakeSocket()
@@ -921,12 +954,21 @@ class TestReconnect:
921
954
  await _wait_until(lambda: client.socket is final and client._connected.is_set())
922
955
  assert delays == [1.0, 2.0, 4.0, 8.0, 8.0, 8.0]
923
956
 
924
- async def test_transport_failure_keeps_token(self, monkeypatch: MonkeyPatch, fake_rest: FakeRest):
957
+ @mark.parametrize(
958
+ "error",
959
+ [OSError(), InvalidHandshake("server rejected the handshake"), AsyncTimeoutError()],
960
+ # The handshake can also be refused (e.g. a 5xx during maintenance) or time out, which on
961
+ # Python 3.10 is a distinct asyncio.TimeoutError.
962
+ ids=["socket", "handshake", "timeout"],
963
+ )
964
+ async def test_transport_failure_keeps_token(
965
+ self, monkeypatch: MonkeyPatch, fake_rest: FakeRest, error: BaseException
966
+ ):
925
967
  first, final = FakeSocket(), FakeSocket()
926
968
  client, _ = _setup_reconnecting(
927
969
  monkeypatch,
928
970
  fake_rest,
929
- _sequence(FakeConnection(first), FailingConnection(OSError()), FakeConnection(final)),
971
+ _sequence(FakeConnection(first), FailingConnection(error), FakeConnection(final)),
930
972
  )
931
973
  async with client:
932
974
  token = client.token
@@ -999,12 +1041,14 @@ class TestReconnect:
999
1041
  monkeypatch, fake_rest, _sequence(FakeConnection(first), *(FakeConnection(s) for s in reconnects))
1000
1042
  )
1001
1043
  client.reconnect_max_relogins = 2
1044
+ client.queue = _RecordingQueue(client)
1002
1045
  async with client:
1003
1046
  first.close()
1004
1047
  await _wait_until(lambda: client._closed is not None)
1005
1048
  assert isinstance(client._closed, ConnectionLost)
1006
1049
  assert client._connected.is_set()
1007
1050
  assert _validate_count(first, *reconnects) == 2 # never issues a 3rd VALIDATE_PASSWORD
1051
+ assert client.queue.closed_at_sentinel[-1] # subscribers are woken after the client closed
1008
1052
  with raises(ConnectionLost):
1009
1053
  await client.get_grid_status("A") # gated call fails promptly, no hang
1010
1054
 
@@ -1017,10 +1061,12 @@ class TestReconnect:
1017
1061
  fake_rest,
1018
1062
  _sequence(FakeConnection(first), FakeConnection(reject_hello), FakeConnection(reject_login)),
1019
1063
  )
1064
+ client.queue = _RecordingQueue(client)
1020
1065
  async with client:
1021
1066
  first.close()
1022
1067
  await _wait_until(lambda: client._closed is not None)
1023
1068
  assert isinstance(client._closed, AuthenticationFailed) # permanent — no retry loop
1069
+ assert client.queue.closed_at_sentinel[-1] # subscribers are woken after the client closed
1024
1070
  with raises(AuthenticationFailed):
1025
1071
  await client.get_grid_status("A")
1026
1072
 
@@ -1078,6 +1124,62 @@ class TestReconnect:
1078
1124
  assert client._supervisor is None
1079
1125
  assert client.consumer is None and client.socket is None
1080
1126
 
1127
+ async def test_timed_out_reconnect_handshake_backs_off_hardest(self, monkeypatch: MonkeyPatch, fake_rest: FakeRest):
1128
+ first, second, final = FakeSocket(), FakeSocket(), FakeSocket()
1129
+ client, delays = _setup_reconnecting(
1130
+ monkeypatch, fake_rest, _sequence(FakeConnection(first), FakeConnection(second), FakeConnection(final))
1131
+ )
1132
+ client.reconnect_initial_backoff = 1.0
1133
+ client.reconnect_max_backoff = 50.0
1134
+ hello = client._hello
1135
+
1136
+ async def hello_timing_out_on_second():
1137
+ if client.socket is second:
1138
+ raise RequestTimeout("No HELLO received within 10s.")
1139
+ await hello()
1140
+
1141
+ monkeypatch.setattr(client, "_hello", hello_timing_out_on_second)
1142
+ async with client:
1143
+ first.close()
1144
+ await _wait_until(lambda: client.socket is final and client._connected.is_set())
1145
+ assert delays == [1.0, 50.0] # the timed-out attempt backs off with the maximum delay
1146
+ assert _validate_count(final) == 1 # and drops the token, so the next attempt logs in again
1147
+
1148
+ async def test_supervisor_crash_closes_the_client(self, monkeypatch: MonkeyPatch, fake_rest: FakeRest):
1149
+ first = FakeSocket()
1150
+ client, _ = _setup_reconnecting(monkeypatch, fake_rest, _sequence(FakeConnection(first)))
1151
+
1152
+ async def crash():
1153
+ raise RuntimeError("unexpected")
1154
+
1155
+ monkeypatch.setattr(client, "_reconnect_with_backoff", crash)
1156
+ client.queue = _RecordingQueue(client)
1157
+ async with client:
1158
+ first.close()
1159
+ await _wait_until(lambda: client._closed is not None)
1160
+ assert isinstance(client._closed, ConnectionLost)
1161
+ assert client.queue.closed_at_sentinel[-1]
1162
+ with raises(ConnectionLost):
1163
+ await wait_for(client.get_grid_status("A"), 1) # fails promptly rather than hanging
1164
+ assert client.httpx_client is None # the crashed supervisor does not stop the teardown
1165
+
1166
+ async def test_exit_while_reconnecting_wakes_subscribers(self, monkeypatch: MonkeyPatch, fake_rest: FakeRest):
1167
+ first = FakeSocket()
1168
+ client, _ = _setup_reconnecting(monkeypatch, fake_rest, _sequence(FakeConnection(first)))
1169
+ parked = Event()
1170
+
1171
+ async def parked_sleep(_delay):
1172
+ parked.set()
1173
+ await Event().wait() # park the supervisor in its backoff
1174
+
1175
+ monkeypatch.setattr("pybluecurrent.client.sleep", parked_sleep)
1176
+ client.queue = _RecordingQueue(client)
1177
+ async with client:
1178
+ first.close()
1179
+ await wait_for(parked.wait(), 1)
1180
+ assert client.consumer is None # no handler left to send a sentinel on the way out
1181
+ assert client.queue.closed_at_sentinel[-1]
1182
+
1081
1183
 
1082
1184
  class TestLogging:
1083
1185
  """Logger naming, credential redaction, and coverage of the reconnect failure paths."""
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "0.4.0",
3
- "distance": 0,
4
- "node": "gf95de5f790263d92fa4a81a86dfbd93f4b291164",
5
- "dirty": false,
6
- "branch": "HEAD",
7
- "node_date": "2026-09-11"
8
- }
File without changes
File without changes
File without changes
File without changes