@@ -157,7 +157,7 @@ def call_watcher(o, k):
157
157
if callable (watcher ):
158
158
watcher (getattr (o , k ))
159
159
160
- all = defaultdict (lambda : set ([] ))
160
+ all = defaultdict (lambda : set ())
161
161
KEY_ATOMIC = '_v_ATOMIC'
162
162
async def broadcast_update (id , k , v ):
163
163
a = all [id ].copy ()
@@ -182,16 +182,28 @@ def next_instance_id():
182
182
return str (_previd [0 ])
183
183
184
184
async def handleClient (websocket , path ):
185
- # TODO: cleanup g_instances (on socket disconnect at least)
185
+ inited = None
186
+ def cleanup ():
187
+ if inited is None : return
188
+ if id != 'ROOT' and id in g_instances :
189
+ del g_instances [id ]
190
+ if websocket in all [inited ]:
191
+ all [inited ].remove (websocket )
192
+ if len (all [inited ]) == 0 :
193
+ del all [inited ]
186
194
try :
187
195
while True :
196
+ print ({k :len (all [k ]) for k in all })
188
197
comm = await websocket .recv ()
189
198
if comm == 'INIT' or comm == 'INFO' :
190
199
clss_name = await websocket .recv ()
200
+ if inited is not None :
201
+ info ('ERR' , 'Tentative double init/info' , clss_name )
191
202
info ('IN' , comm , clss_name )
192
203
if clss_name == 'ROOT' :
193
- all [clss_name ].add (websocket )
194
204
id = clss_name
205
+ all [id ].add (websocket )
206
+ inited = id
195
207
o = g_instances [id ]
196
208
clss = type (o )
197
209
o ._v_just_schedule = False
@@ -202,6 +214,7 @@ async def handleClient(websocket, path):
202
214
o = clss ()
203
215
id = next_instance_id ()
204
216
all [id ].add (websocket )
217
+ inited = id
205
218
setattr (o , '__id' , id )
206
219
setup_model_object_infra (o )
207
220
g_instances [id ] = o
@@ -265,6 +278,7 @@ async def handleClient(websocket, path):
265
278
info ('ERR' , 'Not a JSON value (or watcher error) for key' , k , '->' , v , '//' , e )
266
279
info_exception ('ERR' , ' ' )
267
280
except websockets .ConnectionClosed as e :
281
+ cleanup ()
268
282
if e .code == 1001 :
269
283
info ('END' , 'disconnected' )
270
284
elif e .code == 1005 :
@@ -273,6 +287,7 @@ async def handleClient(websocket, path):
273
287
info ('END' , e )
274
288
info_exception ('ENDx' )
275
289
except Exception as e :
290
+ cleanup ()
276
291
info ('END' , e )
277
292
info_exception ('ENDe' )
278
293
return handleClient
0 commit comments