e00ad69 로 늘어난 표면(라우트 17, 표 6종+컬럼 4, CLI 도구 5, 엣지 모듈 4, 통보 발송 경로,
감사 해시체인)을 8개 관점으로 재감사. 후보는 반증 시도 후 확정된 것만 채택.
CRITICAL
- A1 신규 감지 유형이 EventValidator 허용 목록에 없어 서버가 전부 400 으로 거부했다.
edge/queue.py 는 20회 재시도 후 그 행을 버리므로, 카메라 무결성 감지는 구현·테스트·배포가
끝난 상태로 end-to-end 무력화되어 있었다. DB CHECK 와 프런트 라벨은 갱신했는데 가운데
검증 계층만 빠진 형태 — 파이썬 테스트도 PHP 테스트도 각자 절반만 보기 때문에 둘 다 통과한다.
허용 목록을 고치고, 언어 경계를 넘는 회귀 테스트를 신설했다
(tests/test_event_type_parity.py: edge/events.py ↔ EventValidator ↔ schema.sql ↔
프런트 라벨 5종 ↔ 유형 필터). 실제로 A4 를 이 테스트가 잡았다.
- A2 seed_demo --purge 가 위험성평가를 reviewed_by='안전관리자' AND site='factory-a' 로
지웠다. 전자는 이 제품의 기본 관리자 계정명이고 후자는 흔한 현장명이다 — 운영 DB 에서
한 번 돌리면 실제 위험성평가가 복구 불가능하게 사라진다. 데모 행은 이제 전용 표식으로만
식별하고, 표식 없는 행은 어떤 경우에도 건드리지 않는다.
- A3 backup.php 의 웹 공개 경로 차단이 '/www/' 부분문자열이라 docroot 자체
(/home/acct/www)는 뒤에 슬래시가 없어 통과했다 — 가장 흔한 오사용이 정확히 그 경우다.
전 현장 사고 기록 + 작업자 이미지가 웹에서 내려받히고, 파일명은 하루 범위만 알면 추측된다.
경로를 세그먼트로 쪼개 웹 루트 이름(www/public_html/htdocs/html/web/public)을 거부한다.
HIGH
- A4 신규 유형이 app.js/detail.js/report.js 라벨 맵과 유형 필터에 없어 화면에 원시 코드가
그대로 떴고, 조사자가 그 유형만 걸러 볼 방법도 없었다.
- A5 서버 타임존 미설정. 대시보드는 브라우저 시각을 쓰지만 통보 메일은 PHP 가 만들고,
공유호스팅은 date.timezone 이 흔히 UTC 다 — 콘솔이 13:01 로 보여준 넘어짐을 메일이
04:01 로 적는다. 응급 대응에서 읽는 유일한 문장이 9시간 어긋나는 문제.
Config::timezone() 신설(기본 Asia/Seoul), 잘못된 값이면 폴백하되 발송은 막지 않는다.
- A6 ALTER TABLE … DROP CHECK 는 MySQL 8.0.16+ 전용이다. 카페24에 흔한 MariaDB 는
DROP CONSTRAINT 를 쓰므로 마이그레이션이 통째로 실패한다. 엔진별 분기를 명시하고,
이 CHECK 가 2차 방어선(1차는 EventValidator)임을 적어 실패해도 판단할 수 있게 했다.
MEDIUM
- A7 디스패처가 매분 창 전체를 재-claim 해 비용이 '새 이벤트'가 아니라 '창 길이'에 비례했다.
크론이 불안정해 창을 넓힌 현장일수록 나빠지는 방향이다. 원장을 한 번에 읽어 사전 필터하고,
claim() 은 경합 시 최종 권위로 남긴다.
- A8 move_alert_log 에 보존 정책이 없어 유일하게 무한 증가하는 표였다. 해소된 전달만
정리하고 failed 는 남긴다 — "아무에게도 닿지 않았다"가 조사에서 필요한 발견이다.
- A9 전역 관리자가 현장 채널을 수정하면 site 가 NULL 로 덮여 그 채널이 모든 현장에
발화했다. 폼에는 그런 안내가 없다. 수정 시 기존 site 보존.
- A10 일괄 확인이 대상마다 fetch 를 띄웠다. HTTP/2 는 직렬화하지 않으므로 수백 건이
공유호스팅에 한꺼번에 떨어진다. 동시 4개 제한 + 진행 중 목록 갱신.
LOW
- A11 패키지 테스트가 tools/ 배치를 검사하지 않았다. 이 도구들은 메일을 보내고 DB 전체를
읽으므로 www/ 아래로 새면 인증 없는 표면이 된다. CLI 가드 require·private 배치·웹 루트
PHP 화이트리스트 3종 검사 추가.
- A12 판정 배너와 CLAUDE.md 의 "43/43" 표기 갱신.
수정하지 않고 판단만 기록한 3건(웹훅 SSRF·서버가 지정하는 GPIO 핀·/setup 첫 카메라 한정)은
리포트 "확인만 하고 수정하지 않은 항목" 절 참조.
부수 효과: 기존 config 템플릿 가드가 timezone 키 누락을 잡아 두 템플릿도 함께 갱신됐다.
검증: PHPUnit 224 (skip 0, +3) · pytest 통과(skip 3 = 하드웨어·환경) · 산출물 패리티 통과.
backup 경로 가드는 docroot 자체/하위/비공개 3케이스로 회귀 확인. 감사로그 변조 탐지는
실제 UPDATE 후 verify_audit_chain.php exit 1 로 확인.
cafe24 번들 + Pi 오프라인 번들 재생성.
477 lines
27 KiB
PHP
477 lines
27 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;
|
|
/** Observation hook: how many times claim() was actually attempted. The dispatcher is
|
|
* supposed to pre-filter already-delivered pairs, and the only way to see that from the
|
|
* outside is to count the attempts. */
|
|
public int $claimCalls = 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 {
|
|
$this->claimCalls++;
|
|
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);
|
|
}
|
|
public function claimedSince(int $since): array {
|
|
$out = [];
|
|
foreach ($this->log as $r) {
|
|
if ($r['queued_at'] >= $since) $out[$r['event_id'] . ':' . $r['channel_id']] = true;
|
|
}
|
|
return $out;
|
|
}
|
|
public function pruneResolved(int $before): int {
|
|
$n = count($this->log);
|
|
$this->log = array_filter($this->log, fn($r) =>
|
|
!($r['queued_at'] < $before && in_array($r['status'], ['sent', 'suppressed'], true)));
|
|
return $n - count($this->log);
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
}
|