diff --git a/app.py b/app.py index d305a19..1afddcf 100644 --- a/app.py +++ b/app.py @@ -744,6 +744,8 @@ def api_zone_save(preset_name: str): return jsonify({"error": "preset must be an object"}), 400 try: save_zone_preset(ZONES_PATH, preset_name, preset) + except FileNotFoundError: + return jsonify({"error": "zones.json not found"}), 404 except ValueError as exc: return jsonify({"error": str(exc)}), 400 except OSError as exc: @@ -764,7 +766,11 @@ def api_zone_reset(preset_name: str): return jsonify({"error": "unknown preset"}), 404 try: save_zone_preset(ZONES_PATH, preset_name, default, replace=True) - except (ValueError, OSError) as exc: + except FileNotFoundError: + return jsonify({"error": "zones.json not found"}), 404 + except ValueError as exc: + return jsonify({"error": str(exc)}), 400 + except OSError as exc: return jsonify({"error": str(exc)}), 500 return jsonify({"status": "reset", "preset": default}) diff --git a/src/zone_config.py b/src/zone_config.py index 2a38fd1..03eb216 100644 --- a/src/zone_config.py +++ b/src/zone_config.py @@ -6,6 +6,7 @@ import json import os import shutil import tempfile +import threading from math import isfinite from numbers import Real from typing import Any @@ -266,7 +267,9 @@ def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]: raise ValueError( f"reference_resolution must be [{ZONE_BOUNDS_W}, {ZONE_BOUNDS_H}]" ) - normalized["reference_resolution"] = [ZONE_BOUNDS_W, ZONE_BOUNDS_H] + # Always pin the analysis space: a preset without the key would fall back + # to build_static_roi's 1920x1080 default and be scaled by 1280/1920. + normalized["reference_resolution"] = [ZONE_BOUNDS_W, ZONE_BOUNDS_H] for key in _POLYGON_KEYS: if key not in preset: @@ -328,6 +331,11 @@ def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]: return normalized +# Serializes the read-modify-write in save_zone_preset; without it two +# concurrent writes can lose one of the updates. +_SAVE_LOCK = threading.Lock() + + def save_zone_preset(path: str, name: str, preset: dict[str, Any], replace: bool = False) -> None: """Merge a preset into zones.json under `name`, atomically, with a backup. @@ -339,25 +347,36 @@ def save_zone_preset(path: str, name: str, preset: dict[str, Any], The normalized preset returned by validate_zone_preset is what gets persisted, so a float count_line is stored as an int. + + Raises FileNotFoundError if the file does not exist (this function never + creates a zones.json) and ValueError if the file is not a usable config. """ - if os.path.isfile(path): + if not os.path.isfile(path): + raise FileNotFoundError(f"zones.json not found: {path}") + with _SAVE_LOCK: config = load_zone_config(path) - else: - config = {"presets": {}, "active_preset": name} - presets = config.setdefault("presets", {}) - merged = preset if replace else {**presets.get(name, {}), **preset} - presets[name] = validate_zone_preset(merged) - if os.path.exists(path): + if not isinstance(config, dict): + raise ValueError("zones.json must contain a JSON object") + presets = config.get("presets") + if presets is None: + presets = {} + config["presets"] = presets + elif not isinstance(presets, dict): + raise ValueError("zones.json 'presets' must be a JSON object") + merged = preset if replace else {**presets.get(name, {}), **preset} + presets[name] = validate_zone_preset(merged) shutil.copy2(path, path + ".bak") - directory = os.path.dirname(os.path.abspath(path)) - fd, tmp = tempfile.mkstemp(dir=directory, prefix=os.path.basename(path) + ".", - suffix=".tmp") - try: - with os.fdopen(fd, "w", encoding="utf-8") as f: - json.dump(config, f, indent=2) - f.write("\n") - os.replace(tmp, path) - except BaseException: - if os.path.exists(tmp): - os.unlink(tmp) - raise + directory = os.path.dirname(os.path.abspath(path)) + fd, tmp = tempfile.mkstemp(dir=directory, prefix=os.path.basename(path) + ".", + suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(config, f, indent=2) + f.write("\n") + # mkstemp creates 0600; keep the mode the file had before. + os.chmod(tmp, os.stat(path).st_mode & 0o777) + os.replace(tmp, path) + except BaseException: + if os.path.exists(tmp): + os.unlink(tmp) + raise diff --git a/tests/test_app.py b/tests/test_app.py index 3edc037..55d147b 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -862,3 +862,81 @@ def test_post_zones_reset_without_a_zones_file_is_404_and_creates_nothing(client resp = client.post("/api/zones/default/reset") assert resp.status_code == 404 assert not missing.exists() + + +# --- fix round 2: R1 reference_resolution, R2/R3 file handling, R4 mode --- + +def test_post_zones_injects_the_analysis_space_when_the_key_is_absent(client, tmp_path, monkeypatch): + """R1: a preset without reference_resolution would be scaled by 1280/1920.""" + import app as app_module + from src.zone_config import build_static_roi + zones = _zones_file(tmp_path, _route_preset()) + monkeypatch.setattr(app_module, "ZONES_PATH", zones) + preset = {k: v for k, v in _route_preset().items() if k != "reference_resolution"} + # A new preset name: merging over a stored preset would keep the stored key. + resp = client.post("/api/zones/fresh", json={"preset": preset}) + assert resp.status_code == 200 + stored = json.loads(open(zones).read())["presets"]["fresh"] + assert stored["reference_resolution"] == [1280, 720] + roi = build_static_roi(stored, 1280, 720) + assert (roi.x1, roi.x2) == (400, 936) + + +def test_post_zones_with_a_non_object_presets_is_400(client, tmp_path, monkeypatch): + """R2: {"presets": []} used to raise TypeError inside the save.""" + import app as app_module + zones = tmp_path / "zones.json" + zones.write_text(json.dumps({"presets": [], "active_preset": "default"})) + monkeypatch.setattr(app_module, "ZONES_PATH", str(zones)) + resp = client.post("/api/zones/default", json={"preset": _route_preset()}) + assert resp.status_code == 400 + assert "presets" in resp.get_json()["error"] + assert "Traceback" not in resp.get_data(as_text=True) + assert json.loads(zones.read_text()) == {"presets": [], "active_preset": "default"} + + +def test_post_zones_reset_with_a_non_object_presets_is_400(client, tmp_path, monkeypatch): + """R2: the reset route maps the same ValueError to 400.""" + import app as app_module + zones = tmp_path / "zones.json" + zones.write_text(json.dumps({"presets": [], "active_preset": "default"})) + monkeypatch.setattr(app_module, "ZONES_PATH", str(zones)) + resp = client.post("/api/zones/default/reset") + assert resp.status_code == 400 + assert "presets" in resp.get_json()["error"] + assert "Traceback" not in resp.get_data(as_text=True) + assert json.loads(zones.read_text()) == {"presets": [], "active_preset": "default"} + + +def test_post_zones_does_not_recreate_a_vanished_zones_file(client, tmp_path, monkeypatch): + """R3: a file that vanishes between the check and the save is not recreated.""" + import os + + import app as app_module + zones = _zones_file(tmp_path, _route_preset()) + monkeypatch.setattr(app_module, "ZONES_PATH", zones) + real_load = app_module.load_zone_config + + def load_then_remove(path): + config = real_load(path) + os.remove(path) + return config + + monkeypatch.setattr(app_module, "load_zone_config", load_then_remove) + resp = client.post("/api/zones/default", json={"preset": _route_preset()}) + assert resp.status_code == 404 + assert "not found" in resp.get_json()["error"] + assert not os.path.exists(zones) + + +def test_post_zones_keeps_the_zones_file_mode(client, tmp_path, monkeypatch): + """R4: mkstemp creates 0600; the file must not become owner-only.""" + import os + + import app as app_module + zones = _zones_file(tmp_path, _route_preset()) + os.chmod(zones, 0o644) + monkeypatch.setattr(app_module, "ZONES_PATH", zones) + resp = client.post("/api/zones/default", json={"preset": _route_preset()}) + assert resp.status_code == 200 + assert os.stat(zones).st_mode & 0o777 == 0o644 diff --git a/tests/test_zone_config.py b/tests/test_zone_config.py index 535620e..b7debc3 100644 --- a/tests/test_zone_config.py +++ b/tests/test_zone_config.py @@ -501,3 +501,102 @@ def test_save_zone_preset_uses_a_unique_temp_file(tmp_path): assert len(seen) == 2 assert seen[0] != seen[1] assert all(os.path.dirname(p) == str(tmp_path) for p in seen) + + +# --- fix round 2: R1 reference_resolution injection, R2/R3 file handling, R4 mode, R5 lock --- + +def test_validate_zone_preset_injects_the_analysis_space_when_the_key_is_absent(): + """R1: without the key, build_static_roi would scale the zone by 1280/1920.""" + preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"} + out = validate_zone_preset(preset) + assert out["reference_resolution"] == [1280, 720] + + +def test_save_zone_preset_persists_the_injected_analysis_space(tmp_path): + """R1: the injected key must reach the file, so the runtime scale is 1.0.""" + path = str(tmp_path / "zones.json") + cfg = {"presets": {}, "active_preset": "default"} + with open(path, "w") as f: + json.dump(cfg, f) + preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"} + save_zone_preset(path, "fresh", preset) + saved = json.load(open(path)) + assert saved["presets"]["fresh"]["reference_resolution"] == [1280, 720] + roi = build_static_roi(saved["presets"]["fresh"], 1280, 720) + assert (roi.x1, roi.x2) == (400, 936) + + +def test_save_zone_preset_rejects_a_non_object_presets(tmp_path): + """R2: {"presets": []} used to raise TypeError inside the save.""" + path = str(tmp_path / "zones.json") + with open(path, "w") as f: + json.dump({"presets": []}, f) + with pytest.raises(ValueError, match="presets"): + save_zone_preset(path, "default", GOOD_PRESET) + + +def test_save_zone_preset_rejects_a_non_object_config(tmp_path): + """R2: a JSON array as the whole config is not a zone config.""" + path = str(tmp_path / "zones.json") + with open(path, "w") as f: + json.dump([1, 2, 3], f) + with pytest.raises(ValueError, match="object"): + save_zone_preset(path, "default", GOOD_PRESET) + + +def test_save_zone_preset_refuses_to_create_a_missing_file(tmp_path): + """R3: the write path must never bring a zones.json into existence.""" + path = str(tmp_path / "zones.json") + with pytest.raises(FileNotFoundError): + save_zone_preset(path, "default", GOOD_PRESET) + assert not os.path.exists(path) + + +def test_save_zone_preset_keeps_the_file_mode(tmp_path): + """R4: mkstemp creates 0600; the file must not silently become owner-only.""" + path = str(tmp_path / "zones.json") + with open(path, "w") as f: + json.dump({"presets": {}, "active_preset": "default"}, f) + os.chmod(path, 0o644) + save_zone_preset(path, "default", GOOD_PRESET) + assert os.stat(path).st_mode & 0o777 == 0o644 + + +def test_save_zone_preset_serializes_concurrent_writes(tmp_path, monkeypatch): + """R5: two concurrent saves must not lose one of the presets.""" + import threading + import time + + import src.zone_config as zc + path = str(tmp_path / "zones.json") + with open(path, "w") as f: + json.dump({"presets": {}, "active_preset": "default"}, f) + # Widen the read-modify-write window so an unsynchronized save loses an update. + real_load = zc.load_zone_config + first_read = threading.Event() + + def slow_load(p): + cfg = real_load(p) + first_read.set() + time.sleep(0.05) + return cfg + + monkeypatch.setattr(zc, "load_zone_config", slow_load) + errors = [] + + def worker(name): + try: + zc.save_zone_preset(path, name, GOOD_PRESET) + except Exception as exc: # noqa: BLE001 - reported below + errors.append(exc) + + t1 = threading.Thread(target=worker, args=("one",)) + t2 = threading.Thread(target=worker, args=("two",)) + t1.start() + assert first_read.wait(5) + t2.start() + t1.join(5) + t2.join(5) + assert not errors + saved = json.load(open(path)) + assert set(saved["presets"]) == {"one", "two"}