감사에서 확정된 잔여 항목을 일괄 처리. 이전 커밋이 증상(스테일 번들)을 고쳤다면 이번에는 그것이 조용히 지나가게 만든 구조를 고친다. 보안 - CSP 도입. 인라인 2블록에 per-request nonce, unsafe-inline 없음. 빌드가 없다는 제약이 nonce를 막지는 않는다. 보안 헤더를 .htaccess 단독에서 PHP로 옮겨 개발/납품이 같아진다. - /logout에 CSRF. SameSite=Lax가 막아주지만, 사고 대응 중 운영자를 콘솔에서 튕겨내는 건 이 제품에선 실제 가용성 공격이라 예외로 둘 이유가 없다. - 잠긴 계정 423 → 401. 아무나 이름을 추측해 5회 실패로 잠근 뒤 423을 계정 실재 확인으로 쓸 수 있었다. 잠금 사실은 감사 로그에 남고, 익명 호출자는 못 읽는다. 엣지 - 큐 flush에 회당 상한. 정전 복구 직후 2000건을 비우는 동안 감지가 멈추던 구간을 없앤다. - 타이머 env 전수 검증. COOLDOWN_S=nan은 dedup을 무력화해 매 틱 발보시켰다. - T2 프레임 스킵(INFER_EVERY). 스킵 틱은 프레임을 읽어 버퍼만 비우고 링버퍼에 넣지 않는다 — 추론이 없으면 얼굴 박스도 없어 그대로 넣으면 증거 스냅샷에 미블러 얼굴이 실린다. T3(모션 게이트)는 의도적으로 미구현: 게이트가 틀리면 '움직이지 않는 쓰러진 작업자'에게 추론이 안 돈다. 실영상 없이 임계값을 정할 수 없다. - systemd 워치독(sd_notify) + 메모리 상한. Restart=always는 죽은 프로세스만 잡고 '살아 있는데 멈춘' 상태는 못 잡는다. UVC 해상도·버퍼 고정(링버퍼 RSS가 웹캠 기본값에 좌우). 테스트 — 감사의 최대 갭 - PDO 통합 테스트가 pdo_sqlite 부재로 통째로 스킵되고 CI도 없어 사실상 한 번도 안 돌았다. `-d extension=pdo_sqlite`로 되살리고 리포트·히트맵·익스포트 집계 SQL을 최초로 실행한다. - 얼굴 블러 테스트가 out is not None만 봤다 — blur()가 무동작이어도 통과. PIPA 대응의 유일한 실행 가능한 증거였는데 아무것도 증명하지 못했다. 디테일 파괴를 단언하도록 교체. - index.php 라우트 테이블 대조(프런트 호출 15개 교차검증), dist↔소스 패리티 테스트, CI 신설(스킵이 하나라도 있으면 실패). - ArraySessionStore.regenerate()가 데이터를 지워 실제 session_regenerate_id(true)와 달랐다. 더블이 실구현과 어긋난 자리 하나를 실제로 잡았다. 프런트 - 이벤트 목록 시그니처 재렌더 스킵 + 포커스 복원. aria-live 영역을 5초마다 통째로 다시 만들어 스크린리더가 200행을 재낭독하고 키보드 포커스가 body로 날아갔다. 같은 패턴이 device-tree.js에는 이미 있었다. - 폴링 중첩 가드(느린 공유호스팅에서 응답 역전), 콜드스타트 실패 표시. 납품 - VERSION 신설, 두 산출물에 version/git_commit/built_at 스탬프. 스테일 번들의 SHA256SUMS는 자기정합적이라 통과한다 — provenance 없이는 하류에서 탐지할 방법이 없다. - deploy/README·env.example을 Hailo 단독 번들 실제와 일치(템플릿이 없는 ONNX를 가리켰다). - 이벤트 보존 정책은 기본 0(영구). 산업안전 기록을 시스템이 임의로 지우지 않는다. 검증: pytest 251 / PHPUnit 162, 스킵 0. CSP nonce 결합은 실제 렌더 경로로 확인. 브라우저 실렌더는 MySQL이 필요해 이 환경에서 미수행.
123 lines
6.8 KiB
Python
123 lines
6.8 KiB
Python
import base64
|
|
import json
|
|
import sqlite3
|
|
|
|
from edge.alert import SendResult
|
|
from edge.events import Event, EventType, Severity
|
|
|
|
|
|
class OfflineQueue:
|
|
def __init__(self, db_path: str, client, max_rows: int = 2000,
|
|
max_send_attempts: int = 20, max_flush_rows: int = 20):
|
|
self.client = client
|
|
self.max_rows = max_rows # SD-card guard: evict oldest beyond this
|
|
self.max_send_attempts = max_send_attempts # drop a poison event after this many tries
|
|
# Detection-gap guard. flush() runs INSIDE the single-threaded detection loop, so every
|
|
# row it sends is time the camera is not being processed. Draining a full max_rows queue
|
|
# in one call (2000 rows x up to 5s POST timeout) would stall fall detection for minutes
|
|
# right after an outage recovers — exactly when the backlog proves the site was
|
|
# unmonitored. Drain a slice per tick instead: the queue still empties, but the loop keeps
|
|
# detecting between slices.
|
|
self.max_flush_rows = max_flush_rows
|
|
self.db = sqlite3.connect(db_path)
|
|
self.db.execute(
|
|
"CREATE TABLE IF NOT EXISTS queue ("
|
|
"id INTEGER PRIMARY KEY AUTOINCREMENT, payload TEXT, snaps TEXT, "
|
|
"attempts INTEGER DEFAULT 0)"
|
|
)
|
|
# Migrate an older DB that predates the attempts column.
|
|
try:
|
|
self.db.execute("ALTER TABLE queue ADD COLUMN attempts INTEGER DEFAULT 0")
|
|
except sqlite3.OperationalError:
|
|
pass # column already exists
|
|
self.db.commit()
|
|
|
|
def _rehydrate(self, payload: dict, snaps: list[bytes]) -> tuple[Event, list[bytes]]:
|
|
# Preserve the stored event_uuid so a re-sent event keeps its idempotency key and the
|
|
# server dedups it. Rows queued before this field existed simply get a fresh uuid (they
|
|
# predate dedup, so a first-and-only delivery is correct for them).
|
|
uuid_kw = {"event_uuid": payload["event_uuid"]} if payload.get("event_uuid") else {}
|
|
e = Event(EventType(payload["event_type"]), Severity(payload["severity"]),
|
|
payload["camera_id"], payload["track_id"], payload["zone_id"],
|
|
payload["occurred_at"], payload["duration_s"], payload["metrics"],
|
|
tuple(payload["spatial"]) if payload.get("spatial") else None,
|
|
**uuid_kw)
|
|
return e, snaps
|
|
|
|
def enqueue(self, event: Event, snapshots: list[bytes]) -> None:
|
|
payload = event.to_payload("") # device_id는 client가 다시 채움
|
|
payload["event_type"] = event.event_type.value
|
|
payload["severity"] = event.severity.value
|
|
payload["spatial"] = list(event.spatial) if event.spatial else None
|
|
snaps = [base64.b64encode(s).decode() for s in snapshots]
|
|
self.db.execute("INSERT INTO queue (payload, snaps) VALUES (?, ?)",
|
|
(json.dumps(payload), json.dumps(snaps)))
|
|
# Bound the queue so a multi-day outage — or a permanent misconfig that queues every
|
|
# event forever — cannot fill the SD card and hard-crash the Pi. Keep the newest
|
|
# max_rows; a fresh fall alert matters more than a stale one.
|
|
self.db.execute(
|
|
"DELETE FROM queue WHERE id NOT IN "
|
|
"(SELECT id FROM queue ORDER BY id DESC LIMIT ?)", (self.max_rows,))
|
|
self.db.commit()
|
|
|
|
def try_send(self, event: Event, snapshots: list[bytes]) -> bool:
|
|
if self.client.send(event, snapshots):
|
|
return True
|
|
self.enqueue(event, snapshots)
|
|
return False
|
|
|
|
def flush(self) -> int:
|
|
# LIMIT bounds BOTH the stall above and peak memory: each row carries up to 3 base64
|
|
# JPEGs, so fetching the whole queue would also spike RSS on the Pi.
|
|
rows = self.db.execute(
|
|
"SELECT id, payload, snaps, attempts FROM queue ORDER BY id LIMIT ?",
|
|
(self.max_flush_rows,)).fetchall()
|
|
sent = 0
|
|
for rid, payload_json, snaps_json, attempts in rows:
|
|
try:
|
|
payload = json.loads(payload_json)
|
|
snaps = [base64.b64decode(s) for s in json.loads(snaps_json)]
|
|
event, snapshots = self._rehydrate(payload, snaps)
|
|
except Exception:
|
|
# An undecodable row — a torn SD-card write, or schema drift from an older edge
|
|
# build whose payload lacks a key _rehydrate indexes — can NEVER be delivered.
|
|
# flush() breaks on the first undelivered row to preserve order, so leaving this
|
|
# row in place would wedge every queued safety event BEHIND it forever. Drop the
|
|
# single unrecoverable row and continue; losing it beats freezing the whole queue.
|
|
self.db.execute("DELETE FROM queue WHERE id = ?", (rid,))
|
|
self.db.commit()
|
|
continue
|
|
# A row queued before event_uuid existed has none stored; _rehydrate minted a fresh
|
|
# one just now. Persist it so every retry of this row reuses the SAME key — otherwise
|
|
# each flush sends a different uuid and a timeout-retried delivery duplicates on the
|
|
# server (the P1-9 bug, still open for transitional rows).
|
|
if not payload.get("event_uuid"):
|
|
payload["event_uuid"] = event.event_uuid
|
|
self.db.execute("UPDATE queue SET payload = ? WHERE id = ?",
|
|
(json.dumps(payload), rid))
|
|
self.db.commit()
|
|
|
|
result = self.client.send(event, snapshots)
|
|
if result: # SendResult.DELIVERED (only truthy result)
|
|
self.db.execute("DELETE FROM queue WHERE id = ?", (rid,))
|
|
self.db.commit()
|
|
sent += 1
|
|
continue
|
|
# Not delivered. Only a DEFINITE rejection (4xx) counts toward the poison drop cap —
|
|
# a transient outage (network error / 429 / 5xx) must retry forever so a real fall
|
|
# alert survives an overnight outage; max_rows already bounds the disk. This is the
|
|
# fix for the old bool send(), which counted every offline failure toward the cap and
|
|
# silently deleted the oldest queued safety events after ~20 flushes of downtime.
|
|
if result is SendResult.REJECTED:
|
|
attempts += 1
|
|
if attempts >= self.max_send_attempts:
|
|
self.db.execute("DELETE FROM queue WHERE id = ?", (rid,))
|
|
self.db.commit()
|
|
continue # poison dropped — let the events behind it drain
|
|
self.db.execute("UPDATE queue SET attempts = ? WHERE id = ?", (attempts, rid))
|
|
self.db.commit()
|
|
break # preserve order; retry the whole queue next flush
|
|
return sent
|
|
|
|
def pending(self) -> int:
|
|
return self.db.execute("SELECT COUNT(*) FROM queue").fetchone()[0]
|