@@ -45,6 +45,9 @@ def __init__(
45
45
46
46
self ._cleaner : asyncio .Task | None = None
47
47
48
+ # the current `self._maybe_save_document()` task.
49
+ self ._maybe_save_task : asyncio .Task | None = None
50
+
48
51
# the task currently saving to disk via FileLoader, if any.
49
52
self ._save_task : asyncio .Task | None = None
50
53
@@ -219,7 +222,17 @@ def _on_document_change(self, target: str, event: Any) -> None:
219
222
document. This tasks are debounced (60 seconds by default) so we
220
223
need to cancel previous tasks before creating a new one.
221
224
"""
222
- asyncio .create_task (self ._maybe_save_document ())
225
+ if self ._maybe_save_task and not self ._maybe_save_task .done ():
226
+ # only one `self._maybe_save_task` needs to be running.
227
+ # if this method is called after the save delay, then we need to set
228
+ # `self._should_resave` to `True` to reschedule
229
+ # `self._maybe_save_document()` on the event loop after the current
230
+ # `self._maybe_save_task` completes.
231
+ if not self ._waiting_to_save :
232
+ self ._should_resave = True
233
+ return
234
+
235
+ self ._maybe_save_task = asyncio .create_task (self ._maybe_save_document ())
223
236
224
237
async def _maybe_save_document (self ) -> None :
225
238
"""
@@ -234,19 +247,6 @@ async def _maybe_save_document(self) -> None:
234
247
# TODO: fix this; if _save_delay is unset, then this never writes to disk
235
248
return
236
249
237
- if self ._waiting_to_save :
238
- # if a previously spawned `self._maybe_save_document()` task is
239
- # waiting to save, then that task will save the Ydoc within
240
- # `self._save_delay` seconds. therefore we can return early.
241
- return
242
-
243
- if self ._save_task and not self ._save_task .done ():
244
- # if we are currently saving, then set the `_should_resave`
245
- # flag. this indicates to the currently running `self._save_task`
246
- # that it should re-call this method after it completes.
247
- self ._should_resave = True
248
- return
249
-
250
250
# save after `self._save_delay` seconds of inactivity
251
251
self ._waiting_to_save = True
252
252
await asyncio .sleep (self ._save_delay )
@@ -271,7 +271,7 @@ async def _maybe_save_document(self) -> None:
271
271
272
272
if self ._should_resave :
273
273
self ._should_resave = False
274
- asyncio .create_task (self ._maybe_save_document ())
274
+ self . _maybe_save_task = asyncio .create_task (self ._maybe_save_document ())
275
275
276
276
except asyncio .CancelledError :
277
277
return
0 commit comments