move_detect/server/schema.sql
유창욱 e00ad69aa3 feat(safety,ux): 통보·억제·증거 체계 신설 + UI/UX 감사 21건 반영
UI/UX 점검에서 시작해 "이 제품이 안전 시스템으로서 무엇이 없나"까지 내려간 작업.
두 덩어리를 한 커밋으로 둔다 — 뒤쪽 기능들이 앞쪽에서 고친 화면 위에 얹혀 있다.

━━ 1부: UI/UX 감사 21건 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

동선 — 확인(ack) 경로가 위험했다
- 스트림 정렬을 '미확인 우선'에서 엄격 시간순으로 되돌린다. 확인 상태가 연대기를
  뒤집어 사고 재구성이 불가능했고, 확인하면 그 행이 목록 밖으로 사라지며 아래 행이
  밀려 올라와 같은 좌표를 두 번 누르면 다른 이벤트가 확인 처리됐다. 이제 제자리에서
  '확인됨'으로 전환되고 확정 토스트가 뜬다. 처리 큐는 정렬이 아니라 뷰모드 필터로 분리
  (전환해도 행끼리 상대 순서는 절대 안 바뀐다).
- 실행취소는 넣지 않았다. acknowledged_by는 감사로그가 함께 남는 추가 전용 기록이라
  무음 되돌리기가 안전 시스템에서 더 나쁜 속성이다. 대신 오탐·구역삭제를 2단계 확정으로.
- 이벤트 상세에 확인/오탐 신설. 판단하는 화면에 판단 도구가 없었다.
- 구역 설정에 장치·카메라 선택기. 시스템이 아는 값을 사람에게 묻고 있었고,
  플레이스홀더(device-01)마저 실제와 다른 포맷을 가르쳤다.
- 날짜 조회(키셋 커서 시딩). 사고 조사 진입로가 아예 없어 '더 보기'를 반복해야 했다.
- 경보음 세션 음소거(새 위급 도착 시 자동 해제). 끌 수 없는 반복음은 안전 콘솔이
  통째로 꺼지는 경로다.

전달 — 같은 단어가 화면마다 다른 숫자를 가리켰다
- KPI '미확인'(최근 200건)과 24시간 브리프 '미확인'이 40px 간격으로 충돌했다.
  KPI에 실제 집계 범위를 명시. 중대=위급+높음을 인라인 정의.
- 페이지 명칭 3종·날짜 포맷 3종 통일. '확인 필요' 칩을 전 심각도로 확장
  (그전엔 확인 여부가 먼 컬럼의 버튼 유무로만 구분됐다).
- 표본 게이트: 오탐율 '100% (1/1)'이 '33% (5/15)'보다 위에 뜨던 것, 최다 3건짜리
  시간패턴 히트맵, 6→8건에 붙던 빨간 ▲33%. 개선조치 효과는 푸아송 잡음 범위(√before)를
  넘어야 방향을 주장한다 — 안전회의에서 한 번 반박당하면 카드 전체가 신뢰를 잃는다.
- 카메라 위험 순위가 중대>0이면 전부 빨강이라 순위 노릇을 못 했다. 상대 기준으로.

시각 — 화면마다 완성도가 달랐다
- 구역 설정·이벤트 상세를 카드 셸로 재구성. 둘 다 스타일 없는 기본 폼이었고,
  납품 심사에서 "덜 만든 티"는 정확히 거기서 났다.
- 히트맵 토글은 aria-pressed만 있고 CSS 규칙이 없어 켜졌는지 눈으로 알 수 없었다.
- 존 색을 팔레트와 정합(팔레트 어디에도 없던 보라 제거), 채움+라벨칩+협착 점선.
  캔버스에 1px 외곽선만 그리면 실제 공장 프레임에서 사라진다.

━━ 2부: 안전 플랫폼 (마이그레이션 2026-08-09-safety-platform.sql) ━━━

통보 — 이 제품의 정의에 해당하는 구멍
  지금까지 감지는 브라우저 탭이 열려 있고 사람이 보고 있어야만 전달됐다. 새벽 3시에
  넘어진 작업자는 DB에 행 하나를 남기고 아침을 맞았다.
