move_detect/server/tests/Support/InMemoryRepositories.php
유창욱 9e4225a338 feat(heatmap): near-miss events + spatial ingestion + camera risk-heatmap overlay
Heinrich's-law play: the signals we already compute but used to throw away
become a spatial risk map of the workplace, drawn over the camera's own frame.

Edge:
- near_fall (INFO): a track that reached FALLING (sustained prone) but recovered
  before the FALLEN confirm. Treated as a full event per product decision -
  same ingest, snapshots, dedup, ack flow as incidents. Fix en route: prone_s
  used a truthiness check that turned prone_since=0.0 into "no timer".
- Every per-track event (fall/no_motion/near_fall/immobility/zone hits) now
  carries the foot point in the zones' normalized 0..1 space (reusing the zone
  detector's own coordinate math); ghost's pixel-space loss point is normalized
  at emit. to_payload omits the key when absent, so an old server ignores it.

Server:
- move_events.spatial_x/spatial_y (nullable DOUBLE) + validator: optional
  [x, y] finite-number pair; range deliberately NOT enforced (an off-by-a-hair
  foot must never reject a FALL alert - renderers clamp).
- MIGRATION FIX: chk_events_type would have REJECTED the previous commit's
  lone_worker/overcapacity/overstay inserts on MySQL 8.0.16+ - the constraint
  is rebuilt with all 13 types (incl. near_fall).
- GET /api/heatmap/{camera}?days=N (1..90, default 30, 5000-point cap):
  spatial points with the same fail-closed site scoping as the event list.

UI (zone editor): "위험 히트맵" toggle + day window. Additive radial blots in
an offscreen layer under the zone polygons; severity weighs the alpha so a
cluster of near-misses reads lighter than one confirmed fall at the same spot.
Events console/detail label near_fall in Korean.

Verified: pytest 222 pass / PHPUnit 130 pass + Chrome real-render (blue
near-miss cluster + red incident hotspot inside the restricted zone, amber
cluster in the warning zone, zones drawn on top; no console errors).
2026-08-06 20:19:09 +09:00

142 lines
8.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests\Support;
use App\Repository\{DeviceRepository, NonceRepository, RateLimiterRepository,
EventRepository, SnapshotRepository, UserRepository, ZoneRepository,
ThresholdRepository, AuditRepository};
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 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; return true; }
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 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 InMemoryThresholdRepository implements ThresholdRepository {
public function __construct(private array $data = []) {}
public function forDevice(string $d): array { return $this->data[$d] ?? []; }
}
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'); }
}