okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-agent3 c99896ae6 (status, goal and time-skip events and backend, time-skip keepalive and stop, atomic.py) into f-split-intf9bfe8bc1

main
1.7 KiB42 linesraw
1"""Replace a file that another program may be reading, on Windows as well as everywhere else.
2
3A job record (a Time-skip `run.json`, a tuning `job.json`) is rewritten at every phase and READ by the app's host every couple of seconds.
4On Windows, `os.replace` onto a file that is open in another process fails with PermissionError ("Access is denied") for as long as the
5reader holds it. That is a split second, but a job saves many times, so a Time-skip or a tune died at random with that error. The fix is
6to wait that split second and try again; any other error, and a PermissionError that does not go away, is raised as before.
7"""
8
9from __future__ import annotations
10
11import os
12import time
13from pathlib import Path
14from typing import Union
15
16PathLike = Union[str, "os.PathLike[str]"]
17
18#: how long a held file is waited for, in total (seconds) and between tries
19PATIENCE_S = 5.0
20STEP_S = 0.02
21
22
23def replace(src: PathLike, dst: PathLike, *, patience: float = PATIENCE_S, sleep=time.sleep, clock=time.monotonic) -> None:
24    deadline = clock() + patience
25    step = STEP_S
26    while True:
27        try:
28            os.replace(src, dst)
29            return
30        except PermissionError:
31            if os.name != "nt" or clock() >= deadline:
32                raise
33            sleep(step)
34            step = min(step * 1.5, 0.25)
35
36
37def write_text(path: PathLike, text: str, *, encoding: str = "utf-8") -> None:
38    """Write `text` to `path` through a neighbouring temporary file, so a reader never sees half a record."""
39    target = Path(path)
40    tmp = target.with_suffix(target.suffix + ".tmp") if target.suffix else target.with_name(target.name + ".tmp")
41    tmp.write_text(text, encoding=encoding)
42    replace(tmp, target)