- 엣지 GPIO 경광등(edge/beacon.py). 인터넷·서버 없이 동작하는 유일한 경로라
  어떤 현장이든 이것부터 설정한다. /api/config의 beacons로 배선을 받고, 하드웨어가
  없거나 핀이 안 열리면 NullBeacon으로 떨어지되 그 사실은 반드시 로그로 남긴다.
- 메일·웹훅 채널 + 크론 디스패처(tools/dispatch_alerts.php). 중복 발송은 읽고-쓰기가
  아니라 (event,channel) UNIQUE로 막는다 — 크론 중첩 실행은 공유호스팅의 상수다.
- 미확인 위급은 unacked_escalation 이벤트가 되어 상위 채널로 올라간다(event_uuid로 멱등).
  '아무도 보지 않았다'는 사실 자체를 사건으로 만든다.
- 통보에 이미지는 싣지 않는다. 스냅샷은 PIPA 대상이고 메일링 리스트로 나가는 순간
  인증 프록시가 지키던 통제를 벗어난다 — 링크만 보낸다.

조용한 실패 제거
- 카메라 화각 이동·가림·조도 저하 감지(detectors/integrity.py). 존 판정은 화각 고정을
  전제로 서 있는데, 삼각대를 스치면 제한구역이 엉뚱한 바닥을 가리키면서 시스템은 계속
  초록불이었다. numpy만 사용하고, 지나가는 사람과 구분하기 위해 지속시간을 요구한다.
- 스토리지 여유 감시. 디스크가 차면 이미지 저장만 조용히 실패하고 보드는 멀쩡해 보인다.

끊겨 있던 배선 2건
- thresholds_from_config()가 정의만 있고 어디서도 호출되지 않았다. 서버에 표가 있고
  /api/config가 성실히 실어 보내고 엣지가 파싱한 뒤 버렸다 — 관리자가 무엇을 바꿔도
  장비는 부팅 시 edge.env 값으로 영원히 돌았다(edge/tuning.py).
- 존·임계값 저장이 config_version을 올리지 않아 '설정 지연' 표시가 애초에 켜질 수
  없었다. 지표는 있는데 그것을 켜는 사건이 없었다.

관리 화면 (그전에는 phpMyAdmin이 유일한 방법이었다)
- 임계값 편집: 자유 텍스트가 아니라 카탈로그(범위·단위·설명)로 렌더한다. 범위 밖 값은
  엣지가 기동 시 거부하는데 그때는 이미 공장 안 장비가 재시작 루프다. 키보드 앞에서 막는다.
  목록에 없는 키는 저장 불가 — 장비가 조용히 무시할 값이 '설정됨'으로 보이면 안 된다.
- 정비 억제: 사유 필수, 최대 8시간(한 교대), 자동 만료. 감지와 기록은 그대로 계속되고
  통보만 보류되며 그 보류도 원장에 status='suppressed'로 남는다 — 조사에서 '경보가 났지만
  의도적으로 withheld됐다'를 볼 수 있어야 한다.
- 교대 인수인계, 위험성평가, 설비 성능 추이, 설치 점검(/setup — 실제 상태 조회 기반).

증거·규정
- 감사로그 해시체인. 공유호스팅은 append-only 권한을 줄 수 없으니 '막는' 대신 '숨길 수
  없게' 만든다. 수정·삭제·우회삽입이 전부 탐지되고(tools/verify_audit_chain.php, 손상 시
  exit 1), 체인 이전 행은 손상이 아니라 '검증 불가 구간'으로 따로 센다 — 정상 시스템이
  매번 빨간불을 켜면 아무도 이 도구를 안 본다.
- 사고조사 패키지 1클릭: 전후 타임라인 + 통보 이력(누구에게 닿았는가) + 위험요인 +
  조치 이력 + 서명란. 인쇄 CSS로 그대로 제출 가능. 사고 다음 날 반나절을 쓸 사람은 없다.
- 이벤트→조치 직접 기록, 현장별 롤업(전역 계정만).

운영
- 일괄 확인(위급은 의도적으로 제외·2단계 확정), 키보드 트리아지(J/K/A/F/Enter),
  모바일 레이아웃(44px 타깃), 보존기간 정리(tools/maintain.php),
  백업/복구(tools/backup.php — www 안 출력은 거부), 데모 시드(tools/seed_demo.php).
