teleo-infrastructure/ops/private_receipt_io.py

34 lines
1.2 KiB
Python

"""Atomic private JSON receipt output shared by GCP parity helpers."""
from __future__ import annotations
import json
import os
import uuid
from pathlib import Path
from typing import Any
def write_private_json(path: Path, payload: dict[str, Any]) -> None:
"""Write one JSON receipt as mode 0600 without chmodding existing parents."""
parent_preexisting = path.parent.exists()
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
if not path.parent.is_dir() or path.parent.is_symlink():
raise ValueError("output parent must be a real directory")
if not parent_preexisting:
os.chmod(path.parent, 0o700)
temporary = path.parent / f".{path.name}.{uuid.uuid4().hex}.tmp"
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
json.dump(payload, handle, indent=2, sort_keys=True)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
os.chmod(path, 0o600)
finally:
try:
temporary.unlink()
except FileNotFoundError:
pass