wse-client 2.3.1__tar.gz → 2.3.2__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 (35) hide show
  1. {wse_client-2.3.1 → wse_client-2.3.2}/PKG-INFO +3 -3
  2. {wse_client-2.3.1 → wse_client-2.3.2}/README.md +2 -2
  3. {wse_client-2.3.1 → wse_client-2.3.2}/pyproject.toml +1 -1
  4. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_client.py +5 -0
  5. wse_client-2.3.2/wse_client/_version.py +1 -0
  6. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/client.py +43 -22
  7. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/security.py +6 -9
  8. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/sync_client.py +22 -0
  9. wse_client-2.3.1/wse_client/_version.py +0 -1
  10. {wse_client-2.3.1 → wse_client-2.3.2}/.gitignore +0 -0
  11. {wse_client-2.3.1 → wse_client-2.3.2}/tests/conftest.py +0 -0
  12. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_circuit_breaker.py +0 -0
  13. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_compression.py +0 -0
  14. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_connection_pool.py +0 -0
  15. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_event_sequencer.py +0 -0
  16. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_network_monitor.py +0 -0
  17. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_protocol.py +0 -0
  18. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_rate_limiter.py +0 -0
  19. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_security.py +0 -0
  20. {wse_client-2.3.1 → wse_client-2.3.2}/tests/test_sync_client.py +0 -0
  21. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/__init__.py +0 -0
  22. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/_logging.py +0 -0
  23. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/circuit_breaker.py +0 -0
  24. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/compression.py +0 -0
  25. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/connection.py +0 -0
  26. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/connection_pool.py +0 -0
  27. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/constants.py +0 -0
  28. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/errors.py +0 -0
  29. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/event_sequencer.py +0 -0
  30. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/msgpack_handler.py +0 -0
  31. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/network_monitor.py +0 -0
  32. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/offline_queue.py +0 -0
  33. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/protocol.py +0 -0
  34. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/rate_limiter.py +0 -0
  35. {wse_client-2.3.1 → wse_client-2.3.2}/wse_client/types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wse-client
3
- Version: 2.3.1
3
+ Version: 2.3.2
4
4
  Summary: Python client for WSE (WebSocket Engine) -- real-time event streaming
5
5
  Project-URL: Homepage, https://github.com/silvermpx/wse
6
6
  Project-URL: Documentation, https://github.com/silvermpx/wse/tree/main/python-client
