32
32
33
33
34
34
class YRoom :
35
- clients : list
35
+ clients : set [Websocket ]
36
+ fork_ydocs : set [Doc ]
36
37
ydoc : Doc
37
38
ystore : BaseYStore | None
38
39
ready_event : Event
@@ -51,6 +52,7 @@ def __init__(
51
52
ystore : BaseYStore | None = None ,
52
53
exception_handler : Callable [[Exception , Logger ], bool ] | None = None ,
53
54
log : Logger | None = None ,
55
+ ydoc : Doc | None = None ,
54
56
):
55
57
"""Initialize the object.
56
58
@@ -74,13 +76,14 @@ def __init__(
74
76
returns True if the exception was handled.
75
77
log: An optional logger.
76
78
"""
77
- self .ydoc = Doc ()
79
+ self .ydoc = Doc () if ydoc is None else ydoc
78
80
self .awareness = Awareness (self .ydoc )
79
81
self .ready_event = Event ()
80
82
self .ready = ready
81
83
self .ystore = ystore
82
84
self .log = log or getLogger (__name__ )
83
- self .clients = []
85
+ self .clients = set ()
86
+ self .fork_ydocs = set ()
84
87
self ._on_message = None
85
88
self .exception_handler = exception_handler
86
89
self ._stopped = Event ()
@@ -147,13 +150,19 @@ async def _broadcast_updates(self):
147
150
return
148
151
# broadcast internal ydoc's update to all clients, that includes changes from the
149
152
# clients and changes from the backend (out-of-band changes)
150
- for client in self .clients :
151
- try :
152
- self .log .debug ("Sending Y update to client with endpoint: %s" , client .path )
153
- message = create_update_message (update )
154
- self ._task_group .start_soon (client .send , message )
155
- except Exception as exception :
156
- self ._handle_exception (exception )
153
+ for ydoc in self .fork_ydocs :
154
+ ydoc .apply_update (update )
155
+
156
+ if self .clients :
157
+ message = create_update_message (update )
158
+ for client in self .clients :
159
+ try :
160
+ self .log .debug (
161
+ "Sending Y update to remote client with endpoint: %s" , client .path
162
+ )
163
+ self ._task_group .start_soon (client .send , message )
164
+ except Exception as exception :
165
+ self ._handle_exception (exception )
157
166
if self .ystore :
158
167
try :
159
168
self ._task_group .start_soon (self .ystore .write , update )
@@ -245,7 +254,7 @@ async def serve(self, websocket: Websocket):
245
254
"""
246
255
try :
247
256
async with create_task_group () as tg :
248
- self .clients .append (websocket )
257
+ self .clients .add (websocket )
249
258
sync_message = create_sync_message (self .ydoc )
250
259
self .log .debug (
251
260
"Sending %s message to endpoint: %s" ,
@@ -296,6 +305,6 @@ async def serve(self, websocket: Websocket):
296
305
)
297
306
tg .start_soon (client .send , message )
298
307
# remove this client
299
- self .clients = [ c for c in self . clients if c != websocket ]
308
+ self .clients . remove ( websocket )
300
309
except Exception as exception :
301
310
self ._handle_exception (exception )
0 commit comments