- tools/는 전부 CLI 전용이고 납품 시 move_detect_app/tools/에 www 밖으로 배치된다.

미착수 4건 (모델·하드웨어가 선행 조건)
- 보호구·중장비 근접·화재 감지는 AGPL 아닌 가중치 확보 + HEF 컴파일이 관문이다.
  감지기 배선·이벤트 계약·심각도·쿨다운·테스트까지 만들고 기본 비활성으로 둔다
  (edge/detectors/pending.py). enabled=True인데 model=None이면 아무것도 하지 않도록
  명시적으로 막았다 — "곧 됩니다" 상태로 켜 두면 현장은 감지되고 있다고 믿는다.
- PLC 접점 협착 게이팅도 같은 이유로 인터페이스만.

검증: pytest 통과(skip 3 = 하드웨어·환경) / PHPUnit 221 (skip 0, +59).
Chrome 실렌더로 신규 4화면 + 임계값 저장→config_version 증가→감사 기록→체인 검증→
행 변조→탐지(exit 1) 전 경로 확인. cafe24 번들 + Pi 오프라인 번들(aarch64 휠 11개)
재생성, 소스 패리티 통과. 보안 자체점검: SQL 문자열 보간 0, innerHTML 0,
상태 변경 핸들러 전부 CSRF+RBAC.
2026-08-18 07:51:23 +09:00

437 lines
25 KiB
SQL