@@ -46,7 +46,7 @@ Python client for [WSE (WebSocket Engine)](https://github.com/niceguy135/wse) -
46
46
  [![Python](https://img.shields.io/pypi/pyversions/wse-client)](https://pypi.org/project/wse-client/)
47
47
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](../LICENSE)
48
48
 
49
- Feature parity with the TypeScript client. Pure Python, no Rust dependency.
49
+ Feature parity with the TS client. Pure Python, no Rust dependency.
50
50
 
51
51
  ## Installation
52
52
 
@@ -246,7 +246,7 @@ ECDH P-256 key exchange with AES-GCM-256 encryption. Requires the `cryptography`
246
246
  pip install wse-client[crypto]
247
247
  ```
248
248
 
249
- Key exchange happens automatically during the WebSocket handshake. All messages are encrypted with per-connection session keys derived via HKDF-SHA256. Wire format is the `E:` prefix + 12-byte IV + ciphertext + 16-byte auth tag, compatible with the TypeScript client and Rust server.
249
+ Key exchange happens automatically during the WebSocket handshake. All messages are encrypted with per-connection session keys derived via HKDF-SHA256. Wire format is the `E:` prefix + 12-byte IV + ciphertext + 16-byte auth tag, compatible with the TS client and Rust server.
250
250
 
251
251
  ### Circuit Breaker
252
252
 
@@ -6,7 +6,7 @@ Python client for [WSE (WebSocket Engine)](https://github.com/niceguy135/wse) -
6
6
  [![Python](https://img.shields.io/pypi/pyversions/wse-client)](https://pypi.org/project/wse-client/)
7
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](../LICENSE)
8
8
 
9
- Feature parity with the TypeScript client. Pure Python, no Rust dependency.
9
+ Feature parity with the TS client. Pure Python, no Rust dependency.
10
10
 
11
11
  ## Installation
12
12
 
@@ -206,7 +206,7 @@ ECDH P-256 key exchange with AES-GCM-256 encryption. Requires the `cryptography`
206
206
  pip install wse-client[crypto]
207
207
  ```
208
208
 
209
- Key exchange happens automatically during the WebSocket handshake. All messages are encrypted with per-connection session keys derived via HKDF-SHA256. Wire format is the `E:` prefix + 12-byte IV + ciphertext + 16-byte auth tag, compatible with the TypeScript client and Rust server.
209
+ Key exchange happens automatically during the WebSocket handshake. All messages are encrypted with per-connection session keys derived via HKDF-SHA256. Wire format is the `E:` prefix + 12-byte IV + ciphertext + 16-byte auth tag, compatible with the TS client and Rust server.
210
210
 
211
211
  ### Circuit Breaker
212
212
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "wse-client"
7
- version = "2.3.1"
7
+ version = "2.3.2"
8
8
  description = "Python client for WSE (WebSocket Engine) -- real-time event streaming"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -17,7 +17,12 @@ from wse_client.types import (
17
17
  @pytest.fixture
18
18
  def client():
19
19
  """Create a client with mocked connection manager."""
20
+ import asyncio
21
+
20
22
  c = AsyncWSEClient("ws://localhost:5006/wse", token="test-jwt")
23
+ # Initialize lazy asyncio primitives (normally done in connect())
24
+ c._event_queue = asyncio.Queue(maxsize=c._queue_size)
25
+ c._server_ready_event = asyncio.Event()
21
26
  # Mock the connection manager to avoid real WebSocket
22
27
  c._connection = MagicMock()
23
28
  c._connection.is_connected = True
@@ -0,0 +1 @@
1
+ __version__ = "2.3.2"
@@ -134,10 +134,10 @@ class AsyncWSEClient:
134
134
  self._network_monitor = NetworkMonitor()
135
135
  self._offline_queue = OfflineQueue(max_size=1000, max_age=3600.0)
136
136
 
137
- # Event queue for async iteration
138
- self._event_queue: asyncio.Queue[WSEEvent | None] = asyncio.Queue(
139
- maxsize=queue_size
140
- )
137
+ # Event queue for async iteration (created lazily in connect() to avoid
138
+ # RuntimeError when instantiated outside a running event loop)
139
+ self._event_queue: asyncio.Queue[WSEEvent | None] | None = None
140
+ self._queue_size = queue_size
141
141
  self._disconnecting = False
142
142
 
143
143
  # Callback handlers: type -> list of handlers
@@ -183,7 +183,8 @@ class AsyncWSEClient:
183
183
 
184
184
  self._connection._on_pong = self._on_transport_pong
185
185
  self._connection._on_ping_sent = lambda: self._network_monitor.record_ping()
186
- self._server_ready_event = asyncio.Event()
186
+ # Created lazily in connect() to avoid RuntimeError outside event loop
187
+ self._server_ready_event: asyncio.Event | None = None
187
188
 
188
189
  # System handler dispatch table (dict lookup = O(1))
189
190
  self._system_handlers: dict[str, Callable[[WSEEvent], None]] = {
@@ -233,6 +234,8 @@ class AsyncWSEClient:
233
234
  return self
234
235
 
235
236
  async def __anext__(self) -> WSEEvent:
237
+ if self._event_queue is None:
238
+ raise StopAsyncIteration
236
239
  event = await self._event_queue.get()
237
240
  if event is None:
238
241
  raise StopAsyncIteration
@@ -242,6 +245,14 @@ class AsyncWSEClient:
242
245
 
243
246
  async def connect(self) -> None:
244
247
  """Connect and wait for server_ready."""
248
+ # Lazily create asyncio primitives (requires running event loop)
249
+ if self._event_queue is None:
250
+ self._event_queue = asyncio.Queue(maxsize=self._queue_size)
251
+ if self._server_ready_event is None:
252
+ self._server_ready_event = asyncio.Event()
253
+ # Clear in case of reconnect (prevents stale set from prior session)
254
+ self._server_ready_event.clear()
255
+
245
256
  await self._connection.connect(self._initial_topics)
246
257
 
247
258
  # Wait for server_ready with timeout
@@ -271,14 +282,15 @@ class AsyncWSEClient:
271
282
  self._offline_queue.clear()
272
283
 
273
284
  # Signal iterator to stop (drop oldest if queue is full)
274
- try:
275
- self._event_queue.put_nowait(None)
276
- except asyncio.QueueFull:
285
+ if self._event_queue is not None:
277
286
  try:
278
- self._event_queue.get_nowait()
279
287
  self._event_queue.put_nowait(None)
280
- except (asyncio.QueueEmpty, asyncio.QueueFull):
281
- pass
288
+ except asyncio.QueueFull:
289
+ try:
290
+ self._event_queue.get_nowait()
291
+ self._event_queue.put_nowait(None)
292
+ except (asyncio.QueueEmpty, asyncio.QueueFull):
293
+ pass
282
294
  try:
283
295
  await self._connection.destroy()
284
296
  finally:
@@ -332,7 +344,7 @@ class AsyncWSEClient:
332
344
  @property
333
345
  def queue_size(self) -> int:
334
346
  """Number of events waiting in the iterator queue."""
335
- return self._event_queue.qsize()
347
+ return self._event_queue.qsize() if self._event_queue else 0
336
348
 
337
349
  # -- Send / Subscribe / Unsubscribe ---------------------------------------
338
350
 
@@ -583,6 +595,8 @@ class AsyncWSEClient:
583
595
  WSEConnectionError: If the connection is closed.
584
596
  asyncio.TimeoutError: If *timeout* expires.
585
597
  """
598
+ if self._event_queue is None:
599
+ raise WSEConnectionError("Not connected")
586
600
  if timeout is not None:
587
601
  event = await asyncio.wait_for(self._event_queue.get(), timeout=timeout)
588
602
  else:
@@ -599,7 +613,8 @@ class AsyncWSEClient:
599
613
 
600
614
  async def force_reconnect(self) -> None:
601
615
  """Force a reconnection (e.g. after detecting degraded quality)."""
602
- self._server_ready_event.clear()
616
+ if self._server_ready_event is not None:
617
+ self._server_ready_event.clear()
603
618
  await self._connection.force_reconnect()
604
619
 
605
620
  async def change_endpoint(self, new_url: str) -> None:
@@ -612,7 +627,8 @@ class AsyncWSEClient:
612
627
  self._connection._url = new_url
613
628
  self._connection._active_endpoint = new_url
614
629
  self._connection._reconnect_attempts = 0
615
- self._server_ready_event.clear()
630
+ if self._server_ready_event is not None:
631
+ self._server_ready_event.clear()
616
632
 
617
633
  # Register with pool if active
618
634
  if self._connection._pool is not None:
@@ -681,7 +697,7 @@ class AsyncWSEClient:
681
697
  "bytes_sent": self._stats.bytes_sent,
682
698
  "reconnect_count": self._stats.reconnect_count,
683
699
  "sequencer": self._sequencer.get_stats(),
684
- "queue_size": self._event_queue.qsize(),
700
+ "queue_size": self._event_queue.qsize() if self._event_queue else 0,
685
701
  "network": {
686
702
  "quality": diag.quality.value,
687
703
  "latency_ms": diag.round_trip_time,
@@ -751,6 +767,8 @@ class AsyncWSEClient:
751
767
  self._invoke_handlers(event)
752
768
 
753
769
  # Enqueue for async iterator
770
+ if self._event_queue is None:
771
+ return
754
772
  try:
755
773
  self._event_queue.put_nowait(event)
756
774
  except asyncio.QueueFull:
@@ -785,7 +803,8 @@ class AsyncWSEClient:
785
803
  "details", {}
786
804
  ).get("connection_id")
787
805
  self._connection.handle_server_ready(conn_id)
788
- self._server_ready_event.set()
806
+ if self._server_ready_event is not None:
807
+ self._server_ready_event.set()
789
808
  self._snapshot_requested = False
790
809
 
791
810
  # Check if server supports recovery (from features in details)
@@ -949,7 +968,7 @@ class AsyncWSEClient:
949
968
  "latency_ms": diag.round_trip_time,
950
969
  "jitter_ms": diag.jitter,
951
970
  },
952
- "queue_size": self._event_queue.qsize(),
971
+ "queue_size": self._event_queue.qsize() if self._event_queue else 0,
953
972
  },
954
973
  priority=MessagePriority.CRITICAL,
955
974
  )
@@ -1033,8 +1052,8 @@ class AsyncWSEClient:
1033
1052
  "bytes_sent": self._stats.bytes_sent,
1034
1053
  },
1035
1054
  "queue_stats": {
1036
- "size": self._event_queue.qsize(),
1037
- "max_size": self._event_queue.maxsize,
1055
+ "size": self._event_queue.qsize() if self._event_queue else 0,
1056
+ "max_size": self._event_queue.maxsize if self._event_queue else 0,
1038
1057
  },
1039
1058
  "diagnostics": {
1040
1059
  "quality": diag.quality.value,
@@ -1093,18 +1112,20 @@ class AsyncWSEClient:
1093
1112
  def _on_state_change(self, state: ConnectionState) -> None:
1094
1113
  if state == ConnectionState.RECONNECTING:
1095
1114
  self._stats.reconnect_count += 1
1096
- self._server_ready_event.clear()
1115
+ if self._server_ready_event is not None:
1116
+ self._server_ready_event.clear()
1097
1117
  self._snapshot_requested = False
1098
1118
  self._sequencer.reset()
1099
1119
  elif state == ConnectionState.CONNECTED:
1100
1120
  pass # record_ping() is called per-heartbeat via on_ping_sent
1101
1121
  elif state == ConnectionState.DISCONNECTED:
1102
- self._server_ready_event.clear()
1122
+ if self._server_ready_event is not None:
1123
+ self._server_ready_event.clear()
1103
1124
  # Signal iterator to stop on terminal disconnect.
1104
1125
  # DISCONNECTED only fires for permanent closes (normal close,
1105
1126
  # going_away). Transient errors go through RECONNECTING, not here.
1106
1127
  # Skip if disconnect() already enqueued the sentinel.
1107
- if not self._disconnecting:
1128
+ if not self._disconnecting and self._event_queue is not None:
1108
1129
  try:
1109
1130
  self._event_queue.put_nowait(None)
1110
1131
  except asyncio.QueueFull:
@@ -37,8 +37,8 @@ except ImportError:
37
37
  from .errors import WSEEncryptionError
38
38
 
39
39
  # Wire constants
40
- HKDF_SALT = b"wse-encryption"
41
- HKDF_INFO = b"aes-gcm-key"
40
+ HKDF_SALT = None # RFC 5869: zero-salt default for ECDH output
41
+ HKDF_INFO = b"wse-encryption/aes-gcm-key"
42
42
  AES_KEY_LEN = 32 # 256 bits
43
43
  GCM_IV_LEN = 12 # 96 bits
44
44
  GCM_TAG_LEN = 16 # 128 bits
@@ -47,7 +47,7 @@ GCM_TAG_LEN = 16 # 128 bits
47
47
  class SecurityManager:
48
48
  """ECDH P-256 + AES-GCM-256 + HMAC-SHA256.
49
49
 
50
- Wire-compatible with the Rust server and TypeScript client.
50
+ Wire-compatible with the Rust server and TS client.
51
51
  Requires ``cryptography`` package (``pip install wse-client[crypto]``).
52
52
  """
53
53
 
@@ -240,16 +240,13 @@ class SecurityManager:
240
240
  except asyncio.CancelledError:
241
241
  return
242
242
 
243
- # Skip rotation when ECDH session is active (matches TS behavior)
244
- if self._aes_key is not None and self._enabled:
245
- logger.debug("Skipping key rotation (ECDH session active)")
246
- continue
247
-
248
243
  try:
244
+ # Signing key rotates regardless of ECDH session state --
245
+ # it is independent of the AES key derived from ECDH
249
246
  self._signing_key = os.urandom(32)
250
247
  self._iv_cache = {}
251
248
  failures = 0
252
- logger.debug("Keys rotated successfully")
249
+ logger.debug("Signing key rotated successfully")
253
250
  except Exception as exc:
254
251
  failures += 1
255
252
  logger.error("Key rotation failed: %s", exc)
@@ -90,6 +90,8 @@ class SyncWSEClient:
90
90
  self._running = False
91
91
  self._connected_event = threading.Event()
92
92
  self._connect_error: Exception | None = None
93
+ self._background_error: Exception | None = None
94
+ self._on_error: Callable[[Exception], Any] | None = None
93
95
 
94
96
  # -- Lifecycle ------------------------------------------------------------
95
97
 
@@ -126,6 +128,20 @@ class SyncWSEClient:
126
128
  self._running = False
127
129
  raise WSEConnectionError(f"Connection failed: {err}") from err
128
130
 
131
+ def set_error_handler(self, handler: Callable[[Exception], Any]) -> None:
132
+ """Set a callback for background loop errors that occur after connect().
133
+
134
+ Without this, errors in the background event loop (e.g. unexpected
135
+ disconnect without reconnect) are only logged. The handler is called
136
+ from the background thread.
137
+ """
138
+ self._on_error = handler
139
+
140
+ @property
141
+ def background_error(self) -> Exception | None:
142
+ """Last error from the background event loop (None if healthy)."""
143
+ return self._background_error
144
+
129
145
  def close(self) -> None:
130
146
  """Disconnect and stop the background thread."""
131
147
  self._running = False
@@ -468,7 +484,13 @@ class SyncWSEClient:
468
484
 
469
485
  except Exception as exc:
470
486
  self._connect_error = exc
487
+ self._background_error = exc
471
488
  logger.error("Client error: %s", exc)
489
+ if self._on_error is not None:
490
+ try:
491
+ self._on_error(exc)
492
+ except Exception:
493
+ pass
472
494
  finally:
473
495
  await self._client.disconnect()
474
496
  self._connected_event.set() # Unblock connect() if still waiting
@@ -1 +0,0 @@
1
- __version__ = "2.3.1"
File without changes
File without changes