From cafd8b62aa59fdd1c0e7a70b0c43639cd8df46db Mon Sep 17 00:00:00 2001 From: 0xdefimaster <111867946+0xdefimaster@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:39:40 +0300 Subject: [PATCH 1/2] fix(ws): handle non-object JSON messages safely --- lighter/ws_client.py | 64 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/lighter/ws_client.py b/lighter/ws_client.py index 0638875..ecb5df9 100644 --- a/lighter/ws_client.py +++ b/lighter/ws_client.py @@ -1,11 +1,14 @@ + import json from websockets.sync.client import connect from websockets.client import connect as connect_async from lighter.configuration import Configuration from lighter.endpoint_profiles import join_url import logging + logger = logging.getLogger(__name__) + class WsClient: def __init__( self, @@ -48,6 +51,9 @@ def on_message(self, ws, message): if isinstance(message, str): message = json.loads(message) + if not isinstance(message, dict): + return + message_type = message.get("type") if message_type == "connected": @@ -69,7 +75,12 @@ def on_message(self, ws, message): self.handle_unhandled_message(message) async def on_message_async(self, ws, message): - message = json.loads(message) + if isinstance(message, str): + message = json.loads(message) + + if not isinstance(message, dict): + return + message_type = message.get("type") if message_type == "connected": @@ -108,66 +119,95 @@ def handle_subscribed_order_book(self, message): market_id = message["channel"].split(":")[1] self.order_book_states[market_id] = message["order_book"] if self.on_order_book_update: - self.on_order_book_update(market_id, self.order_book_states[market_id]) + self.on_order_book_update( + market_id, + self.order_book_states[market_id], + ) def handle_update_order_book(self, message): market_id = message["channel"].split(":")[1] self.update_order_book_state(market_id, message["order_book"]) if self.on_order_book_update: - self.on_order_book_update(market_id, self.order_book_states[market_id]) + self.on_order_book_update( + market_id, + self.order_book_states[market_id], + ) def update_order_book_state(self, market_id, order_book): self.update_orders( - order_book["asks"], self.order_book_states[market_id]["asks"] + order_book["asks"], + self.order_book_states[market_id]["asks"], ) self.update_orders( - order_book["bids"], self.order_book_states[market_id]["bids"] + order_book["bids"], + self.order_book_states[market_id]["bids"], ) def update_orders(self, new_orders, existing_orders): for new_order in new_orders: is_new_order = True - # iterate over a copy so removal is safe + + # Iterate over a copy so removal is safe existing_order_copy = existing_orders[:] + for existing_order in existing_order_copy: if new_order["price"] == existing_order["price"]: is_new_order = False existing_order["size"] = new_order["size"] + if float(new_order["size"]) == 0: existing_orders.remove(existing_order) if is_new_order: existing_orders.append(new_order) - # final cleanup (in-place) + # Final cleanup (in-place) existing_orders[:] = [ - order for order in existing_orders if float(order["size"]) > 0 + order + for order in existing_orders + if float(order["size"]) > 0 ] def handle_subscribed_account(self, message): account_id = message["channel"].split(":")[1] self.account_states[account_id] = message + if self.on_account_update: - self.on_account_update(account_id, self.account_states[account_id]) + self.on_account_update( + account_id, + self.account_states[account_id], + ) def handle_update_account(self, message): account_id = message["channel"].split(":")[1] self.account_states[account_id] = message + if self.on_account_update: - self.on_account_update(account_id, self.account_states[account_id]) + self.on_account_update( + account_id, + self.account_states[account_id], + ) def handle_unhandled_message(self, message): if self.on_unhandled_message: self.on_unhandled_message(message) else: - logger.warning("Unhandled message type %r: %s", message.get("type"), message) + logger.warning( + "Unhandled message type %r: %s", + message.get("type"), + message, + ) def handle_shutdown(self, message): close_in_ms = message.get("close_in_ms", 0) + if self.on_shutdown: self.on_shutdown(close_in_ms) else: - print(f"Server shutting down, connection closes in {close_in_ms}ms") + print( + f"Server shutting down, " + f"connection closes in {close_in_ms}ms" + ) def on_error(self, ws, error): raise Exception(f"Error: {error}") From 1397d5a996649b8c21b722f1195350aac22e67c5 Mon Sep 17 00:00:00 2001 From: 0xdefimaster <111867946+0xdefimaster@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:45:23 +0300 Subject: [PATCH 2/2] Add files via upload --- test/test_ws_client_non_object.py | 62 +++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 test/test_ws_client_non_object.py diff --git a/test/test_ws_client_non_object.py b/test/test_ws_client_non_object.py new file mode 100644 index 0000000..28cc037 --- /dev/null +++ b/test/test_ws_client_non_object.py @@ -0,0 +1,62 @@ +"""Regression tests for non-object JSON WS frames (issue #123). No network.""" + +import json +import unittest +from unittest.mock import AsyncMock, Mock + +from lighter.ws_client import WsClient + + +NON_OBJECT_FRAMES = ('"heartbeat"', 'null', '[]', '42', 'true') + + +class TestWsClientNonObjectFrames(unittest.TestCase): + def setUp(self): + self.unhandled = Mock() + self.client = WsClient( + ws_url="wss://example.invalid/stream", + order_book_ids=[1], + on_unhandled_message=self.unhandled, + ) + + def test_sync_ignores_non_object_json(self): + ws = Mock() + for frame in NON_OBJECT_FRAMES: + with self.subTest(frame=frame): + self.client.on_message(ws, frame) + self.unhandled.assert_not_called() + ws.send.assert_not_called() + + def test_sync_ping_responds_normally(self): + ws = Mock() + self.client.on_message(ws, json.dumps({"type": "ping"})) + ws.send.assert_called_once_with(json.dumps({"type": "pong"})) + + +class TestWsClientAsyncNonObjectFrames(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.unhandled = Mock() + self.client = WsClient( + ws_url="wss://example.invalid/stream", + order_book_ids=[1], + on_unhandled_message=self.unhandled, + ) + + async def test_async_ignores_non_object_json(self): + ws = Mock() + ws.send = AsyncMock() + for frame in NON_OBJECT_FRAMES: + with self.subTest(frame=frame): + await self.client.on_message_async(ws, frame) + self.unhandled.assert_not_called() + ws.send.assert_not_awaited() + + async def test_async_ping_responds_normally(self): + ws = Mock() + ws.send = AsyncMock() + await self.client.on_message_async(ws, json.dumps({"type": "ping"})) + ws.send.assert_awaited_once_with(json.dumps({"type": "pong"})) + + +if __name__ == "__main__": + unittest.main()