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.
459 lines
26 KiB
PHP
459 lines
26 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace App\Tests\Support;
|
|
use App\Repository\{DeviceRepository, NonceRepository, RateLimiterRepository,
|
|
EventRepository, SnapshotRepository, UserRepository, ZoneRepository,
|
|
ThresholdRepository, AuditRepository, ActionRepository, SuppressionRepository,
|
|
AlertRepository, HandoverRepository, RiskControlRepository, DeviceMetricRepository};
|
|
|
|
final class InMemoryDeviceRepository implements DeviceRepository {
|
|
public array $heartbeats = [];
|
|
// $statusRows: full device rows for listStatus() (the status panel tests populate it). Kept a
|
|
// trailing optional arg so the many existing 3-arg call sites are unaffected.
|
|
public function __construct(private array $secrets = [], private array $versions = [],
|
|
private array $sites = [], public array $statusRows = []) {}
|
|
public function secretFor(string $d): ?string { return $this->secrets[$d] ?? null; }
|
|
public function exists(string $d): bool {
|
|
// A device is "known" if it appears in any provisioned map the test set up.
|
|
return isset($this->secrets[$d]) || isset($this->sites[$d]) || isset($this->versions[$d]);
|
|
}
|
|
public function siteFor(string $d): ?string { return $this->sites[$d] ?? null; }
|
|
public function touchHeartbeat(string $d, array $m): void { $this->heartbeats[$d] = $m; }
|
|
public function configVersion(string $d): int { return $this->versions[$d] ?? 1; }
|
|
public function bumpConfigVersion(string $d): int {
|
|
if (!isset($this->secrets[$d]) && !isset($this->versions[$d])) return 0;
|
|
$this->versions[$d] = ($this->versions[$d] ?? 1) + 1;
|
|
return $this->versions[$d];
|
|
}
|
|
public function listStatus(?string $site): array {
|
|
$rows = $this->statusRows;
|
|
if ($site !== null) $rows = array_filter($rows, fn($d) => ($d['site'] ?? null) === $site);
|
|
return array_values($rows);
|
|
}
|
|
}
|
|
final class InMemoryNonceRepository implements NonceRepository {
|
|
public array $store = [];
|
|
public function seen(string $n): bool { return isset($this->store[$n]); }
|
|
public function remember(string $n, int $exp): void { $this->store[$n] = $exp; }
|
|
}
|
|
final class InMemoryRateLimiter implements RateLimiterRepository {
|
|
public array $counts = [];
|
|
public function hit(string $k, int $w): int { $key = "$k:$w"; return $this->counts[$key] = ($this->counts[$key] ?? 0) + 1; }
|
|
}
|
|
final class InMemoryEventRepository implements EventRepository {
|
|
public array $rows = []; private int $seq = 0;
|
|
public function insert(array $e): int { $id = ++$this->seq; $this->rows[$id] = $e + ['event_id' => $id, 'acknowledged_by' => null]; return $id; }
|
|
public function idByUuid(string $uuid): ?int {
|
|
foreach ($this->rows as $id => $r) if (($r['event_uuid'] ?? null) === $uuid) return (int)$id;
|
|
return null;
|
|
}
|
|
public function recent(int $limit, ?string $sev): array {
|
|
$r = array_reverse($this->rows, true);
|
|
if ($sev !== null) $r = array_filter($r, fn($x) => $x['severity'] === $sev);
|
|
return array_slice(array_values($r), 0, $limit);
|
|
}
|
|
public function page(int $limit, ?string $sev, ?string $beforeTs, ?int $beforeId, ?string $site = null): array {
|
|
$r = array_values($this->rows);
|
|
if ($sev !== null) $r = array_filter($r, fn($x) => $x['severity'] === $sev);
|
|
if ($site !== null) $r = array_filter($r, fn($x) => ($x['site'] ?? null) === $site);
|
|
// (occurred_at DESC, event_id DESC); events inserted without occurred_at sort as 0.
|
|
usort($r, fn($a, $b) => [$b['occurred_at'] ?? 0, $b['event_id']] <=> [$a['occurred_at'] ?? 0, $a['event_id']]);
|
|
if ($beforeTs !== null && $beforeId !== null) {
|
|
$bt = (float)$beforeTs; // cursor carries occurred_at as a string; compare numerically
|
|
$r = array_filter($r, fn($x) => ($x['occurred_at'] ?? 0) < $bt
|
|
|| (($x['occurred_at'] ?? 0) == $bt && $x['event_id'] < $beforeId));
|
|
}
|
|
return array_slice(array_values($r), 0, $limit);
|
|
}
|
|
public function find(int $id): ?array { return $this->rows[$id] ?? null; }
|
|
public function acknowledge(int $id, string $u): bool { if (!isset($this->rows[$id])) return false; $this->rows[$id]['acknowledged_by'] = $u; $this->rows[$id]['acknowledged_at'] = $this->rows[$id]['acknowledged_at'] ?? time(); return true; }
|
|
public function markFalsePositive(int $id, string $user): bool {
|
|
if (!isset($this->rows[$id])) return false;
|
|
$r = $this->rows[$id];
|
|
$r['false_positive_by'] = $r['false_positive_by'] ?? $user;
|
|
$r['false_positive_at'] = $r['false_positive_at'] ?? time();
|
|
$r['acknowledged_by'] = ($r['acknowledged_by'] ?? null) !== null ? $r['acknowledged_by'] : $user;
|
|
$this->rows[$id] = $r;
|
|
return true;
|
|
}
|
|
public function fpStats(float $since, ?string $site): array {
|
|
$groups = [];
|
|
foreach ($this->rows as $r) {
|
|
if (($r['occurred_at'] ?? 0) < $since) continue;
|
|
if ($site !== null && ($r['site'] ?? null) !== $site) continue;
|
|
$key = ($r['camera_id'] ?? '') . '|' . ($r['event_type'] ?? '');
|
|
$groups[$key] = $groups[$key] ?? ['camera_id' => $r['camera_id'], 'event_type' => $r['event_type'], 'total' => 0, 'fp' => 0];
|
|
$groups[$key]['total']++;
|
|
if (($r['false_positive_by'] ?? null) !== null) $groups[$key]['fp']++;
|
|
}
|
|
$out = array_values(array_filter($groups, fn($g) => $g['fp'] > 0));
|
|
usort($out, fn($a, $b) => $b['fp'] <=> $a['fp']);
|
|
return $out;
|
|
}
|
|
public function reportSummary(float $since, ?string $site, int $topCameras, ?float $until = null): array {
|
|
$rows = array_filter($this->rows, fn($r) => ($r['occurred_at'] ?? 0) >= $since
|
|
&& ($until === null || ($r['occurred_at'] ?? 0) < $until)
|
|
&& ($site === null || ($r['site'] ?? null) === $site));
|
|
$byType = []; $byCam = []; $ttaDeltas = []; $ergo = [];
|
|
foreach ($rows as $r) {
|
|
$tk = ($r['event_type'] ?? '') . '|' . ($r['severity'] ?? '');
|
|
$byType[$tk] = $byType[$tk] ?? ['event_type' => $r['event_type'], 'severity' => $r['severity'], 'count' => 0, 'unacked' => 0, 'fp' => 0];
|
|
$byType[$tk]['count']++;
|
|
if (($r['acknowledged_by'] ?? null) === null) $byType[$tk]['unacked']++;
|
|
if (($r['false_positive_by'] ?? null) !== null) $byType[$tk]['fp']++;
|
|
$cam = $r['camera_id'] ?? '';
|
|
$byCam[$cam] = $byCam[$cam] ?? ['camera_id' => $cam, 'count' => 0, 'critical_high' => 0];
|
|
$byCam[$cam]['count']++;
|
|
if (in_array($r['severity'] ?? '', ['critical', 'high'], true)) $byCam[$cam]['critical_high']++;
|
|
if (in_array($r['severity'] ?? '', ['critical', 'high'], true)
|
|
&& ($r['acknowledged_at'] ?? null) !== null && ($r['false_positive_by'] ?? null) === null
|
|
&& $r['acknowledged_at'] >= ($r['occurred_at'] ?? 0)) {
|
|
$ttaDeltas[] = $r['acknowledged_at'] - $r['occurred_at'];
|
|
}
|
|
if (($r['event_type'] ?? '') === 'ergo_report') $ergo[] = $r['metrics'] ?? [];
|
|
}
|
|
$cams = array_values($byCam);
|
|
usort($cams, fn($a, $b) => [$b['critical_high'], $b['count']] <=> [$a['critical_high'], $a['count']]);
|
|
return [
|
|
'by_type' => array_values($byType),
|
|
'by_camera' => array_slice($cams, 0, $topCameras),
|
|
'tta' => ['acked' => count($ttaDeltas),
|
|
'avg_s' => $ttaDeltas ? array_sum($ttaDeltas) / count($ttaDeltas) : null,
|
|
'max_s' => $ttaDeltas ? max($ttaDeltas) : null],
|
|
'ergo_metrics' => $ergo,
|
|
];
|
|
}
|
|
public function exportRows(float $since, ?string $site, int $limit): array {
|
|
$r = array_filter($this->rows, fn($x) => ($x['occurred_at'] ?? 0) >= $since
|
|
&& ($site === null || ($x['site'] ?? null) === $site));
|
|
usort($r, fn($a, $b) => [$b['occurred_at'] ?? 0, $b['event_id']] <=> [$a['occurred_at'] ?? 0, $a['event_id']]);
|
|
return array_slice(array_values($r), 0, $limit);
|
|
}
|
|
public function forNotification(float $since, int $limit): array {
|
|
$r = array_filter($this->rows, fn($x) => ($x['occurred_at'] ?? 0) >= $since);
|
|
usort($r, fn($a, $b) => [$a['occurred_at'] ?? 0, $a['event_id']] <=> [$b['occurred_at'] ?? 0, $b['event_id']]);
|
|
return array_slice(array_values($r), 0, $limit);
|
|
}
|
|
public function siteSummary(float $since, ?float $until = null): array {
|
|
$by = [];
|
|
foreach ($this->rows as $r) {
|
|
if (($r['occurred_at'] ?? 0) < $since) continue;
|
|
if ($until !== null && ($r['occurred_at'] ?? 0) >= $until) continue;
|
|
if (($r['event_type'] ?? '') === 'ergo_report') continue;
|
|
$s = $r['site'] ?? null;
|
|
$k = $s === null ? "\x00" : $s;
|
|
if (!isset($by[$k])) $by[$k] = ['site' => $s, 'count' => 0, 'critical_high' => 0,
|
|
'unacked' => 0, 'cameras' => [], ];
|
|
$by[$k]['count']++;
|
|
if (in_array($r['severity'] ?? '', ['critical', 'high'], true)) $by[$k]['critical_high']++;
|
|
if (empty($r['acknowledged_by'])) $by[$k]['unacked']++;
|
|
if (!empty($r['camera_id'])) $by[$k]['cameras'][$r['camera_id']] = true;
|
|
}
|
|
$out = array_map(fn($x) => ['site' => $x['site'], 'count' => $x['count'],
|
|
'critical_high' => $x['critical_high'], 'unacked' => $x['unacked'],
|
|
'cameras' => count($x['cameras'])], array_values($by));
|
|
usort($out, fn($a, $b) => [$b['critical_high'], $b['count']] <=> [$a['critical_high'], $a['count']]);
|
|
return $out;
|
|
}
|
|
public function windowForCamera(string $cam, float $from, float $to, ?string $site, int $limit): array {
|
|
$r = array_filter($this->rows, fn($x) => ($x['camera_id'] ?? '') === $cam
|
|
&& ($x['occurred_at'] ?? 0) >= $from && ($x['occurred_at'] ?? 0) < $to
|
|
&& ($site === null || ($x['site'] ?? null) === $site));
|
|
usort($r, fn($a, $b) => [$a['occurred_at'] ?? 0, $a['event_id']] <=> [$b['occurred_at'] ?? 0, $b['event_id']]);
|
|
return array_slice(array_values($r), 0, $limit);
|
|
}
|
|
public function countForCamera(string $cam, float $from, float $to, ?string $site): int {
|
|
return count(array_filter($this->rows, fn($x) => ($x['camera_id'] ?? '') === $cam
|
|
&& ($x['occurred_at'] ?? 0) >= $from && ($x['occurred_at'] ?? 0) < $to
|
|
&& ($x['event_type'] ?? '') !== 'ergo_report'
|
|
&& ($site === null || ($x['site'] ?? null) === $site)));
|
|
}
|
|
public function purgeOlderThan(float $cutoff, int $limit = 500): int {
|
|
$old = array_filter($this->rows, fn($r) => ($r['occurred_at'] ?? 0) < $cutoff);
|
|
$n = 0;
|
|
foreach (array_keys($old) as $id) {
|
|
if ($n >= $limit) break;
|
|
unset($this->rows[$id]); $n++;
|
|
}
|
|
return $n;
|
|
}
|
|
public function cameraExists(string $cam): bool {
|
|
foreach ($this->rows as $r) if (($r['camera_id'] ?? '') === $cam) return true;
|
|
return false;
|
|
}
|
|
public function siteForCamera(string $cam): ?string {
|
|
$best = null;
|
|
foreach ($this->rows as $r) {
|
|
if (($r['camera_id'] ?? '') !== $cam || ($r['site'] ?? null) === null) continue;
|
|
if ($best === null || ($r['event_id'] ?? 0) >= ($best['event_id'] ?? 0)) $best = $r;
|
|
}
|
|
return $best === null ? null : (string)$best['site'];
|
|
}
|
|
public function occurrenceTimes(float $since, ?string $site, int $limit): array {
|
|
$r = array_filter($this->rows, fn($x) => ($x['occurred_at'] ?? 0) >= $since
|
|
&& ($x['event_type'] ?? '') !== 'ergo_report'
|
|
&& ($site === null || ($x['site'] ?? null) === $site));
|
|
usort($r, fn($a, $b) => ($b['occurred_at'] ?? 0) <=> ($a['occurred_at'] ?? 0));
|
|
return array_map(fn($x) => ['occurred_at' => (float)($x['occurred_at'] ?? 0),
|
|
'event_type' => $x['event_type']], array_slice(array_values($r), 0, $limit));
|
|
}
|
|
public function heatmapPoints(string $cameraId, float $since, ?string $site, int $limit): array {
|
|
$r = array_filter($this->rows, fn($x) => ($x['camera_id'] ?? '') === $cameraId
|
|
&& ($x['occurred_at'] ?? 0) >= $since
|
|
&& ($x['spatial_x'] ?? null) !== null && ($x['spatial_y'] ?? null) !== null
|
|
&& ($site === null || ($x['site'] ?? null) === $site));
|
|
usort($r, fn($a, $b) => ($b['occurred_at'] ?? 0) <=> ($a['occurred_at'] ?? 0));
|
|
return array_map(fn($x) => ['x' => (float)$x['spatial_x'], 'y' => (float)$x['spatial_y'],
|
|
'severity' => $x['severity'], 'event_type' => $x['event_type'],
|
|
'occurred_at' => (float)($x['occurred_at'] ?? 0)], array_slice(array_values($r), 0, $limit));
|
|
}
|
|
}
|
|
final class InMemorySnapshotRepository implements SnapshotRepository {
|
|
public array $rows = []; public array $paths = []; public array $created = [];
|
|
public function add(int $e, string $uuid, string $hash): void {
|
|
// Mirror the DB's UNIQUE (event_id, content_hash): a re-sent event's identical bytes
|
|
// collide instead of duplicating, so the dedup recovery path is idempotent.
|
|
foreach ($this->rows[$e] ?? [] as $r) { if ($r['content_hash'] === $hash) return; }
|
|
$this->rows[$e][] = ['file_uuid' => $uuid, 'content_hash' => $hash]; $this->paths[$uuid] = "/tmp/$uuid.jpg"; $this->created[$uuid] = time();
|
|
}
|
|
public function forEvent(int $e): array { return $this->rows[$e] ?? []; }
|
|
public function thumbUuidsFor(array $eventIds): array {
|
|
$out = [];
|
|
foreach ($eventIds as $e) {
|
|
$list = $this->rows[(int)$e] ?? [];
|
|
if ($list !== []) $out[(int)$e] = end($list)['file_uuid']; // newest = last appended
|
|
}
|
|
return $out;
|
|
}
|
|
public function pathByUuid(string $u): ?string { return $this->paths[$u] ?? null; }
|
|
public function eventIdByUuid(string $u): ?int {
|
|
foreach ($this->rows as $e => $list) foreach ($list as $r) if ($r['file_uuid'] === $u) return (int)$e;
|
|
return null;
|
|
}
|
|
/** @var array<string,string> file_uuid => camera_id, recorded by the tests that need it */
|
|
public array $cameras = [];
|
|
/** @var array<string,string> file_uuid => device_id */
|
|
public array $devices = [];
|
|
public function latestForCamera(string $cameraId): ?array {
|
|
// Insert order, newest first -- mirrors the Pdo impl's ORDER BY snapshot_id DESC.
|
|
foreach (array_reverse($this->cameras, true) as $uuid => $cam) {
|
|
if ($cam === $cameraId) return ['file_uuid' => $uuid, 'device_id' => $this->devices[$uuid] ?? ''];
|
|
}
|
|
return null;
|
|
}
|
|
public function uuidsFor(array $eventIds): array {
|
|
$out = [];
|
|
foreach ($eventIds as $e) {
|
|
foreach ($this->rows[(int)$e] ?? [] as $r) $out[(int)$e][] = $r['file_uuid'];
|
|
}
|
|
return $out;
|
|
}
|
|
public function purgeOlderThan(int $cutoff): int {
|
|
$n = 0;
|
|
foreach ($this->created as $uuid => $ts) {
|
|
if ($ts >= $cutoff) continue;
|
|
unset($this->created[$uuid], $this->paths[$uuid]);
|
|
foreach ($this->rows as $e => $list) {
|
|
$this->rows[$e] = array_values(array_filter($list, fn($r) => $r['file_uuid'] !== $uuid));
|
|
}
|
|
$n++;
|
|
}
|
|
return $n;
|
|
}
|
|
}
|
|
final class InMemoryUserRepository implements UserRepository {
|
|
public function __construct(public array $users = []) {}
|
|
public function byUsername(string $u): ?array { return $this->users[$u] ?? null; }
|
|
public function recordFailure(int $id, int $lock): void { foreach ($this->users as &$row) if ($row['id'] === $id) { $row['failed_attempts'] = ($row['failed_attempts'] ?? 0) + 1; $row['locked_until'] = $lock; } }
|
|
public function clearFailures(int $id): void { foreach ($this->users as &$row) if ($row['id'] === $id) { $row['failed_attempts'] = 0; $row['locked_until'] = 0; } }
|
|
}
|
|
final class InMemoryZoneRepository implements ZoneRepository {
|
|
public array $zones = []; private int $seq = 0;
|
|
public function forDevice(string $d): array { return array_values(array_filter($this->zones, fn($z) => ($z['device_id'] ?? '') === $d)); }
|
|
public function forCamera(string $c): array { return array_values(array_filter($this->zones, fn($z) => $z['camera_id'] === $c)); }
|
|
public function find(string $id): ?array { return $this->zones[$id] ?? null; }
|
|
public function save(array $z): string { $id = $z['zone_id'] ?? ('z' . (++$this->seq)); $this->zones[$id] = $z + ['zone_id' => $id]; return $id; }
|
|
public function delete(string $id): bool { if (!isset($this->zones[$id])) return false; unset($this->zones[$id]); return true; }
|
|
}
|
|
final class InMemoryActionRepository implements ActionRepository {
|
|
public array $rows = []; private int $seq = 0;
|
|
public function insert(array $a): int { $id = ++$this->seq; $this->rows[$id] = $a + ['action_id' => $id]; return $id; }
|
|
public function recent(int $limit, ?string $site): array {
|
|
$r = array_values(array_filter($this->rows,
|
|
fn($a) => $site === null || ($a['site'] ?? null) === $site));
|
|
usort($r, fn($a, $b) => [$b['taken_at'], $b['action_id']] <=> [$a['taken_at'], $a['action_id']]);
|
|
return array_slice($r, 0, $limit);
|
|
}
|
|
}
|
|
final class InMemoryThresholdRepository implements ThresholdRepository {
|
|
public array $rows = []; private int $seq = 0;
|
|
/** @param array $data device_id => [key => value] (the pre-editor shape many tests use) */
|
|
public function __construct(array $data = []) {
|
|
foreach ($data as $dev => $kv) foreach ($kv as $k => $v) {
|
|
$id = ++$this->seq;
|
|
$this->rows[$id] = ['id' => $id, 'device_id' => $dev, 'camera_id' => null, 'key' => $k,
|
|
'value' => (string)$v, 'updated_by' => null, 'updated_at' => null, 'site' => null];
|
|
}
|
|
}
|
|
public function forDevice(string $d): array {
|
|
// Device-wide rows only — the same contract PdoThresholdRepository has, so a test that
|
|
// passes here cannot pass for a reason the delivered query would not reproduce.
|
|
$out = [];
|
|
foreach ($this->rows as $r) if ($r['device_id'] === $d && $r['camera_id'] === null) $out[$r['key']] = $r['value'];
|
|
return $out;
|
|
}
|
|
public function listAll(?string $site): array {
|
|
return array_values(array_filter($this->rows, fn($r) => $site === null || $r['site'] === $site));
|
|
}
|
|
public function set(string $dev, ?string $cam, string $k, string $v, string $actor, int $now): int {
|
|
foreach ($this->rows as $id => $r) {
|
|
if ($r['device_id'] === $dev && $r['camera_id'] === $cam && $r['key'] === $k) {
|
|
$this->rows[$id]['value'] = $v;
|
|
$this->rows[$id]['updated_by'] = $actor;
|
|
$this->rows[$id]['updated_at'] = $now;
|
|
return $id;
|
|
}
|
|
}
|
|
$id = ++$this->seq;
|
|
$this->rows[$id] = ['id' => $id, 'device_id' => $dev, 'camera_id' => $cam, 'key' => $k,
|
|
'value' => $v, 'updated_by' => $actor, 'updated_at' => $now, 'site' => null];
|
|
return $id;
|
|
}
|
|
public function remove(int $id, ?string $site): bool {
|
|
if (!isset($this->rows[$id])) return false;
|
|
if ($site !== null && $this->rows[$id]['site'] !== $site) return false;
|
|
unset($this->rows[$id]); return true;
|
|
}
|
|
public function find(int $id): ?array { return $this->rows[$id] ?? null; }
|
|
}
|
|
final class InMemoryAuditRepository implements AuditRepository {
|
|
public array $log = [];
|
|
public function append(string $a, string $act, string $t, array $b, array $af): void { $this->log[] = compact('a', 'act', 't', 'b', 'af'); }
|
|
}
|
|
final class InMemorySuppressionRepository implements SuppressionRepository {
|
|
public array $rows = []; private int $seq = 0;
|
|
private function live(array $r, int $now): bool {
|
|
return $r['revoked_at'] === null && $r['starts_at'] <= $now && $r['ends_at'] > $now;
|
|
}
|
|
public function activeFor(array $scopes, int $now): array {
|
|
return array_values(array_filter($this->rows, function ($r) use ($scopes, $now) {
|
|
if (!$this->live($r, $now)) return false;
|
|
foreach ($scopes as [$type, $id]) if ($r['scope_type'] === $type && $r['scope_id'] === (string)$id) return true;
|
|
return false;
|
|
}));
|
|
}
|
|
public function listAll(?string $site, int $now, bool $includeExpired = false): array {
|
|
$r = array_values(array_filter($this->rows, fn($x) =>
|
|
($site === null || $x['site'] === $site) && ($includeExpired || $this->live($x, $now))));
|
|
usort($r, fn($a, $b) => $b['created_at'] <=> $a['created_at']);
|
|
return $r;
|
|
}
|
|
public function create(array $row): int {
|
|
$id = ++$this->seq;
|
|
$this->rows[$id] = $row + ['suppression_id' => $id, 'revoked_by' => null, 'revoked_at' => null];
|
|
return $id;
|
|
}
|
|
public function revoke(int $id, string $user, int $now, ?string $site): bool {
|
|
if (!isset($this->rows[$id]) || $this->rows[$id]['revoked_at'] !== null) return false;
|
|
if ($site !== null && $this->rows[$id]['site'] !== $site) return false;
|
|
$this->rows[$id]['revoked_by'] = $user; $this->rows[$id]['revoked_at'] = $now; return true;
|
|
}
|
|
public function find(int $id): ?array { return $this->rows[$id] ?? null; }
|
|
}
|
|
final class InMemoryAlertRepository implements AlertRepository {
|
|
public array $chan = []; public array $log = []; private int $seq = 0;
|
|
public function __construct(array $channels = []) { foreach ($channels as $c) $this->saveChannel($c); }
|
|
public function channels(?string $s): array {
|
|
$r = array_values(array_filter($this->chan, fn($c) =>
|
|
$c['enabled'] && ($s === null || $c['site'] === null || $c['site'] === $s)));
|
|
usort($r, fn($a, $b) => [$a['step'], $a['channel_id']] <=> [$b['step'], $b['channel_id']]);
|
|
return $r;
|
|
}
|
|
public function allChannels(?string $s): array {
|
|
return array_values(array_filter($this->chan, fn($c) => $s === null || $c['site'] === $s));
|
|
}
|
|
public function saveChannel(array $row): int {
|
|
$id = $row['channel_id'] ?? ++$this->seq;
|
|
$this->chan[$id] = $row + ['channel_id' => $id, 'site' => null, 'enabled' => 1, 'step' => 0,
|
|
'escalate_after_s' => 0, 'min_severity' => 'high', 'config_json' => '{}'];
|
|
return $id;
|
|
}
|
|
public function deleteChannel(int $id, ?string $s): bool {
|
|
if (!isset($this->chan[$id])) return false;
|
|
if ($s !== null && $this->chan[$id]['site'] !== $s) return false;
|
|
unset($this->chan[$id]); return true;
|
|
}
|
|
private function key(int $e, int $c): string { return $e . ':' . $c; }
|
|
public function claim(int $e, int $c, int $now): bool {
|
|
if (isset($this->log[$this->key($e, $c)])) return false;
|
|
$this->log[$this->key($e, $c)] = ['event_id' => $e, 'channel_id' => $c, 'status' => 'pending',
|
|
'attempts' => 0, 'last_error' => null, 'queued_at' => $now, 'sent_at' => null];
|
|
return true;
|
|
}
|
|
public function markSent(int $e, int $c, int $now): void {
|
|
$k = $this->key($e, $c);
|
|
if (isset($this->log[$k])) { $this->log[$k]['status'] = 'sent'; $this->log[$k]['sent_at'] = $now; $this->log[$k]['attempts']++; }
|
|
}
|
|
public function markFailed(int $e, int $c, string $err, int $now): void {
|
|
$k = $this->key($e, $c);
|
|
if (isset($this->log[$k])) { $this->log[$k]['status'] = 'failed'; $this->log[$k]['last_error'] = $err; $this->log[$k]['attempts']++; }
|
|
}
|
|
public function markSuppressed(int $e, int $c, int $now): void {
|
|
$k = $this->key($e, $c);
|
|
if (isset($this->log[$k])) { $this->log[$k]['status'] = 'suppressed'; $this->log[$k]['sent_at'] = $now; }
|
|
}
|
|
public function forEvent(int $e): array {
|
|
return array_values(array_filter($this->log, fn($r) => $r['event_id'] === $e));
|
|
}
|
|
public function retryable(int $max, int $limit): array {
|
|
return array_slice(array_values(array_filter($this->log,
|
|
fn($r) => $r['status'] === 'failed' && $r['attempts'] < $max)), 0, $limit);
|
|
}
|
|
}
|
|
final class InMemoryHandoverRepository implements HandoverRepository {
|
|
public array $rows = []; private int $seq = 0;
|
|
public function recent(?string $s, int $limit): array {
|
|
$r = array_values(array_filter($this->rows, fn($x) => $s === null || $x['site'] === $s));
|
|
usort($r, fn($a, $b) => $b['created_at'] <=> $a['created_at']);
|
|
return array_slice($r, 0, $limit);
|
|
}
|
|
public function latest(?string $s): ?array { return $this->recent($s, 1)[0] ?? null; }
|
|
public function create(array $row): int {
|
|
$id = ++$this->seq; $this->rows[$id] = $row + ['handover_id' => $id]; return $id;
|
|
}
|
|
}
|
|
final class InMemoryRiskControlRepository implements RiskControlRepository {
|
|
public array $rows = []; private int $seq = 0;
|
|
public function listAll(?string $s): array {
|
|
return array_values(array_filter($this->rows, fn($r) => $s === null || $r['site'] === $s));
|
|
}
|
|
public function upsert(array $row): void {
|
|
foreach ($this->rows as $id => $r) {
|
|
if ($r['site'] === ($row['site'] ?? null) && $r['event_type'] === $row['event_type']) {
|
|
$this->rows[$id] = $row + ['control_id' => $id]; return;
|
|
}
|
|
}
|
|
$id = ++$this->seq; $this->rows[$id] = $row + ['control_id' => $id];
|
|
}
|
|
public function delete(int $id, ?string $s): bool {
|
|
if (!isset($this->rows[$id])) return false;
|
|
if ($s !== null && $this->rows[$id]['site'] !== $s) return false;
|
|
unset($this->rows[$id]); return true;
|
|
}
|
|
}
|
|
final class InMemoryDeviceMetricRepository implements DeviceMetricRepository {
|
|
public array $rows = [];
|
|
public function append(string $d, array $m, int $now): void {
|
|
$this->rows[] = ['device_id' => $d, 'ts' => $now] + $m;
|
|
}
|
|
public function series(string $d, int $since, int $limit): array {
|
|
$r = array_values(array_filter($this->rows, fn($x) => $x['device_id'] === $d && $x['ts'] >= $since));
|
|
usort($r, fn($a, $b) => $a['ts'] <=> $b['ts']);
|
|
return array_slice($r, 0, $limit);
|
|
}
|
|
public function prune(int $before): int {
|
|
$n = count($this->rows);
|
|
$this->rows = array_values(array_filter($this->rows, fn($x) => $x['ts'] >= $before));
|
|
return $n - count($this->rows);
|
|
}
|
|
}
|