AirPlan V2 initial release — unified scheduler with 12 sub-modes
Merges 8 V1 plugins into 1 unified plugin, adds 4 new components (dep, tst, sec, rvr). 12 sub-modes: arc, eng, do, dbg, xdb, sdb, ndb, ctx, dep, tst, sec, rvr. L1 code-level guarantees: atomic writes, file locks, evidence gating, forced debug routing, 3-phase arc gate, evidence-first debug gate, Chinese language lock, scheduler boundary. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
53
lib/air_runtime/io.py
Normal file
53
lib/air_runtime/io.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
原子 I/O 模块 — 消除 V1 5 份 _json_dump/_json_load 重复。
|
||||
每次写入使用 tempfile + os.replace() 保证原子性,写入前自动备份。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def atomic_json_write(path: Path, data: dict | list, indent: int = 2) -> None:
|
||||
"""POSIX 原子写入:tempfile + os.replace()。写入前自动备份旧文件为 .bak(单级轮转)。"""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 备份旧文件
|
||||
if path.exists():
|
||||
bak = path.with_suffix(path.suffix + ".bak")
|
||||
try:
|
||||
os.replace(str(path), str(bak))
|
||||
except OSError as exc:
|
||||
logger.warning("backup %s -> %s failed: %s", path, bak, exc)
|
||||
|
||||
fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
|
||||
try:
|
||||
os.write(fd, json.dumps(data, indent=indent, ensure_ascii=False).encode("utf-8"))
|
||||
os.close(fd)
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp)
|
||||
raise
|
||||
|
||||
|
||||
def safe_json_load(path: Path) -> dict | list | None:
|
||||
"""安全加载:处理损坏文件,自动从 .bak 恢复。文件不存在返回 None。"""
|
||||
try:
|
||||
return json.loads(path.read_text("utf-8"))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
bak = path.with_suffix(path.suffix + ".bak")
|
||||
if bak.exists():
|
||||
logger.warning("corrupt %s, restoring from %s", path, bak)
|
||||
return json.loads(bak.read_text("utf-8"))
|
||||
logger.error("corrupt %s with no backup", path)
|
||||
return None
|
||||
Reference in New Issue
Block a user