The session folders leave after the reapers, not on the shutdown thread
The downloads root and the upload root were removed by after-shutdown steps on the juggler-shutdown thread, which the user's stop and the context exit wait for; a removal of a profile-sized folder took 0.4 to 2.5 s on Windows. _reaped.after_the_reapers is now the one place for "run this step after the session's reapers": once, after the last one, and at once when there is none. final_reap runs on it, and so do the two folder removals (Server.after_reapers, which reads the session tokens of the launches when the shutdown runs the step). The no-reaper route of SessionRemoval.after_shutdown is unchanged.
This commit is contained in:
1 parent
ef3ba1c862
commit
27b3c7f2a7
4 files changed
+125
-22
No files matched your search
@@ -43,7 +43,11 @@ class SessionRemoval:
|
||||
self._remove()
|
||||
|
||||
def after_shutdown(self) -> None:
|
||||
"""The step the server runs once its hooks have: the removal itself, unless the reaper has been handed it."""
|
||||
"""The step the server runs once its hooks have: the removal itself, unless the reaper has been handed it.
|
||||
|
||||
⛔ ON THIS ROUTE THERE IS NO LAUNCH THREAD TO HAND THE STEP TO: `close` did not hand it, because the connection has no
|
||||
reaper (a core before the one that makes them, or a close that raised), so the removal runs where it is, here. The
|
||||
session's other steps (`after_the_reapers`) are the ones that wait for the reapers."""
|
||||
with self._lock:
|
||||
if self._handed:
|
||||
return
|
||||
@@ -90,22 +94,26 @@ def wait_reaped(token: Any, timeout: Optional[float] = None) -> bool:
|
||||
return done
|
||||
|
||||
|
||||
def final_reap(guard: Any, token: Any) -> int:
|
||||
"""The teardown's last step: whatever still carries the session's ``token`` is ended.
|
||||
def after_the_reapers(step: Callable[[], Any], *tokens: Any, forget: bool = False) -> Any:
|
||||
"""Runs ``step`` once, after the last of the reapers of the launches made under ``tokens`` (a `SessionToken` or its
|
||||
value each), and returns at once with None when it was handed over. With no reaper at all it runs now, on the caller,
|
||||
and its result is returned: the way it always ran.
|
||||
|
||||
⛔ WHEN THE SESSION'S LAUNCHES HAVE A REAPER THE LAST REAP IS ITS TO RUN. `guard.reap` ends the session's tree at once, and
|
||||
what is left at that moment is the sender of the shutdown pings: ended here, the pings were lost and the grace the reaper
|
||||
gives it was for nothing. The reap is handed to the reapers (`then`), so it runs after the grace and the end of what is left,
|
||||
and it is the net it always was for what the reaper did not end. Returns at once then, with 0: nothing is waited for.
|
||||
⛔ THE ONE PLACE FOR "AFTER THE SESSION'S REAPERS". A step that the server's shutdown thread or the user's close would run
|
||||
waits there for what the reaper waits for (the sender of the shutdown pings, the tree), and a folder's removal is as slow
|
||||
as the disk. Handed to the reapers (`then`) it runs on the thread that ends the tree, after the grace, and nothing is
|
||||
waited for. Nothing here assumes which thread runs the step: that is `Reaper.then`'s to say.
|
||||
|
||||
With no reaper (a core before the one that makes them, a launch that failed before it had one, an error path that never
|
||||
reached the shutdown) it runs now, as it always did. Never raises on the reapers' side; the guard's own errors reach the
|
||||
caller as they did."""
|
||||
value = getattr(token, "value", token)
|
||||
``forget``: the reapers of this snapshot are taken out of the tokens' entries with the step (even when it raises): a
|
||||
process that opens sessions without end (the server) would keep one entry per session, with its reapers and their trees.
|
||||
Only the reapers of THIS snapshot go: a launch registered under the same token meanwhile keeps its own. Left False, the
|
||||
entries stay for `wait_reaped`, which is what joins the reapers and takes them out. Never raises on the reapers' side;
|
||||
the step's own errors reach whoever runs it."""
|
||||
values = [getattr(token, "value", token) for token in tokens]
|
||||
with _lock:
|
||||
reapers = list(_reapers.get(value, ()))
|
||||
reapers = [r for value in values for r in _reapers.get(value, ())]
|
||||
if not reapers:
|
||||
return guard.reap(token)
|
||||
return step()
|
||||
pending = [len(reapers)]
|
||||
gate = threading.Lock()
|
||||
|
||||
@@ -115,16 +123,30 @@ def final_reap(guard: Any, token: Any) -> int:
|
||||
if pending[0]:
|
||||
return
|
||||
try:
|
||||
guard.reap(token)
|
||||
step()
|
||||
finally:
|
||||
# ⛔ THE ENTRY GOES WITH THE LAST REAP: a process that opens sessions without end (the server) would keep one per
|
||||
# session, with its reapers and their trees. Only the reapers of THIS snapshot are taken out: a launch registered
|
||||
# under the same token meanwhile keeps its own.
|
||||
_forget(value, reapers)
|
||||
if forget:
|
||||
for value in values:
|
||||
_forget(value, reapers)
|
||||
|
||||
for reaper in reapers:
|
||||
reaper.then(after_the_last)
|
||||
return 0
|
||||
return None
|
||||
|
||||
|
||||
def final_reap(guard: Any, token: Any) -> int:
|
||||
"""The teardown's last step: whatever still carries the session's ``token`` is ended.
|
||||
|
||||
⛔ WHEN THE SESSION'S LAUNCHES HAVE A REAPER THE LAST REAP IS ITS TO RUN. `guard.reap` ends the session's tree at once, and
|
||||
what is left at that moment is the sender of the shutdown pings: ended here, the pings were lost and the grace the reaper
|
||||
gives it was for nothing. The reap is handed to the reapers (`after_the_reapers`), so it runs after the grace and the end of
|
||||
what is left, and it is the net it always was for what the reaper did not end. Returns at once then, with 0: nothing is
|
||||
waited for.
|
||||
|
||||
With no reaper (a core before the one that makes them, a launch that failed before it had one, an error path that never
|
||||
reached the shutdown) it runs now, as it always did. Never raises on the reapers' side; the guard's own errors reach the
|
||||
caller as they did."""
|
||||
return after_the_reapers(lambda: guard.reap(token), token, forget=True) or 0
|
||||
|
||||
|
||||
def _forget(value: str, reapers: List[Any]) -> None:
|
||||
|
||||
@@ -39,6 +39,7 @@ import time
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from . import perimeter, variants
|
||||
from ._reaped import after_the_reapers
|
||||
from ._threads import ThreadStarter
|
||||
# One class for a target that is gone, raised here for a disposed object and
|
||||
# by the connection for a closed pipe. Defined there, the lower layer.
|
||||
@@ -275,6 +276,8 @@ class Server:
|
||||
self._on_shutdown: list = []
|
||||
#: What `shutdown` runs after every hook. See `after_shutdown`.
|
||||
self._after_shutdown: list = []
|
||||
#: The session tokens of the launches this server made, in order: what `after_reapers` waits for.
|
||||
self._session_tokens: list = []
|
||||
self._starter: Optional[ThreadStarter] = None
|
||||
self._starter_lock = threading.Lock()
|
||||
self._is_shut_down = False
|
||||
@@ -443,6 +446,21 @@ class Server:
|
||||
"""
|
||||
self._after_shutdown.append(step)
|
||||
|
||||
def note_session_token(self, token: Any) -> None:
|
||||
"""A launch was made under ``token`` (a `SessionToken` or its value): its reaper is one of those `after_reapers` waits for."""
|
||||
value = getattr(token, "value", token)
|
||||
if value and value not in self._session_tokens:
|
||||
self._session_tokens.append(value)
|
||||
|
||||
def after_reapers(self, step: Callable[[], None]) -> None:
|
||||
"""Like `after_shutdown`, for a step that is slow or waits for something (a folder's removal): it is run once the
|
||||
session's reapers are done with the launches (`_reaped.after_the_reapers`), never on the shutdown thread that the user's
|
||||
stop waits for. With no reaper it runs there, as `after_shutdown` runs it.
|
||||
|
||||
⛔ THE TOKENS ARE READ WHEN THE SHUTDOWN RUNS THE STEP, not now: the folders are made by a context, after the launch
|
||||
that gives the reaper its token, and the reaper itself exists only once the hooks have closed the connection."""
|
||||
self.after_shutdown(lambda: after_the_reapers(step, *self._session_tokens))
|
||||
|
||||
def shutdown(self) -> None:
|
||||
for hook in reversed(self._on_shutdown):
|
||||
try:
|
||||
|
||||
@@ -5972,7 +5972,7 @@ class BrowserDispatcher(Dispatcher):
|
||||
if root is None:
|
||||
import shutil
|
||||
root = self._downloads_root = tempfile.mkdtemp(prefix="invpw-downloads-")
|
||||
self.server.after_shutdown(
|
||||
self.server.after_reapers(
|
||||
lambda: shutil.rmtree(root, ignore_errors=True))
|
||||
path = os.path.join(root, context_id or "default")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
@@ -6221,7 +6221,9 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
files = SessionFiles(params.get("userDataDir"), environment)
|
||||
# ⛔ WITH A CORE THAT GIVES THE LAUNCH A REAPER the removal is handed to it once `conn.close` has returned (see
|
||||
# `_reaped`); without one it runs here, after the hooks, as before.
|
||||
removal = SessionRemoval(files.remove, getattr(getattr(files, "token", None), "value", ""))
|
||||
session_token = getattr(getattr(files, "token", None), "value", "")
|
||||
removal = SessionRemoval(files.remove, session_token)
|
||||
self.server.note_session_token(session_token)
|
||||
self.server.after_shutdown(removal.after_shutdown)
|
||||
env, profile = files.env, files.profile
|
||||
# ⛔ THE TYPING SEED TRAVELS IN THE PREFS AND IS TAKEN OUT AGAIN HERE,
|
||||
@@ -6372,7 +6374,7 @@ class JugglerServer(Server):
|
||||
if root is None:
|
||||
root = tempfile.mkdtemp(prefix="invisible_upload_")
|
||||
self._upload_root = root
|
||||
self.after_shutdown(lambda: remove_profile(root))
|
||||
self.after_reapers(lambda: remove_profile(root))
|
||||
path = os.path.join(tempfile.mkdtemp(dir=root), name)
|
||||
with open(path, "wb") as out:
|
||||
out.write(base64.b64decode(payload.get("buffer") or ""))
|
||||
|
||||
@@ -9,6 +9,7 @@ registered with `reaper.then` and does not run inside the shutdown; with a core
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
@@ -171,3 +172,63 @@ def test_wait_reaped_says_false_at_its_timeout():
|
||||
finally:
|
||||
_reaped._reapers.pop("slow-session", None)
|
||||
release.set()
|
||||
|
||||
|
||||
def _the_session_folders(server):
|
||||
"""Makes the two folders a session keeps beside its profile, the way a context and a file upload make them: the
|
||||
downloads root (`BrowserDispatcher._downloads_dir`) and the upload root (`stage_upload`). Returns both roots."""
|
||||
holder = type("Holder", (), {"_downloads_root": None, "server": server})()
|
||||
module.BrowserDispatcher._downloads_dir(holder, "ctx-1")
|
||||
uploaded = server.stage_upload({"name": "a.txt", "buffer": ""})
|
||||
downloads = holder._downloads_root
|
||||
uploads = server._upload_root
|
||||
assert os.path.isdir(downloads) and os.path.isdir(uploads) and os.path.isfile(uploaded)
|
||||
return downloads, uploads
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_with_a_reaper_alive_the_shutdown_leaves_the_downloads_and_upload_folders_to_it(monkeypatch, tmp_path):
|
||||
engine = _Engine(_Reaper)
|
||||
server, files = _launched(monkeypatch, engine, tmp_path)
|
||||
downloads, uploads = _the_session_folders(server)
|
||||
try:
|
||||
server.shutdown()
|
||||
assert os.path.isdir(downloads), "the shutdown thread removed the downloads root while the reaper was alive"
|
||||
assert os.path.isdir(uploads), "the shutdown thread removed the upload root while the reaper was alive"
|
||||
assert files.removed == 0
|
||||
finally:
|
||||
engine.reaper.finish()
|
||||
_reaped.wait_reaped(TOKEN, timeout=5)
|
||||
for root in (downloads, uploads):
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_once_the_reaper_is_released_the_two_folders_are_gone_when_wait_reaped_returns(monkeypatch, tmp_path):
|
||||
engine = _Engine(_Reaper)
|
||||
server, files = _launched(monkeypatch, engine, tmp_path)
|
||||
downloads, uploads = _the_session_folders(server)
|
||||
try:
|
||||
server.shutdown()
|
||||
assert len(engine.reaper.steps) == 3, "the removal and the two folders are the reaper's steps"
|
||||
assert _reaped.wait_reaped(TOKEN, timeout=5) is True
|
||||
assert not os.path.exists(downloads)
|
||||
assert not os.path.exists(uploads)
|
||||
assert files.removed == 1
|
||||
finally:
|
||||
for root in (downloads, uploads):
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_with_no_reaper_the_two_folders_are_gone_when_the_shutdown_returns(monkeypatch, tmp_path):
|
||||
engine = _Engine(None)
|
||||
server, files = _launched(monkeypatch, engine, tmp_path)
|
||||
downloads, uploads = _the_session_folders(server)
|
||||
try:
|
||||
server.shutdown()
|
||||
assert not os.path.exists(downloads), "with no reaper nobody else removes the downloads root"
|
||||
assert not os.path.exists(uploads), "with no reaper nobody else removes the upload root"
|
||||
finally:
|
||||
for root in (downloads, uploads):
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
Reference in new issue
Block a user