11from __future__ import annotations
2+ import traceback
23
34import json
45import ssl
910from threading import Lock
1011from collections .abc import Iterator
1112
13+ from scratchattach .cloud import cloud as cloud_module
14+
1215if TYPE_CHECKING :
1316 from _typeshed import SupportsRead
1417else :
@@ -173,7 +176,12 @@ class WebSocketEventStream(EventStream):
173176
174177 def __init__ (self , cloud : BaseCloud ):
175178 super ().__init__ ()
176- self .source_cloud = type (cloud )(project_id = cloud .project_id )
179+ # NOTE: maybe consider using copy.copy here (copy.deepcopy doesn't work as you cannot deepcopy a Thread)
180+ cloud_type = type (cloud )
181+ if cloud_type is cloud_module .CustomCloud :
182+ self .source_cloud = cloud_type (project_id = cloud .project_id , cloud_host = cloud .cloud_host )
183+ else :
184+ self .source_cloud = cloud_type (project_id = cloud .project_id )
177185 self .source_cloud ._session = cloud ._session
178186 self .source_cloud .cookie = cloud .cookie
179187 self .source_cloud .header = cloud .header
@@ -217,7 +225,6 @@ def read(self, amount: int = -1) -> Iterator[dict[str, Any]]:
217225 done = False
218226 # print("Getting data...")
219227 with self .reading :
220- # print("Getting data...", end_time is None, end_time > time.time(), end_time is None or end_time > time.time())
221228 while not done :
222229 # print("Getting data...")
223230 try :
@@ -229,11 +236,18 @@ def read(self, amount: int = -1) -> Iterator[dict[str, Any]]:
229236 self .receive_new (timeout = timeout_end - time .time () if has_timeout else None )
230237 if not self .packets_left :
231238 continue
232- yield json .loads (self .packets_left .pop (0 ))
233239 i += 1
240+ yield json .loads (self .packets_left .pop (0 ))
234241 done = True
242+ except json .JSONDecodeError as e :
243+ # this could happen e.g. when the scratchattach server sends the message
244+ # "This server uses @TimMcCool's scratchattach 2.0.0"
245+ warnings .warn (f"Invalid JSON sent from server: { e } " )
235246 except Exception :
236- # traceback.print_exc()
247+ # NOTE: at the very least for `except Exception`, let's print the traceback
248+ # ideally we would never even use `except Exception`. Maybe this is technical debt.
249+ # TODO: investigate what the exception we actually want to catch here
250+ traceback .print_exc ()
237251 self .source_cloud .reconnect ()
238252
239253 def __del__ (self ):
0 commit comments