From 5731675153097c396e843b5ab96c5f332c6e5c8e Mon Sep 17 00:00:00 2001 From: host Date: Mon, 26 Oct 2026 00:16:54 +0800 Subject: [PATCH] host: real-backup --- host.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/host.py b/host.py index a6e0008..807339e 100644 --- a/host.py +++ b/host.py @@ -326,7 +326,8 @@ def _state_lock(path, exclusive=True): def _read_state_file(path): if os.path.exists(path): try: - return json.load(open(path)) + with open(path) as f: + return json.load(f) except Exception: pass return {"tasks": {}, "automations": []} @@ -356,7 +357,22 @@ def save_state(path, state): if k not in ("tasks", "automations"): merged[k] = v tmp = f"{path}.tmp.{os.getpid()}" - json.dump(merged, open(tmp, "w"), indent=2, ensure_ascii=False) + with open(tmp, "w") as f: + json.dump(merged, f, indent=2, ensure_ascii=False) + if os.path.exists(path): + import shutil + backup = path + ".bak" + backup_1 = backup + ".1" + backup_2 = backup + ".2" + backup_tmp = f"{backup}.tmp.{os.getpid()}.{threading.get_ident()}" + shutil.copy2(path, backup_tmp) + if os.path.exists(backup_2): + os.remove(backup_2) + if os.path.exists(backup_1): + os.replace(backup_1, backup_2) + if os.path.exists(backup): + os.replace(backup, backup_1) + os.replace(backup_tmp, backup) os.replace(tmp, path) # 让调用方内存里的 state 也跟上合并结果,避免下次保存 # 又把别的进程的任务挤掉(调用方继续用这份 state 时)。