-- cloud/schema.sql
-- MySQL 8.0+ DDL for the P1-B cloud ingest + dashboard subset
-- (backing store for App\Repository\Pdo\* -- see cloud/src/Repository/Pdo/).
--
-- Scope: this is the P1-B subset of the full design-spec schema (design doc §7.4).
-- Tables/columns that belong to later phases are intentionally OMITTED here (YAGNI):
-- sites, escalations, oncall, compliance, retention_policy, audit hash-chaining
-- (prev_hash/hash on audit_log), and events.disposition/is_test/legal_hold/lifecycle_state.
-- See docs/superpowers/specs/2026-07-11-workplace-safety-ai-cctv-design.md §7.4 and the
-- Task 16 brief self-review for the P1-B / P2 / P3 split.
--
-- sqlite compatibility notes (cloud/tests/PdoIntegrationTest.php uses its own minimal
-- sqlite-flavored DDL for the tables it round-trips -- this file targets MySQL only,
-- these notes exist to explain the mechanical translation if that ever needs to grow):
-- * `INT ... AUTO_INCREMENT` -> sqlite: `INTEGER PRIMARY KEY AUTOINCREMENT` (must be the
-- table's sole INTEGER PRIMARY KEY column)
-- * `ENGINE=InnoDB` -> sqlite: omit (no storage engines)
-- * `DEFAULT CHARSET=...` -> sqlite: omit
-- * `JSON` column type -> sqlite: `TEXT` (no native JSON type; app always
-- reads/writes JSON-encoded strings either way)
-- * `DEFAULT (UNIX_TIMESTAMP())` -> sqlite: `DEFAULT (strftime('%s','now'))`
-- * `INSERT ... ON DUPLICATE KEY UPDATE` (rate_limits upsert) -> sqlite:
-- `INSERT ... ON CONFLICT(rate_key, window_start)
-- DO UPDATE SET count = count + 1`
-- * `CHECK (...)` on enum-like columns -> sqlite supports CHECK natively, no change
-- * `TINYINT(1)` -> sqlite: `INTEGER` (0/1)
-- * `BIGINT UNSIGNED` -> sqlite: `INTEGER` (sqlite ints are always 64-bit signed)
--
-- All app-level SQL against this schema uses prepared statements with `?` placeholders --
-- no string interpolation of values anywhere in App\Repository\Pdo\*.
SET NAMES utf8mb4;
-- ---------------------------------------------------------------------------
-- users: dashboard accounts (auth + RBAC + brute-force lockout).
-- No PdoUserRepository::create() exists in P1-B -- the first admin account is
-- provisioned out-of-band via the CLI snippet in cloud/docs/cloud-deploy.md.
-- ---------------------------------------------------------------------------
CREATE TABLE move_users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(190) NOT NULL,
password_hash VARCHAR(255) NOT NULL, -- Argon2id, see App\Security\Password::hash()
role VARCHAR(32) NOT NULL, -- app-whitelisted: admin|operator|viewer (App\Auth\Rbac)
site_scope VARCHAR(190) NULL,
failed_attempts INT UNSIGNED NOT NULL DEFAULT 0,
locked_until BIGINT UNSIGNED NOT NULL DEFAULT 0, -- unix timestamp; 0 = not locked
created_at BIGINT UNSIGNED NOT NULL DEFAULT (UNIX_TIMESTAMP()),
PRIMARY KEY (id),
UNIQUE KEY uq_users_username (username),
CONSTRAINT chk_users_role CHECK (role IN ('admin','operator','viewer'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- devices: one row per Pi/edge device; holds the per-device HMAC ingest secret.
-- No PdoDeviceRepository::create() exists -- rows are provisioned by an admin
-- (per-device secret issuance) before the device is allowed to sync/ingest.
-- ---------------------------------------------------------------------------
CREATE TABLE move_devices (
device_id VARCHAR(64) NOT NULL,
name VARCHAR(190) NULL,
site VARCHAR(64) NULL, -- access-control scope; matches users.site_scope (NULL = unassigned)
secret VARCHAR(255) NOT NULL, -- per-device HMAC key; rotate via admin CLI, never log
config_version INT UNSIGNED NOT NULL DEFAULT 1, -- authoritative version served by GET /api/config
last_fps DOUBLE NULL,
last_temp DOUBLE NULL,
last_throttle TINYINT(1) NULL,
reported_config_version INT UNSIGNED NULL, -- version the device last claimed via heartbeat
last_heartbeat_at BIGINT UNSIGNED NULL,
created_at BIGINT UNSIGNED NOT NULL DEFAULT (UNIX_TIMESTAMP()),
PRIMARY KEY (device_id),
KEY ix_devices_site (site)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- cameras: per-device camera inventory (design doc §7.4). No dedicated
-- PdoCameraRepository exists in P1-B -- zones/events reference camera_id
-- directly as a free-form string. Kept for documentation/future per-camera
-- config and to avoid a breaking migration when that repository is added.
-- ---------------------------------------------------------------------------
CREATE TABLE move_cameras (
camera_id VARCHAR(64) NOT NULL,
device_id VARCHAR(64) NOT NULL,
name VARCHAR(190) NULL,
role VARCHAR(32) NULL, -- app-whitelisted: fall_critical|zone|low
created_at BIGINT UNSIGNED NOT NULL DEFAULT (UNIX_TIMESTAMP()),
PRIMARY KEY (camera_id),
KEY ix_cameras_device (device_id),
CONSTRAINT chk_cameras_role CHECK (role IS NULL OR role IN ('fall_critical','zone','low'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- zones: polygon regions per camera, edited via the zone-config dashboard.
-- No FK to cameras/devices: zones may legitimately be created before a
-- `cameras` row exists for a given camera_id (no camera-registration flow in
-- P1-B), so a FK here would spuriously reject valid app writes.
-- ---------------------------------------------------------------------------
-- ---------------------------------------------------------------------------
-- Improvement action log (개선 조치): a site fix ("미끄럼 매트 설치") recorded against a
-- camera; the report compares detection density before/after to prove the fix worked.
-- ---------------------------------------------------------------------------
CREATE TABLE move_actions (
action_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
camera_id VARCHAR(64) NOT NULL,
site VARCHAR(64) NULL, -- access-control scope, resolved from the camera's events at insert
event_id INT UNSIGNED NULL, -- 이 조치의 계기가 된 사건 (상세 화면에서 바로 기록할 때)
note VARCHAR(500) NOT NULL,
taken_at BIGINT UNSIGNED NOT NULL, -- when the fix went in (epoch s)
created_by VARCHAR(190) NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (action_id),
KEY ix_actions_taken (taken_at),
KEY ix_actions_site_taken (site, taken_at),
KEY ix_actions_event (event_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE move_zones (
zone_id CHAR(32) NOT NULL, -- bin2hex(random_bytes(16)), same convention as snapshot uuids
device_id VARCHAR(64) NOT NULL,
camera_id VARCHAR(64) NOT NULL,
level VARCHAR(16) NOT NULL, -- app-whitelisted: warning|restricted|pinch (ZoneConfigController::LEVELS)
polygon_json JSON NOT NULL,
rules_json JSON NULL, -- optional occupancy rules: {"min_workers","max_workers","max_dwell_s"} (ZoneConfigController validates)
updated_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (zone_id),
KEY ix_zones_camera (camera_id),
KEY ix_zones_device (device_id),
CONSTRAINT chk_zones_level CHECK (level IN ('warning','restricted','pinch'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- events: ingested detections. event_type/severity are already validated in
-- App\Ingest\EventValidator before insert(); the CHECK constraints below are
-- defense-in-depth only, not the primary validation layer.
-- ---------------------------------------------------------------------------
CREATE TABLE move_events (
event_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
event_uuid CHAR(32) NULL, -- edge-generated idempotency key (dedup a re-sent event); NULL for legacy rows
device_id VARCHAR(64) NOT NULL,
site VARCHAR(64) NULL, -- denormalized from move_devices.site at ingest; access-control scope
camera_id VARCHAR(64) NOT NULL,
event_type VARCHAR(32) NOT NULL,
severity VARCHAR(16) NOT NULL,
track_id INT NULL,
zone_id CHAR(32) NULL,
occurred_at DOUBLE NOT NULL, -- device-reported epoch seconds (float)
duration_s DOUBLE NOT NULL DEFAULT 0,
metrics_json JSON NULL,
spatial_x DOUBLE NULL, -- normalized foot/reference point (0..1 of the frame),
spatial_y DOUBLE NULL, -- heatmap raw material; NULL for legacy/deviceless events
acknowledged_by VARCHAR(190) NULL,
acknowledged_at BIGINT UNSIGNED NULL,
false_positive_by VARCHAR(190) NULL, -- operator's 오탐 tag (per-camera FP-rate stats; no auto-tuning)
false_positive_at BIGINT UNSIGNED NULL,
received_at BIGINT UNSIGNED NOT NULL, -- server receipt time (PHP time()), for clock-skew flagging (design doc §8)
PRIMARY KEY (event_id),
-- Idempotency: a UNIQUE key on event_uuid makes a re-sent event (POST succeeded server-side
-- but the ACK timed out client-side) collide instead of duplicating. MySQL allows multiple
-- NULLs in a UNIQUE index, so legacy rows without a uuid do not conflict.
UNIQUE KEY uq_events_uuid (event_uuid),
KEY ix_events_occurred_at (occurred_at),
KEY ix_events_severity_occurred_at (severity, occurred_at),
KEY ix_events_site_occurred_at (site, occurred_at), -- site-scoped dashboard list (P3-2b)
KEY ix_events_device (device_id),
KEY ix_events_camera (camera_id, event_id), -- zone editor: newest snapshot per camera
CONSTRAINT chk_events_type CHECK (event_type IN (
'fall','no_motion','immobility','ghost','zone_warning',
'zone_restricted','pinch','monitoring_degraded','device_fault',
'lone_worker','overcapacity','overstay','near_fall','ergo_report',
-- 감시 자체의 건전성: 카메라가 틀어지거나 가려지면 존 판정이 조용히 무의미해진다.
'camera_moved','camera_obstructed','low_light',
-- 아무도 확인하지 않았다는 사실 자체를 사건으로 만든다 (에스컬레이션 디스패처가 발행).
'unacked_escalation',
-- 모델 확보 후 활성화되는 자리. 엣지 감지기는 있으나 기본 비활성이다.
'ppe_missing','proximity','fire_smoke'
)),
CONSTRAINT chk_events_severity CHECK (severity IN ('critical','high','warning','info'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- event_snapshots: re-encoded JPEG references. Files live under storage/
-- (webroot-adjacent, served only via the authenticated SnapshotProxy). FK to
-- events is safe because IngestController always inserts the parent event row
-- before calling SnapshotRepository::add() for its snapshots.
-- ---------------------------------------------------------------------------
CREATE TABLE move_event_snapshots (
snapshot_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
event_id INT UNSIGNED NOT NULL,
file_uuid CHAR(32) NOT NULL, -- bin2hex(random_bytes(16)); on-disk filename = <uuid>.jpg
content_hash CHAR(64) NOT NULL, -- sha256 of the re-encoded bytes
created_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (snapshot_id),
UNIQUE KEY uq_event_snapshots_uuid (file_uuid),
-- Idempotent snapshot recovery: a re-sent event carries the SAME re-encoded bytes (same
-- content_hash), so this makes a duplicate/racing store collide instead of writing a second
-- copy. Lets the dedup path safely re-store missing evidence without duplication.
UNIQUE KEY uq_event_snapshots_event_hash (event_id, content_hash),
KEY ix_event_snapshots_event (event_id),
KEY ix_event_snapshots_created (created_at), -- retention purge scans WHERE created_at < ?
CONSTRAINT fk_event_snapshots_event FOREIGN KEY (event_id) REFERENCES move_events (event_id)
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- thresholds: per-device (optionally per-camera/zone) tunables synced via
-- GET /api/config. No PdoThresholdRepository write method exists in P1-B --
-- rows are seeded/edited directly (phpMyAdmin) until a management UI lands.
-- ---------------------------------------------------------------------------
CREATE TABLE move_thresholds (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
device_id VARCHAR(64) NOT NULL,
camera_id VARCHAR(64) NULL,
zone_id CHAR(32) NULL,
`key` VARCHAR(64) NOT NULL,
`value` VARCHAR(255) NOT NULL,
updated_by VARCHAR(190) NULL, -- 편집 UI(관리자 전용)가 남기는 감사 흔적
updated_at BIGINT UNSIGNED NULL,
PRIMARY KEY (id),
KEY ix_thresholds_device (device_id),
UNIQUE KEY uq_thresholds_scope_key (device_id, camera_id, zone_id, `key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- nonces: replay-protection store for ingest/config/heartbeat HMAC requests.
-- `nonce` is the PRIMARY KEY (unique) so PdoNonceRepository::remember() is
-- safe against a duplicate-insert race: IngestController already calls
-- seen() before remember(), and a thrown duplicate-key error on a racing
-- remember() is an acceptable, expected outcome (closes the seen()/remember()
-- TOCTOU flagged in the Task 7 review -- the PK uniqueness is the real guard,
-- not the earlier seen() check).
-- ---------------------------------------------------------------------------
CREATE TABLE move_nonces (
nonce VARCHAR(190) NOT NULL,
expires_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (nonce),
KEY ix_nonces_expires_at (expires_at) -- for a periodic `DELETE FROM move_nonces WHERE expires_at < ?` cleanup job
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- rate_limits: per-key sliding-window counters for ingest rate limiting. The
-- (rate_key, window_start) primary key backs an atomic
-- `INSERT ... ON DUPLICATE KEY UPDATE count = count + 1` upsert in
-- PdoRateLimiterRepository::hit() -- no read-modify-write race window.
-- ---------------------------------------------------------------------------
CREATE TABLE move_rate_limits (
rate_key VARCHAR(190) NOT NULL,
window_start BIGINT UNSIGNED NOT NULL, -- floor(now / 60): the minute bucket
count INT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (rate_key, window_start),
-- The reap `DELETE ... WHERE window_start < ?` cannot use the PK (window_start is its trailing
-- column), so give it its own index to avoid a locking full-scan on the pre-auth hot path.
KEY ix_rate_limits_window (window_start)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- audit_log: append-only action log (acknowledge / zone save+delete / login /
-- threshold edit / suppression / handover).
--
-- TAMPER-EVIDENT: each row carries prev_hash (the previous row's entry_hash) and
-- entry_hash = sha256(id|actor|action|target|before|after|ts|prev_hash). Editing or
-- deleting a row breaks every hash after it, so a doctored log is DETECTABLE even
-- though shared hosting cannot grant append-only rights at the DB level. Verified by
-- `php tools/verify_audit_chain.php`. Rows written before the chain existed keep NULL
-- hashes and the verifier reports them as the pre-chain segment rather than as damage.
-- ---------------------------------------------------------------------------
CREATE TABLE move_audit_log (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
actor VARCHAR(190) NOT NULL,
action VARCHAR(64) NOT NULL,
target VARCHAR(190) NOT NULL,
before_json JSON NOT NULL,
after_json JSON NOT NULL,
ts BIGINT UNSIGNED NOT NULL,
prev_hash CHAR(64) NULL,
entry_hash CHAR(64) NULL,
PRIMARY KEY (id),
KEY ix_audit_log_ts (ts),
KEY ix_audit_log_actor (actor),
KEY ix_audit_log_entry_hash (entry_hash)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- suppressions: planned-work alarm suppression (정비 모드 / 작업허가).
-- Detection is NOT paused -- events are still ingested and still appear in the console
-- and in reports. Only NOTIFICATION is withheld, and every suppression carries a
-- mandatory reason, a hard expiry (no open-ended suppression) and an audit entry.
-- Rationale: the single largest source of false alarms is planned maintenance, and a
-- console that cries wolf during every shutdown is a console the site switches off.
-- ---------------------------------------------------------------------------
CREATE TABLE move_suppressions (
suppression_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
scope_type VARCHAR(16) NOT NULL, -- device | camera | zone
scope_id VARCHAR(64) NOT NULL,
site VARCHAR(64) NULL,
reason VARCHAR(500) NOT NULL,
starts_at BIGINT UNSIGNED NOT NULL,
ends_at BIGINT UNSIGNED NOT NULL,
created_by VARCHAR(190) NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
revoked_by VARCHAR(190) NULL,
revoked_at BIGINT UNSIGNED NULL,
PRIMARY KEY (suppression_id),
KEY ix_suppressions_window (ends_at, starts_at),
KEY ix_suppressions_scope (scope_type, scope_id),
KEY ix_suppressions_site (site),
CONSTRAINT chk_suppressions_scope CHECK (scope_type IN ('device','camera','zone'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- alert_channels / alert_log: how a detection reaches a human.
-- Air-gapped sites cannot use FCM/Slack, so the channels are the ones a closed network
-- actually has: `local` (the edge node's own beacon/buzzer over GPIO -- the only path
-- that needs no network at all), `email` (in-house SMTP relay) and `webhook` (in-house
-- groupware / SMS gateway). step>0 channels fire only after escalate_after_s of the
-- event still being unacknowledged, which is what turns "we detected it" into "someone
-- was made to look at it".
-- ---------------------------------------------------------------------------
CREATE TABLE move_alert_channels (
channel_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
site VARCHAR(64) NULL,
kind VARCHAR(16) NOT NULL,
name VARCHAR(190) NOT NULL,
config_json JSON NOT NULL, -- recipients / url / gpio pin. NEVER credentials.
min_severity VARCHAR(16) NOT NULL DEFAULT 'high',
enabled TINYINT(1) NOT NULL DEFAULT 1,
step INT UNSIGNED NOT NULL DEFAULT 0,
escalate_after_s INT UNSIGNED NOT NULL DEFAULT 0,
created_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (channel_id),
KEY ix_alert_channels_site (site, enabled),
CONSTRAINT chk_alert_channels_kind CHECK (kind IN ('local','email','webhook')),
CONSTRAINT chk_alert_channels_sev CHECK (min_severity IN ('critical','high','warning','info'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE move_alert_log (
alert_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
event_id INT UNSIGNED NOT NULL,
channel_id INT UNSIGNED NOT NULL,
status VARCHAR(16) NOT NULL,
attempts INT UNSIGNED NOT NULL DEFAULT 0,
last_error VARCHAR(500) NULL,
queued_at BIGINT UNSIGNED NOT NULL,
sent_at BIGINT UNSIGNED NULL,
PRIMARY KEY (alert_id),
-- The dispatcher runs from cron and overlapping runs are expected; this unique key is
-- the only thing standing between a site and the same fall being phoned in five times.
UNIQUE KEY uq_alert_log_event_channel (event_id, channel_id),
KEY ix_alert_log_status (status, queued_at),
CONSTRAINT chk_alert_log_status CHECK (status IN ('pending','sent','failed','suppressed')),
CONSTRAINT fk_alert_log_event FOREIGN KEY (event_id) REFERENCES move_events (event_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- shift_handovers: who took responsibility for what, and when.
-- The 24h brief tells an operator what happened; it does not record that anyone
-- accepted the backlog. Without that, unacknowledged events evaporate across a shift
-- change with nobody accountable for them.
-- ---------------------------------------------------------------------------
CREATE TABLE move_shift_handovers (
handover_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
site VARCHAR(64) NULL,
from_user VARCHAR(190) NULL,
to_user VARCHAR(190) NOT NULL,
period_start BIGINT UNSIGNED NOT NULL,
period_end BIGINT UNSIGNED NOT NULL,
unacked_count INT UNSIGNED NOT NULL,
severe_count INT UNSIGNED NOT NULL,
note VARCHAR(1000) NULL,
created_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (handover_id),
KEY ix_handovers_site_created (site, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- risk_controls: 위험성평가 연계. One row per (site, detection type): the hazard it
-- stands for, the control currently in place, and the 5x5 rating. This is what lets the
-- system print "what are we controlling and how well", which is the artefact a safety
-- management system is actually audited on.
-- ---------------------------------------------------------------------------
CREATE TABLE move_risk_controls (
control_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
site VARCHAR(64) NULL,
event_type VARCHAR(32) NOT NULL,
hazard VARCHAR(300) NOT NULL,
control VARCHAR(500) NOT NULL,
severity_rating TINYINT UNSIGNED NOT NULL,
likelihood_rating TINYINT UNSIGNED NOT NULL,
reviewed_by VARCHAR(190) NULL,
reviewed_at BIGINT UNSIGNED NULL,
updated_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (control_id),
UNIQUE KEY uq_risk_controls_site_type (site, event_type),
CONSTRAINT chk_risk_sev CHECK (severity_rating BETWEEN 1 AND 5),
CONSTRAINT chk_risk_like CHECK (likelihood_rating BETWEEN 1 AND 5)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ---------------------------------------------------------------------------
-- device_metrics: heartbeat telemetry as a TIME SERIES.
-- move_devices holds only the latest value, so a node whose inference latency doubled
-- overnight looks identical to a healthy one. Appending each heartbeat is what makes
-- slow degradation visible before it becomes a monitoring outage.
-- ---------------------------------------------------------------------------
CREATE TABLE move_device_metrics (
metric_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
device_id VARCHAR(64) NOT NULL,
ts BIGINT UNSIGNED NOT NULL,
fps DOUBLE NULL,
temp DOUBLE NULL,
throttle TINYINT(1) NULL,
queue_pending INT UNSIGNED NULL,
cameras_total INT UNSIGNED NULL,
cameras_erroring INT UNSIGNED NULL,
errors INT UNSIGNED NULL,
PRIMARY KEY (metric_id),
KEY ix_device_metrics_device_ts (device_id, ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ===========================================================================
-- UPGRADING AN EXISTING DATABASE (fresh installs already have everything above):
-- do NOT copy the statements below by hand — they are SQL comments and will not
-- run. Apply the RUNNABLE migration instead:
--
-- cloud/migrations/2026-07-17-p1-9-p3-2b.sql
-- cloud/migrations/2026-07-20-move-table-prefix.sql (run this one LAST)
--
-- The second migration renames every table to the `move_` prefix used above and
-- by App\Repository\Pdo\* -- an existing DB must be renamed before deploy or all
-- queries fail with "table doesn't exist".
--
-- It adds devices.site / events.site / events.event_uuid, the retention and
-- rate-limit reap indexes, AND backfills events.site from move_devices.site (without
-- that backfill, historical events vanish for a scoped operator). Run it once in
-- phpMyAdmin BEFORE deploying code that reads these columns, then provision:
-- UPDATE move_devices SET site = 'factory-a' WHERE device_id = 'pi-1';
-- UPDATE move_users SET site_scope = 'factory-a' WHERE username = 'operator-a';
-- A user with site_scope = NULL is a global operator; '' is NOT global (matches
-- nothing — a blank scope fails closed).
-- ===========================================================================