fix(zones): validate the preset space and make zone writes race-free

This commit is contained in:
jetson committed 2026-11-12 11:04:44 +07:00
1 parent b00701a936
commit a0ea7d9f8e
4 files changed
+386 -30

No files matched your search

+47 -10
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
import os
import subprocess
import threading
@@ -37,7 +38,7 @@ from src.zone_config import (
load_zone_config, list_zone_presets, build_static_roi, build_counting_polygon,
build_truck_polygon, get_active_zone,
DEFAULT_ZONES, ZONE_BOUNDS_H, ZONE_BOUNDS_W,
save_zone_preset, validate_zone_preset,
save_zone_preset,
)
load_dotenv()
@@ -680,17 +681,39 @@ def _is_local_request() -> bool:
(counter_dashboard.py:2275) does not exist here. Remote operators use
an SSH tunnel, which makes the request arrive from loopback.
"""
return request.remote_addr in ("127.0.0.1", "::1")
# ::ffff:127.0.0.1 is the IPv4-mapped form of the loopback address; it
# shows up when the server listens on :: (IPv6) and the client is IPv4.
return request.remote_addr in ("127.0.0.1", "::1", "::ffff:127.0.0.1")
def _read_zones_config():
"""Return (config, error_response) for the zones file.
error_response is a Flask response tuple when the file is missing or
unusable, else None. Never raises: a corrupt zones.json must answer
with a status code, never a traceback.
"""
if not os.path.isfile(ZONES_PATH):
return None, (jsonify({"error": "zones.json not found"}), 404)
try:
config = load_zone_config(ZONES_PATH)
except OSError as exc:
return None, (jsonify({"error": f"cannot read zones.json: {exc}"}), 500)
except ValueError as exc: # malformed JSON
return None, (jsonify({"error": f"zones.json is not valid JSON: {exc}"}), 500)
if not isinstance(config, dict):
return None, (jsonify({"error": "zones.json must contain a JSON object"}), 500)
return config, None
@app.route("/api/zones/<preset_name>", methods=["GET"])
def api_zone_detail(preset_name: str):
"""Return one zone preset plus the coordinate space it is authored in."""
try:
config = load_zone_config(ZONES_PATH)
except (OSError, ValueError):
return jsonify({"error": "cannot read zones.json"}), 500
preset = (config.get("presets") or {}).get(preset_name)
config, error = _read_zones_config()
if error is not None:
return error
presets = config.get("presets")
preset = presets.get(preset_name) if isinstance(presets, dict) else None
if preset is None:
return jsonify({"error": "unknown preset"}), 404
return jsonify({
@@ -705,10 +728,21 @@ def api_zone_save(preset_name: str):
"""Save one zone preset. Localhost only."""
if not _is_local_request():
return jsonify({"error": "local access only"}), 403
payload = request.get_json(silent=True) or {}
_, error = _read_zones_config()
if error is not None:
return error
raw = request.get_data(cache=True)
if raw:
try:
payload = json.loads(raw)
except (ValueError, UnicodeDecodeError):
return jsonify({"error": "request body is not valid JSON"}), 400
else:
payload = {}
preset = payload.get("preset", payload) if isinstance(payload, dict) else payload
if not isinstance(preset, dict):
return jsonify({"error": "preset must be an object"}), 400
try:
validate_zone_preset(preset)
save_zone_preset(ZONES_PATH, preset_name, preset)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
@@ -722,11 +756,14 @@ def api_zone_reset(preset_name: str):
"""Restore a preset to the shipped default. Localhost only."""
if not _is_local_request():
return jsonify({"error": "local access only"}), 403
_, error = _read_zones_config()
if error is not None:
return error
default = DEFAULT_ZONES.get(preset_name)
if default is None:
return jsonify({"error": "unknown preset"}), 404
try:
save_zone_preset(ZONES_PATH, preset_name, default)
save_zone_preset(ZONES_PATH, preset_name, default, replace=True)
except (ValueError, OSError) as exc:
return jsonify({"error": str(exc)}), 500
return jsonify({"status": "reset", "preset": default})
+62 -19
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
import os
import shutil
import tempfile
from math import isfinite
from numbers import Real
from typing import Any
@@ -240,21 +241,45 @@ _POLYGON_KEYS = ("truck_area", "counting_area", "palet")
def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
"""Validate one zone preset, raise ValueError naming the offending key.
Checks: truck_area present and a valid non-degenerate polygon; every
polygon key that is present holds >=3 points of 2 finite numbers inside
0..1280 x 0..720 and forms a valid polygon with area > 0; count_line has
integer x_start < x_end and a y inside the frame. Unknown keys (the
tuning knobs) pass through untouched.
Checks: truck_area present with exactly 4 points (the runtime needs 4);
every polygon key that is present holds >=3 points of 2 finite numbers
inside 0..1280 x 0..720 and forms a valid polygon with area > 0;
count_line has finite integer x_start < x_end and a y inside the frame;
reference_resolution, when present, is the analysis space [1280, 720].
Unknown keys (the tuning knobs) pass through untouched.
Returns a normalized copy: count_line numbers and reference_resolution
become ints, so the caller persists exactly what was checked.
"""
if not isinstance(preset, dict):
raise ValueError("preset must be an object")
normalized = dict(preset)
if "reference_resolution" in preset:
ref = preset["reference_resolution"]
if not (
isinstance(ref, (list, tuple))
and len(ref) == 2
and all(isinstance(v, Real) and not isinstance(v, bool) for v in ref)
and [float(v) for v in ref] == [float(ZONE_BOUNDS_W), float(ZONE_BOUNDS_H)]
):
raise ValueError(
f"reference_resolution must be [{ZONE_BOUNDS_W}, {ZONE_BOUNDS_H}]"
)
normalized["reference_resolution"] = [ZONE_BOUNDS_W, ZONE_BOUNDS_H]
for key in _POLYGON_KEYS:
if key not in preset:
if key == "truck_area":
raise ValueError("truck_area is required")
continue
pts = preset[key]
if not isinstance(pts, list) or len(pts) < 3:
if key == "truck_area":
# build_static_roi needs 4 points; a 3-point truck_area would
# pass here and then degrade the job to dynamic mode.
if not isinstance(pts, list) or len(pts) != 4:
raise ValueError("truck_area must be a polygon with exactly 4 points")
elif not isinstance(pts, list) or len(pts) < 3:
raise ValueError(f"{key} must be a polygon with at least 3 points")
clean: list[tuple[float, float]] = []
for pt in pts:
@@ -263,7 +288,7 @@ def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
raise ValueError(f"{key} contains an invalid point")
try:
x, y = float(pt[0]), float(pt[1])
except (OverflowError, ValueError) as exc:
except (OverflowError, TypeError, ValueError) as exc:
raise ValueError(f"{key} contains an invalid point") from exc
if not (isfinite(x) and isfinite(y)):
raise ValueError(f"{key} contains an invalid point")
@@ -287,34 +312,52 @@ def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
v = line.get(name)
if not isinstance(v, Real) or isinstance(v, bool):
raise ValueError("count_line needs integer x_start, x_end and y")
nums[name] = int(v)
try:
fv = float(v)
except (OverflowError, TypeError, ValueError) as exc:
raise ValueError("count_line needs integer x_start, x_end and y") from exc
if not isfinite(fv) or not fv.is_integer():
raise ValueError("count_line needs integer x_start, x_end and y")
nums[name] = int(fv)
x_start, x_end, y = nums["x_start"], nums["x_end"], nums["y"]
if not (0 <= x_start < x_end <= ZONE_BOUNDS_W):
raise ValueError("count_line x_start/x_end must satisfy 0 <= x_start < x_end <= 1280")
if not (0 <= y <= ZONE_BOUNDS_H):
raise ValueError(f"count_line y={y} is outside 0..{ZONE_BOUNDS_H}")
return preset
normalized["count_line"] = {**line, **nums}
return normalized
def save_zone_preset(path: str, name: str, preset: dict[str, Any]) -> None:
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.
The posted preset is merged OVER the stored one, so a partial post (only
the geometry) keeps the preset's tuning knobs. Sibling presets and
active_preset are never touched.
active_preset are never touched. With replace=True the stored preset is
replaced wholesale by the given one (used by the reset route).
The normalized preset returned by validate_zone_preset is what gets
persisted, so a float count_line is stored as an int.
"""
if os.path.isfile(path):
config = load_zone_config(path)
else:
config = {"presets": {}, "active_preset": name}
presets = config.setdefault("presets", {})
merged = {**presets.get(name, {}), **preset}
validate_zone_preset(merged)
presets[name] = merged
merged = preset if replace else {**presets.get(name, {}), **preset}
presets[name] = validate_zone_preset(merged)
if os.path.exists(path):
shutil.copy2(path, path + ".bak")
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)
f.write("\n")
os.replace(tmp, path)
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
+183
View File
@@ -679,3 +679,186 @@ def test_post_zones_reset_restores_the_default_preset(client, tmp_path, monkeypa
assert resp.status_code == 200
saved = json.loads(open(zones).read())
assert saved["presets"]["default"]["count_line"] == {"x_start": 423, "x_end": 939, "y": 182}
# --- fix round 1: route-level coverage for F1-F9 ---
def _route_preset(**overrides):
"""A valid preset in the 1280x720 analysis space, with overrides applied."""
preset = {
"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],
"count_line": {"x_start": 385, "x_end": 934, "y": 220},
"reference_resolution": [1280, 720],
}
preset.update(overrides)
return preset
def test_post_zones_rejects_a_foreign_reference_resolution(client, tmp_path, monkeypatch):
"""F1: a 1920x1080 preset would be scaled twice; the file must not change."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
before = open(zones).read()
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default",
json={"preset": _route_preset(reference_resolution=[1920, 1080])})
assert resp.status_code == 400
assert "reference_resolution" in resp.get_json()["error"]
assert open(zones).read() == before
def test_post_zones_rejects_a_non_finite_count_line(client, tmp_path, monkeypatch):
"""F2: Infinity used to reach int() and raise OverflowError (500)."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
body = ('{"preset": {"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],'
' "count_line": {"x_start": 385, "x_end": 934, "y": Infinity}}}')
resp = client.post("/api/zones/default", data=body, content_type="application/json")
assert resp.status_code == 400
assert "count_line" in resp.get_json()["error"]
def test_post_zones_rejects_a_fractional_count_line(client, tmp_path, monkeypatch):
"""F3: bounds were checked on the truncated int, the raw float was stored."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default",
json={"preset": _route_preset(count_line={"x_start": 385, "x_end": 1280.9, "y": 220})})
assert resp.status_code == 400
assert "count_line" in resp.get_json()["error"]
def test_post_zones_stores_an_integral_float_count_line_as_an_int(client, tmp_path, monkeypatch):
"""F3: 1280.0 is an integer in disguise and must be persisted as 1280."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default",
json={"preset": _route_preset(count_line={"x_start": 385, "x_end": 1280.0, "y": 220})})
assert resp.status_code == 200
x_end = json.loads(open(zones).read())["presets"]["default"]["count_line"]["x_end"]
assert x_end == 1280
assert isinstance(x_end, int)
def test_post_zones_rejects_a_three_point_truck_area(client, tmp_path, monkeypatch):
"""F4: build_static_roi needs 4 points; 3 would degrade the job to dynamic."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default",
json={"preset": _route_preset(truck_area=[[400, 257], [406, 717], [936, 719]])})
assert resp.status_code == 400
assert "truck_area" in resp.get_json()["error"]
def test_get_zone_detail_without_a_zones_file_is_404(client, tmp_path, monkeypatch):
"""F6: a missing file is a missing preset, not a server error."""
import app as app_module
monkeypatch.setattr(app_module, "ZONES_PATH", str(tmp_path / "missing.json"))
resp = client.get("/api/zones/default")
assert resp.status_code == 404
assert "not found" in resp.get_json()["error"]
def test_get_zone_detail_with_a_corrupt_zones_file_is_500(client, tmp_path, monkeypatch):
"""F6: invalid JSON must answer with a message, not a traceback."""
import app as app_module
zones = tmp_path / "zones.json"
zones.write_text("{not json")
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.get("/api/zones/default")
assert resp.status_code == 500
assert "not valid JSON" in resp.get_json()["error"]
assert "Traceback" not in resp.get_data(as_text=True)
def test_get_zone_detail_with_a_non_object_zones_file_is_500(client, tmp_path, monkeypatch):
"""F6: a JSON array is not a zone config."""
import app as app_module
zones = tmp_path / "zones.json"
zones.write_text("[1, 2, 3]")
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.get("/api/zones/default")
assert resp.status_code == 500
assert "JSON object" in resp.get_json()["error"]
assert "Traceback" not in resp.get_data(as_text=True)
@pytest.mark.parametrize("route", ["/api/zones/default", "/api/zones/default/reset"])
@pytest.mark.parametrize("content,expect", [
("{not json", "not valid JSON"),
("[1, 2, 3]", "JSON object"),
])
def test_zone_write_routes_reject_an_unusable_zones_file(client, tmp_path, monkeypatch, route, content, expect):
"""F6: the write routes use the same guard as GET."""
import app as app_module
zones = tmp_path / "zones.json"
zones.write_text(content)
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.post(route, json={"preset": _route_preset()})
assert resp.status_code == 500
assert expect in resp.get_json()["error"]
assert "Traceback" not in resp.get_data(as_text=True)
def test_post_zones_with_a_malformed_body_is_400(client, tmp_path, monkeypatch):
"""F7: the message names the body, not a preset key."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default", data="{not json", content_type="application/json")
assert resp.status_code == 400
error = resp.get_json()["error"]
assert "body" in error.lower()
assert "truck_area" not in error
def test_post_zones_reset_drops_keys_that_are_not_in_the_default(client, tmp_path, monkeypatch):
"""F8: reset replaces the stored preset wholesale, siblings untouched."""
import app as app_module
zones = tmp_path / "zones.json"
with open(zones, "w") as f:
json.dump({"presets": {"default": {**_route_preset(), "custom_tuning": 7},
"other": _route_preset()},
"active_preset": "default"}, f)
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.post("/api/zones/default/reset")
assert resp.status_code == 200
saved = json.loads(open(zones).read())
assert "custom_tuning" not in saved["presets"]["default"]
assert saved["presets"]["default"]["count_line"] == {"x_start": 423, "x_end": 939, "y": 182}
assert saved["presets"]["other"] == _route_preset()
assert saved["active_preset"] == "default"
def test_post_zones_from_ipv4_mapped_loopback_is_200(client, tmp_path, monkeypatch):
"""F9: ::ffff:127.0.0.1 is loopback when the server listens on IPv6."""
import app as app_module
zones = _zones_file(tmp_path, _route_preset())
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
resp = client.post("/api/zones/default", json={"preset": _route_preset()},
environ_base={"REMOTE_ADDR": "::ffff:127.0.0.1"})
assert resp.status_code == 200
def test_post_zones_without_a_zones_file_is_404_and_creates_nothing(client, tmp_path, monkeypatch):
"""F6: the write routes refuse to create a missing zones.json."""
import app as app_module
missing = tmp_path / "missing.json"
monkeypatch.setattr(app_module, "ZONES_PATH", str(missing))
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
assert resp.status_code == 404
assert not missing.exists()
def test_post_zones_reset_without_a_zones_file_is_404_and_creates_nothing(client, tmp_path, monkeypatch):
"""F6: reset refuses to create a missing zones.json either."""
import app as app_module
missing = tmp_path / "missing.json"
monkeypatch.setattr(app_module, "ZONES_PATH", str(missing))
resp = client.post("/api/zones/default/reset")
assert resp.status_code == 404
assert not missing.exists()
+94 -1
View File
@@ -388,7 +388,7 @@ def test_save_zone_preset_keeps_knob_keys_of_the_edited_preset(tmp_path):
"active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
save_zone_preset(path, "default", {"truck_area": [[1, 1], [10, 1], [10, 10]]})
save_zone_preset(path, "default", {"truck_area": [[1, 1], [10, 1], [10, 10], [1, 10]]})
saved = json.load(open(path))
assert saved["presets"]["default"]["duplicate_circle_radius"] == 30
@@ -408,3 +408,96 @@ def test_repo_zones_json_ships_the_fcp_calibrations():
assert legacy["count_line"] == {"x_start": 385, "x_end": 934, "y": 220}
assert legacy["truck_area"] == [[400, 257], [406, 717], [936, 719], [921, 229]]
assert legacy["counting_area"] == [[383, 33], [391, 718], [945, 717], [931, 33]]
# --- fix round 1: F1 reference_resolution, F2/F3 count_line, F4 truck_area ---
def test_validate_zone_preset_rejects_a_foreign_reference_resolution():
"""F1: a 1920x1080 preset would be scaled a second time by build_static_roi."""
bad = {**GOOD_PRESET, "reference_resolution": [1920, 1080]}
with pytest.raises(ValueError, match="reference_resolution"):
validate_zone_preset(bad)
def test_validate_zone_preset_accepts_a_preset_without_reference_resolution():
"""F1: the key is optional; 1280x720 is the analysis space."""
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
assert validate_zone_preset(preset) is not None
def test_validate_zone_preset_rejects_a_non_finite_count_line():
"""F2: int(float('inf')) raises OverflowError, which used to 500."""
bad = {**GOOD_PRESET, "count_line": {"x_start": 385, "x_end": 934, "y": float("inf")}}
with pytest.raises(ValueError, match="count_line"):
validate_zone_preset(bad)
def test_validate_zone_preset_rejects_a_fractional_count_line():
"""F3: bounds were checked on the truncated int, the raw float was stored."""
bad = {**GOOD_PRESET, "count_line": {"x_start": 385, "x_end": 1280.9, "y": 220}}
with pytest.raises(ValueError, match="count_line"):
validate_zone_preset(bad)
def test_validate_zone_preset_normalizes_an_integral_float_count_line():
"""F3: 1280.0 is an integer in disguise and is stored as 1280."""
out = validate_zone_preset({**GOOD_PRESET, "count_line": {"x_start": 385, "x_end": 1280.0, "y": 220.0}})
assert out["count_line"] == {"x_start": 385, "x_end": 1280, "y": 220}
assert all(isinstance(v, int) for v in out["count_line"].values())
def test_validate_zone_preset_requires_four_truck_area_points():
"""F4: build_static_roi needs 4 points; 3 would silently degrade the job."""
bad = {**GOOD_PRESET, "truck_area": [[400, 257], [406, 717], [936, 719]]}
with pytest.raises(ValueError, match="truck_area"):
validate_zone_preset(bad)
def test_save_zone_preset_persists_the_normalized_preset(tmp_path):
"""F3: the normalized count_line must reach the file."""
path = str(tmp_path / "zones.json")
cfg = {"presets": {"default": GOOD_PRESET}, "active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
save_zone_preset(path, "default", {**GOOD_PRESET, "count_line": {"x_start": 385, "x_end": 1280.0, "y": 220.0}})
saved = json.load(open(path))
assert saved["presets"]["default"]["count_line"] == {"x_start": 385, "x_end": 1280, "y": 220}
# 1280.0 == 1280 in Python, so the type is the real assertion here
assert all(isinstance(v, int) for v in saved["presets"]["default"]["count_line"].values())
def test_save_zone_preset_with_replace_drops_stored_keys(tmp_path):
"""F8: replace=True swaps the stored preset wholesale."""
path = str(tmp_path / "zones.json")
cfg = {"presets": {"default": {**GOOD_PRESET, "duplicate_circle_radius": 30}},
"active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
save_zone_preset(path, "default", GOOD_PRESET, replace=True)
saved = json.load(open(path))
assert "duplicate_circle_radius" not in saved["presets"]["default"]
assert saved["active_preset"] == "default"
def test_save_zone_preset_uses_a_unique_temp_file(tmp_path):
"""F5: concurrent posts must not share one temp path."""
import src.zone_config as zc
path = str(tmp_path / "zones.json")
cfg = {"presets": {}, "active_preset": "default"}
with open(path, "w") as f:
json.dump(cfg, f)
seen = []
real_mkstemp = zc.tempfile.mkstemp
def spy(*args, **kwargs):
fd, name = real_mkstemp(*args, **kwargs)
seen.append(name)
return fd, name
zc.tempfile.mkstemp = spy
try:
save_zone_preset(path, "default", GOOD_PRESET)
save_zone_preset(path, "other", GOOD_PRESET)
finally:
zc.tempfile.mkstemp = real_mkstemp
assert len(seen) == 2
assert seen[0] != seen[1]
assert all(os.path.dirname(p) == str(tmp_path) for p in seen)