diff --git a/tests/test_windows_launcher.py b/tests/test_windows_launcher.py index c68800e..8422378 100644 --- a/tests/test_windows_launcher.py +++ b/tests/test_windows_launcher.py @@ -63,3 +63,36 @@ def test_the_windows_launcher_runs_the_command_line(repo, tmp_path, monkeypatch) p = subprocess.run([git_sh() or "sh", ensure_launcher(env), "--cwd", repo, "config", "set", "spiral=off"], env=run_env, capture_output=True, text=True) assert p.returncode == 0, p.stderr + + +def test_sessions_that_write_the_launcher_at_once_from_one_process_do_not_collide( + tmp_path, monkeypatch): + """A Hermes gateway runs every session's hooks as threads of one process, and the first + prompts of several sessions write the launcher together. Named by the process alone, their + temporary files were one file: the first rename took it, and the rest failed, each failure a + line in errors.log.""" + import threading + monkeypatch.setattr(paths, "_WINDOWS", False) + together, first, lock = threading.Barrier(4, timeout=10), set(), threading.Lock() + real = os.replace + + def replace(src, dst): + with lock: + waits = threading.get_ident() not in first + first.add(threading.get_ident()) + if waits: # every writer is between its write and its rename + together.wait() # (a retry on Windows renames again, unhindered) + return real(src, dst) + monkeypatch.setattr(os, "replace", replace) + env, errors = _env(tmp_path), [] + + def write(): + try: + ensure_launcher(env) + except OSError as e: + errors.append(e) + threads = [threading.Thread(target=write) for _ in range(4)] + [t.start() for t in threads] + [t.join() for t in threads] + assert errors == [] + assert sorted(os.listdir(os.path.dirname(paths.launcher_path(env)))) == ["te"] diff --git a/tokeneconomizer/plugin/paths.py b/tokeneconomizer/plugin/paths.py index 7a541e5..2c2774f 100644 --- a/tokeneconomizer/plugin/paths.py +++ b/tokeneconomizer/plugin/paths.py @@ -67,6 +67,8 @@ def ensure_launcher(env=None): changes, as an installed copy's path does across updates.""" import shlex import sys + import threading + from .store import _replace env = os.environ if env is None else env plugin = env.get("TE_PLUGIN_ROOT") target = os.path.join(plugin, "scripts", "te") if plugin else "" @@ -101,13 +103,22 @@ def ensure_launcher(env=None): except OSError: pass os.makedirs(os.path.dirname(launcher), exist_ok=True) - tmp = "%s.%d.tmp" % (launcher, os.getpid()) + # The thread too: one Hermes gateway runs its sessions' hooks as threads of one process, + # and two of them sharing a temporary file would rename it out from under each other. + tmp = "%s.%d.%d.tmp" % (launcher, os.getpid(), threading.get_ident()) # newline="\n": text mode on Windows would end each line with CRLF, and `sh` would pass # the trailing "\r" on as an argument. - with open(tmp, "w", encoding="utf-8", newline="\n") as fh: - fh.write(body) - os.chmod(tmp, 0o700) - os.replace(tmp, launcher) + try: + with open(tmp, "w", encoding="utf-8", newline="\n") as fh: + fh.write(body) + os.chmod(tmp, 0o700) + # Windows refuses to replace a file another thread is reading or replacing. + _replace(tmp, launcher) + finally: + try: + os.unlink(tmp) + except FileNotFoundError: + pass return path