Complete remaining Heimdall features and acceptance
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 19m19s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m13s
Heimdall Gitea / Build and scan agent image (push) Successful in 14m44s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m48s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m9s
Heimdall Gitea / CI policy (push) Successful in 10s

Merge pull request #138

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #138.
This commit is contained in:
arnaud.dartois authored and Arnaud Dartois committed 2026-11-06 11:14:49 +01:00
1 parent 6e61d38ca8
commit 636154572b
217 files changed
+15247 -294

No files matched your search

+3
View File
@@ -23,6 +23,9 @@ JWT__REFRESHKEY=ChangeMeToAtLeast32BytesRefreshKeyInProd!
JWT__ISSUER=heimdall
JWT__AUDIENCE=heimdall-api
# Optional manual license-plate crop OCR (disabled by default).
PLATE_OCR_ENABLED=false
# ASP.NET
ASPNETCORE_ENVIRONMENT=Development
ASPNETCORE_URLS=http://+:8080
+40 -1
View File
@@ -75,7 +75,7 @@ jobs:
policy:
name: CI policy
if: always()
needs: [changes, verify, server_image, agent_image, dockerhub_latest, publish]
needs: [changes, verify, server_image, agent_image, agent_gpu_image, dockerhub_latest, publish]
runs-on: [ubuntu-latest, build-agent]
steps:
- name: Require all applicable validation jobs to pass
@@ -85,6 +85,7 @@ jobs:
VERIFY_RESULT: ${{ needs.verify.result }}
SERVER_IMAGE_RESULT: ${{ needs.server_image.result }}
AGENT_IMAGE_RESULT: ${{ needs.agent_image.result }}
AGENT_GPU_IMAGE_RESULT: ${{ needs.agent_gpu_image.result }}
DOCKERHUB_RESULT: ${{ needs.dockerhub_latest.result }}
RELEASE_RESULT: ${{ needs.publish.result }}
EVENT_NAME: ${{ gitea.event_name }}
@@ -103,10 +104,12 @@ jobs:
pull_request:*)
test "$SERVER_IMAGE_RESULT" = success
test "$AGENT_IMAGE_RESULT" = success
test "$AGENT_GPU_IMAGE_RESULT" = success
;;
push:refs/heads/main)
test "$SERVER_IMAGE_RESULT" = success
test "$AGENT_IMAGE_RESULT" = success
test "$AGENT_GPU_IMAGE_RESULT" = success
test "$DOCKERHUB_RESULT" = success
;;
push:refs/tags/v*)
@@ -286,6 +289,42 @@ jobs:
if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then
bash scripts/ci/cleanup-docker.sh after
fi
agent_gpu_image:
name: Build and scan NVIDIA Agent image
if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main')
needs: [changes, verify]
runs-on: [ubuntu-latest, build-agent]
container:
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
steps:
- name: Prepare action runtime before checkout
run: |
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils
test "$(uname -m)" = x86_64
curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz
echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check
tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1
ln -sf /usr/local/bin/node /usr/bin/node
rm /tmp/node.tar.xz
- name: Checkout
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- name: Runner prerequisites
run: bash scripts/ci/bootstrap.sh
- name: Reclaim old build storage
run: bash scripts/ci/cleanup-docker.sh before
- name: Build NVIDIA Agent image
run: bash scripts/ci/images.sh agent-gpu
- name: Scan NVIDIA Agent image
run: bash scripts/ci/security.sh agent-gpu
- name: Reclaim build storage after job
if: always()
run: |
if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then
bash scripts/ci/cleanup-docker.sh after
fi
dockerhub_latest:
name: Publish Docker Hub latest tags
if: needs.changes.outputs.run_validation == 'true' && gitea.ref == 'refs/heads/main'
+9 -2
View File
@@ -16,8 +16,15 @@ jobs:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_ONBOARDING: 'false'
steps:
- name: Checkout Renovate preflight
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 1
persist-credentials: false
- name: Check Renovate credentials against Gitea
run: |
node --test scripts/ci/renovate-preflight.test.mjs
node scripts/ci/renovate-preflight.mjs
- name: Create dependency pull requests
run: |
test -n "$RENOVATE_TOKEN"
test -n "$RENOVATE_ENDPOINT"
renovate arnaud.dartois/Heimdall
+1 -1
View File
@@ -1,7 +1,7 @@
# Heimdall contributor rules
- For every feature, fix, operational change, or meaningful documentation change, create or update a focused skill under `skills/` in the same PR. The skill must capture the project-specific implementation and acceptance workflow, not restate generic guidance.
- Every behavior or deployment change must pass an acceptance recipe in a disposable Docker Compose project built from the changed source. Use isolated generated credentials, ports, volumes, and project names; never reuse production configuration/data. Tear down only that project and confirm its containers/volumes are gone. Do not skip this recipe silently when Docker is unavailable.
- Every behavior or deployment change must pass an acceptance recipe in a disposable Docker Compose project built from the changed source. Use isolated generated credentials, ports, volumes, project names, and unique tags for locally built acceptance images; never reuse production configuration/data. Tear down only that project and confirm its containers/volumes/networks are gone, then remove and verify absence of only the exact image tags built by that recipe. Keep shared upstream/base images. Never use broad image pruning. Do not skip this recipe silently when Docker is unavailable.
- Read `todo.md` before changing code. Update its status and acceptance notes in the same PR as each correction or feature. Remove a completed item only after the behavior is verified; keep a short completion entry for traceability.
- Keep `Domain` independent of infrastructure. Put use cases and interfaces in `Application`, adapters and EF Core persistence in `Infrastructure`, HTTP/UI composition in `Web`, and camera/runtime behavior in `Agent`.
- Target the SDK pinned by `global.json` and .NET 10 or newer. Use nullable reference types, cancellation tokens for I/O, and explicit options validation. Do not weaken locked restore or suppress a new warning without a reason.
+2 -2
View File
@@ -14,10 +14,10 @@ RUN apt-get update -qq \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \
&& apt_version="$(dpkg-query -W -f='${Version}' apt)" \
&& dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends wget tzdata \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends wget tzdata tesseract-ocr tesseract-ocr-eng \
&& rm -rf /var/lib/apt/lists/*
ENV ASPNETCORE_URLS=http://+:8080
COPY --from=build /out/ ./
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s CMD wget -q --spider http://localhost:8080/healthz || exit 1
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s CMD wget -q -O /dev/null http://localhost:8080/healthz || exit 1
ENTRYPOINT ["dotnet", "Heimdall.Web.dll"]
+1 -1
View File
@@ -23,6 +23,6 @@ ENV ASPNETCORE_URLS=http://127.0.0.1:8080
COPY --from=build /out/ ./
COPY models/yolov8n.onnx ./models/yolov8n.onnx
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q --spider http://127.0.0.1:8080/healthz || exit 1
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1
USER 1654:1654
ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"]
+36
View File
@@ -0,0 +1,36 @@
# Optional NVIDIA Agent image. ONNX Runtime 1.22 GPU uses CUDA 12.8 and cuDNN 9.
# NVIDIA amd64 runtime image digest is pinned; it includes CUDA 12.8.1/cuDNN 9.8.0.87.
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
WORKDIR /src
ARG VERSION=0.0.0-local
COPY global.json Directory.Build.props Directory.Build.targets ./
COPY src/ ./src/
RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRuntime=GPU --locked-mode
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out \
-p:HeimdallOnnxRuntime=GPU -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee AS dotnet-runtime
FROM nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9 AS runtime
WORKDIR /app
ENV DOTNET_ROOT=/usr/share/dotnet \
PATH=/usr/share/dotnet:$PATH \
LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu \
ASPNETCORE_URLS=http://127.0.0.1:8080 \
Agent__InferenceExecutionProvider=CUDA
RUN apt-get update -qq \
&& DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \
&& apt_version="$(dpkg-query -W -f='${Version}' apt)" \
&& dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
ca-certificates ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \
&& rm -rf /var/lib/apt/lists/* \
&& install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall
COPY --from=dotnet-runtime /usr/share/dotnet/ /usr/share/dotnet/
COPY --from=build /out/ ./
COPY models/yolov8n.onnx ./models/yolov8n.onnx
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1
USER 1654:1654
ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"]
+2 -1
View File
@@ -22,7 +22,8 @@ docker compose --env-file .env -f docker-compose.backup.yml up -d
Le Central et PostgreSQL doivent d'abord être démarrés. Le service `backup`
rejoint le réseau partagé et tourne dans un conteneur PostgreSQL 17-alpine
avec crontab interne. Les dumps sont stockés dans `backup_data`; l'upload
avec crontab interne, AWS CLI et GNU coreutils (pour le calcul portable des seuils
de rétention Alpine). Les dumps sont stockés dans `backup_data`; l'upload
RustFS/S3 est facultatif.
Le service monte aussi le volume `heimdall_data` du Compose Central : les
objets stockés localement et les clés Data Protection sont archivés ensemble.
@@ -0,0 +1,25 @@
# Optional development overlay. The default dev Compose remains CPU-only.
services:
heimdall-agent:
platform: linux/amd64
profiles:
- gpu-nvidia
image: heimdall-agent:gpu-local
build:
context: ..
dockerfile: docker/Dockerfile.agent.gpu
environment:
Agent__InferenceExecutionProvider: CUDA
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
agent-state-init:
image: heimdall-agent:gpu-local
build:
context: ..
dockerfile: docker/Dockerfile.agent.gpu
+2 -3
View File
@@ -30,10 +30,9 @@ services:
entrypoint: ["/bin/sh", "-c"]
command:
- |
set -e
export POSTGRES_PASSWORD="$$(cat /run/secrets/db_password)"
apk add --no-cache curl bash >/dev/null 2>&1 || true
curl -fsSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc || true
chmod +x /usr/local/bin/mc 2>/dev/null || true
apk add --no-cache aws-cli bash coreutils
echo '0 2 * * * bash /scripts/backup.sh >> /var/log/backup.log 2>&1' > /tmp/crontab.txt
echo '15 2 * * * bash /scripts/backup-protected-data.sh >> /var/log/backup-protected-data.log 2>&1' >> /tmp/crontab.txt
echo '0 3 * * 0 bash /scripts/backup-rustfs.sh >> /var/log/backup-rustfs.log 2>&1' >> /tmp/crontab.txt
+2 -2
View File
@@ -1,5 +1,5 @@
# Optional NVIDIA device passthrough for Agent GPU inventory.
# The current Agent image still runs ONNX inference on CPU.
# Optional NVIDIA device passthrough for Agent GPU inventory on the published
# CPU image. Use docker-compose.agent.dev.gpu-nvidia.yml for the CUDA image.
services:
heimdall-agent:
profiles:
+9 -1
View File
@@ -47,6 +47,14 @@ services:
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production}
ASPNETCORE_URLS: http://+:8080
Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*}
LiveMedia__WhepUrl: ${HEIMDALL_WHEP_URL:-}
LiveMedia__PublishRtspUrl: ${HEIMDALL_PUBLISH_RTSPS_URL:-}
LiveMedia__AllowInsecureRtsp: ${HEIMDALL_ALLOW_INSECURE_RTSP:-false}
LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-}
LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-}
LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-}
Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776}
PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false}
Sentry__Dsn: ${SENTRY_DSN:-}
Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0.05}
Sentry__Release: ${SENTRY_RELEASE:-}
@@ -91,5 +99,5 @@ secrets:
networks:
heimdall-net:
name: heimdall-net
name: ${HEIMDALL_NETWORK_NAME:-heimdall-net}
driver: bridge
@@ -0,0 +1,62 @@
# Loopback-only media services for disposable acceptance, never production.
services:
mediamtx:
image: bluenviron/mediamtx:1.21.3
restart: unless-stopped
environment:
HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin}
MTX_AUTHMETHOD: http
MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central callback URL}
MTX_WEBRTCALLOWORIGINS: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin}
# The browser receives this ICE port in SDP; keep the published host port
# identical so Docker NAT does not advertise an unreachable container port.
MTX_WEBRTCLOCALUDPADDRESS: :${HEIMDALL_TEST_ICE_PORT:-18189}
ports:
- "127.0.0.1:${HEIMDALL_TEST_PUBLISH_PORT:-18555}:8554/tcp"
- "127.0.0.1:${HEIMDALL_TEST_WHEP_PORT:-18889}:8889/tcp"
- "127.0.0.1:${HEIMDALL_TEST_ICE_PORT:-18189}:${HEIMDALL_TEST_ICE_PORT:-18189}/udp"
volumes:
- ./mediamtx.local-test.yml:/mediamtx.yml:ro
networks:
- heimdall-net
heimdall-agent:
image: heimdall-agent:webrtc-test
build:
context: ..
dockerfile: docker/Dockerfile.agent
restart: unless-stopped
network_mode: host
user: "1654:1654"
environment:
ASPNETCORE_URLS: http://127.0.0.1:${HEIMDALL_TEST_AGENT_PORT:-18081}
Agent__CentralUrl: http://127.0.0.1:${WEB_PORT:-5000}
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:-}
Agent__AgentName: webrtc-synthetic-agent
Agent__StateDirectory: /var/lib/heimdall
volumes:
- heimdall_agent_state:/var/lib/heimdall
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:${HEIMDALL_TEST_AGENT_PORT:-18081}/healthz"]
interval: 10s
timeout: 3s
retries: 3
start_period: 20s
depends_on:
agent-state-init:
condition: service_completed_successfully
agent-state-init:
image: heimdall-agent:webrtc-test
build:
context: ..
dockerfile: docker/Dockerfile.agent
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
- heimdall_agent_state:/state
restart: "no"
volumes:
heimdall_agent_state:
+22
View File
@@ -0,0 +1,22 @@
# Test-only synthetic camera source. Exposes one local RTSP port so an Agent
# can be configured through Central to pull this generated H.264 stream.
services:
synthetic-camera:
image: bluenviron/mediamtx:1.21.3
restart: unless-stopped
ports:
- "127.0.0.1:${HEIMDALL_SYNTHETIC_RTSP_PORT:-18554}:8554/tcp"
volumes:
- ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro
networks:
- heimdall-net
synthetic-camera-publisher:
image: jrottenberg/ffmpeg:7.1-alpine
restart: unless-stopped
entrypoint: ["/bin/sh", "-c"]
command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -profile:v baseline -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 2; done"]
depends_on:
- synthetic-camera
networks:
- heimdall-net
+27
View File
@@ -0,0 +1,27 @@
# Optional MediaMTX for live camera video. Start after the core stack has
# created heimdall-net. Public DNS and certificates are deployment supplied.
services:
mediamtx:
image: bluenviron/mediamtx:1.21.3
restart: unless-stopped
environment:
HEIMDALL_WEBRTC_PUBLIC_HOST: ${HEIMDALL_WEBRTC_PUBLIC_HOST:?Set the public WebRTC hostname}
HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin}
MTX_AUTHMETHOD: http
MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central MediaMTX callback URL}
MTX_WEBRTCALLOWORIGINS: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin}
MTX_WEBRTCADDITIONALHOSTS: ${HEIMDALL_WEBRTC_PUBLIC_HOST:?Set the public WebRTC hostname}
ports:
- "${HEIMDALL_RTSPS_PORT:-8322}:8322/tcp"
- "${HEIMDALL_WHEP_PORT:-8889}:8889/tcp"
- "${HEIMDALL_WEBRTC_UDP_PORT:-8189}:8189/udp"
volumes:
- ./mediamtx.yml:/mediamtx.yml:ro
- ${HEIMDALL_LIVE_MEDIA_CERT_DIR:?Set directory containing server.crt and server.key}:/certs:ro
networks:
- heimdall-net
networks:
heimdall-net:
external: true
name: ${HEIMDALL_NETWORK_NAME:-heimdall-net}
+11 -2
View File
@@ -36,6 +36,15 @@ services:
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
ASPNETCORE_URLS: http://+:8080
Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*}
LiveMedia__WhepUrl: ${HEIMDALL_WHEP_URL:-}
LiveMedia__PublishRtspUrl: ${HEIMDALL_PUBLISH_RTSPS_URL:-}
LiveMedia__AllowInsecureRtsp: ${HEIMDALL_ALLOW_INSECURE_RTSP:-false}
LiveMedia__AllowInsecureHttp: ${HEIMDALL_ALLOW_INSECURE_HTTP:-false}
LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-}
LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-}
LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-}
Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776}
PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false}
ports:
- "${WEB_PORT:-5000}:8080"
volumes:
@@ -46,7 +55,7 @@ services:
postgresql:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://localhost:8080/healthz"]
interval: 30s
timeout: 10s
retries: 3
@@ -61,5 +70,5 @@ volumes:
networks:
heimdall-net:
name: heimdall-net
name: ${HEIMDALL_NETWORK_NAME:-heimdall-net}
driver: bridge
+17
View File
@@ -0,0 +1,17 @@
# Loopback-only insecure listeners for disposable workstation acceptance only.
logLevel: warn
rtsp: true
rtspTransports: [tcp]
rtspEncryption: "no"
rtspAddress: :8554
webrtc: true
webrtcAddress: :8889
webrtcEncryption: false
webrtcAllowOrigins: ['${HEIMDALL_WEBRTC_ALLOWED_ORIGIN}']
webrtcLocalUDPAddress: :8189
webrtcAdditionalHosts: ['127.0.0.1']
pathDefaults:
source: publisher
record: false
paths:
all_others:
+15
View File
@@ -0,0 +1,15 @@
logLevel: warn
rtsp: true
rtspTransports: [tcp]
rtspEncryption: "no"
rtspAddress: :8554
authMethod: internal
authInternalUsers:
- user: any
pass:
ips: []
permissions:
- action: publish
- action: read
paths:
all_others:
+23
View File
@@ -0,0 +1,23 @@
logLevel: warn
rtsp: true
rtspTransports: [tcp]
rtspEncryption: strict
rtspsAddress: :8322
rtspServerCert: /certs/server.crt
rtspServerKey: /certs/server.key
webrtc: true
webrtcAddress: :8889
webrtcEncryption: true
webrtcServerCert: /certs/server.crt
webrtcServerKey: /certs/server.key
webrtcAllowOrigins: []
webrtcLocalUDPAddress: :8189
webrtcAdditionalHosts: []
pathDefaults:
source: publisher
record: false
paths:
all_others:
+8 -3
View File
@@ -35,9 +35,14 @@ find "$ARCHIVE_DIR" -type f -name 'heimdall-data-*.tar.gz' -mtime "+$RETENTION_D
if [[ "$SKIP_S3_UPLOAD" == "1" ]]; then
log "S3 upload disabled by BACKUP_SKIP_S3_UPLOAD"
elif [[ -n "$S3_ENDPOINT" && -n "$S3_ACCESS_KEY" && -n "$S3_SECRET_KEY" ]]; then
command -v mc >/dev/null 2>&1 || die "mc is required to upload protected data backups"
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null
mc cp "$ARCHIVE" "heimdall-backup/${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")"
if command -v mc >/dev/null 2>&1; then
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null
mc cp "$ARCHIVE" "heimdall-backup/${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")"
elif command -v aws >/dev/null 2>&1; then
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$ARCHIVE" "s3://${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")"
else
die "Neither mc nor aws CLI is available to upload protected data backups"
fi
log "Uploaded protected data archive to the configured object store"
else
log "S3 credentials are not configured; the archive remains in the local backup volume"
+10 -2
View File
@@ -76,7 +76,7 @@ else
2>&1 | tail -10
else
# AWS CLI: sync with exclusion
aws --endpoint-url "$S3_ENDPOINT" s3 sync \
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 sync \
"s3://${S3_BUCKET}" \
"s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}" \
--exclude "backup/*" \
@@ -102,6 +102,14 @@ if [[ -n "$CUTOFF_WEEK" ]]; then
mc rm --recursive --force "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" 2>/dev/null || true
fi
done
else
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 ls "s3://${S3_BUCKET}/${BACKUP_PREFIX}/" 2>/dev/null | awk '$1 == "PRE" {print $2}' | while read -r week; do
week="${week%/}"
if [[ "$week" < "$CUTOFF_WEEK" ]]; then
log " Deleting: ${BACKUP_PREFIX}/${week}/"
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 rm --recursive "s3://${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" >/dev/null
fi
done
fi
fi
fi
@@ -131,7 +139,7 @@ Total: ${TOTAL_SIZE} bytes
if [[ "$CLIENT" == "mc" ]]; then
echo "$MANIFEST" | mc pipe "heimdall-backup/${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null
else
echo "$MANIFEST" | aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null
echo "$MANIFEST" | AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null
fi
log "Manifest written: ${MANIFEST_KEY}"
fi
+9 -2
View File
@@ -109,8 +109,8 @@ if [[ -n "$S3_ENDPOINT" ]]; then
mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3
mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3
else
aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3
aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3
fi
log "Upload complete"
fi
@@ -141,6 +141,13 @@ if [[ -n "$S3_ENDPOINT" && "$IS_DRY_RUN" != "1" ]]; then
mc rm "heimdall-backup/${S3_BUCKET}/${key}" 2>/dev/null || true
fi
done
elif command -v aws >/dev/null 2>&1; then
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 ls "s3://${S3_BUCKET}/${S3_PREFIX}/" --recursive 2>/dev/null | awk '{print $4}' | while read -r key; do
if [[ "$key" =~ ([0-9]{4}-[0-9]{2}-[0-9]{2})/ ]] && [[ "${BASH_REMATCH[1]}" < "$CUTOFF_DATE" ]]; then
log " Deleting: $key"
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 rm "s3://${S3_BUCKET}/${key}" >/dev/null
fi
done
fi
fi
fi
+1 -1
View File
@@ -124,7 +124,7 @@ if [[ -n "$S3_KEY" ]]; then
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null
mc cp "heimdall-backup/${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3
else
aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3
fi
log "Downloaded: $(du -h "$FILE" | cut -f1)"
fi
+1
View File
@@ -92,6 +92,7 @@ docker network create "$NETWORK_NAME" >/dev/null
docker run -d \
--name "$CONTAINER_NAME" \
--network "$NETWORK_NAME" \
--tmpfs /var/lib/postgresql/data \
-e POSTGRES_DB="$TEST_DB" \
-e POSTGRES_USER="$TEST_USER" \
-e POSTGRES_PASSWORD_FILE=/tmp/test-db-password \
+2 -2
View File
@@ -16,7 +16,7 @@ La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B
Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’origine HTTPS de la forge attendue (par exemple `https://sources.tordais.cc`, sans chemin). La publication compare cette valeur à `BUILD_SERVER_URL`, fourni par Gitea, avant toute publication. Les images serveur et Agent sont publiées sur Docker Hub sous `eltruncho/heimdall` et `eltruncho/heimdall-agent`; configurer les secrets Actions `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN`. Central transmet à l’Agent le dépôt et le digest signés dans la release.
La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent et le dépôt ainsi que le digest immuable de l’image Docker. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé.
La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent, l’image CPU et son digest, ainsi que l’image NVIDIA CUDA optionnelle et son digest. Les fichiers `agent-image.json` et `agent-image-gpu.json` contiennent ces références et leur SHA-256 est listé dans `SHA256SUMS`. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé.
Les mises à jour automatiques natives sont désactivées par défaut dans les réglages globaux Agent; chaque site peut hériter de ce réglage ou le remplacer. L’Agent vérifie les releases toutes les 12 heures et attend que `publishedAt` ait au moins 24 heures avant d’appliquer une mise à jour automatique. Une demande manuelle d’administrateur peut déclencher la mise à jour immédiatement. Les installations Docker/Kubernetes ne font pas de polling d’image local : elles suivent le mécanisme de l’orchestrateur et le digest fourni par l’IHM.
@@ -35,7 +35,7 @@ L’installateur Linux est servi par Central avec son superviseur. Il installe l
Sous Windows, copiez la commande PowerShell générée dans l’IHM pour le site, en mode processus utilisateur ou service Windows. Elle télécharge le script depuis Central et applique `ExecutionPolicy Bypass` à la session PowerShell courante uniquement; elle ne change pas la stratégie persistante de la machine. L’installation comme service exige une session PowerShell élevée. Une stratégie imposée par une stratégie de groupe peut toujours interdire l’exécution.
Pour un Agent Docker, le Compose généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. Aucun fichier de clé n’est à créer manuellement. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé.
Pour un Agent Docker, le Compose généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
## Rotation
+112 -1
View File
@@ -90,13 +90,32 @@ JWT__ISSUER=heimdall
JWT__AUDIENCE=heimdall-api
ASPNETCORE_ENVIRONMENT=Production
WEB_PORT=5000
RECORDING_STORAGE_QUOTA_MAX_BYTES=1099511627776
Cors__AllowedOrigins=https://heimdall.example.org
EOF
unset db_password
# Replace the example origin above with the public origin of your Central.
# The recording quota defaults to 1 TiB (1099511627776 bytes).
docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d
```
Central images also include Tesseract OCR and its English language data. The
manual license-plate crop reader is opt-in and defaults to disabled. Core and
production Compose files, plus both server installer templates, map
`PLATE_OCR_ENABLED` to Central's `PlateOcr__Enabled` option. Installer-generated
`.env` files set it to `false`; set `PLATE_OCR_ENABLED=true` and recreate the
Central service to enable the feature. Existing installer upgrades preserve an
existing value and add `false` only when the key is absent.
When enabled, an authorized operator can upload a JPEG/PNG plate crop from the
camera detail page. Processing runs on Central; the temporary crop is removed
after processing, while the candidate text and history event are persisted.
The feature limits uploads to 512 KiB and images to four megapixels. It does
not detect plates in video or perform face recognition, and the OCR result is
not a verified identity. Review retention/privacy implications in
[`skills/vision-identity/SKILL.md`](../skills/vision-identity/SKILL.md) before
enabling it.
The development Compose builds Central from the local source and starts only
Central plus PostgreSQL:
@@ -104,6 +123,15 @@ Central plus PostgreSQL:
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d
```
For a disposable local installation, copy `.env.example` to an ignored
temporary env file, replace the sample database/JWT values with generated
values, and choose unused loopback ports. Use a unique Compose project name and
`HEIMDALL_NETWORK_NAME`; after checking `/healthz`, stop only that project with
`docker compose -p <project> ... down --volumes --remove-orphans`. Verify its
containers, volumes, and network are gone. Never use `.env.example` unchanged
for an exposed or production deployment. The disposable recipe is maintained
in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-acceptance/SKILL.md).
## Agent
Prefer the Compose shown in the Central UI's site installation panel. It uses
@@ -138,7 +166,7 @@ docker compose --env-file docker/.env -f docker/docker-compose.backup.yml up -d
Configure Ollama at `http://ollama:11434` in Central's AI settings when enabled.
Choose RustFS as the storage provider in Central and use `http://rustfs:9000` as
its endpoint. Configure the ntfy server URL in Central's notification settings.
TURN is not required until WebRTC is enabled.
Live view can connect directly when ICE succeeds. For clients behind restrictive NAT/firewalls, deploy and validate TURN, then configure its URLs and matching shared secret in Central; without a reachable relay, those clients may not connect.
Redis is provided as a standalone service but is not currently required by
Central. Backups are independent of the core startup and require the core
network and PostgreSQL service to be running.
@@ -146,3 +174,86 @@ network and PostgreSQL service to be running.
See [GPU Agent notes](gpu-runtime.md) and
[Agent update signing](agent-release-signing.md) for device access and
trusted-key setup.
## Optional live video with WebRTC
The live-view vertical uses the separately maintained MediaMTX image. It is not
started with the core stack. Configure Central with the public `HEIMDALL_WHEP_URL`
and `HEIMDALL_PUBLISH_RTSPS_URL` (including scheme, host and port only). Provide
`HEIMDALL_MEDIAMTX_AUTH_URL` to the MediaMTX container; when both services share
the default Docker network this can use the Central service name and internal
port. Configure `HEIMDALL_WEBRTC_PUBLIC_HOST`,
`HEIMDALL_WEBRTC_ALLOWED_ORIGIN`, and `HEIMDALL_LIVE_MEDIA_CERT_DIR` for the
public listener and its TLS certificate (`server.crt` and `server.key`). The
certificate must cover both public WHEP and RTSPS hostnames. Open the configured
RTSPS/WHEP TCP ports and WebRTC ICE UDP port in the firewall. Add STUN URLs under
`LiveMedia:IceServers`; for TURN REST credentials set
`LiveMedia:Turn:Urls` and `LiveMedia:Turn:SharedSecret`. Central returns
five-minute HMAC credentials to the browser; the shared secret is never sent.
When using `docker-compose.coturn.yml`, configure the Central secret from the same
protected secret source as `docker/secrets/coturn_secret`; protect the Central
`.env` with owner-only permissions.
Start the core project first so its external `heimdall-net` network exists, then
start MediaMTX with a separate project name:
```sh
docker compose --env-file docker/.env -f docker/docker-compose.webrtc.yml -p heimdall-live up -d
```
Stop only this optional project with `docker compose ... -p heimdall-live down`.
Live publishing requires an assigned Agent and an online, enabled camera. Agent
relays are video-only H.264 passthrough, limited to two simultaneous cameras per
Agent. Central reserves eight viewers per camera and two per user in its process;
use one Central instance until shared reservation storage is configured. A stream
with a browser-incompatible codec is not transcoded. The WHEP read session
expires after ten minutes; the browser deletes the WHEP resource on
stop/navigation. Physical camera and external TURN validation remain deployment
acceptance work.
### Disposable live-view acceptance
For an isolated local playback test, use the local-only override and synthetic
source Compose files. Generate a unique `.env` outside the repository with new
PostgreSQL/JWT secrets, loopback ports, `HEIMDALL_NETWORK_NAME`,
`HEIMDALL_WEBRTC_ALLOWED_ORIGIN`, and
`HEIMDALL_MEDIAMTX_AUTH_URL=http://heimdall:8080/api/live-media/auth`.
Configure `HEIMDALL_WHEP_URL=http://127.0.0.1:<whep-port>`,
`HEIMDALL_PUBLISH_RTSPS_URL=rtsp://127.0.0.1:<publish-port>`,
`HEIMDALL_ALLOW_INSECURE_HTTP=true`,
`HEIMDALL_ALLOW_INSECURE_RTSP=true`, and
`HEIMDALL_WEBRTC_ALLOWED_ORIGIN=http://localhost:<web-port>`. Set
`HEIMDALL_NETWORK_NAME` to a unique network name and select unused values for
`WEB_PORT`, `HEIMDALL_TEST_PUBLISH_PORT`, `HEIMDALL_TEST_WHEP_PORT`,
`HEIMDALL_TEST_ICE_PORT`, `HEIMDALL_SYNTHETIC_RTSP_PORT`, and
`HEIMDALL_TEST_AGENT_PORT`. Insecure protocols are allowed only because all media
ports bind to loopback in this recipe. Then start Central, the local MediaMTX,
and synthetic source from changed source, excluding the Agent until a site token
is available:
```sh
docker compose -p "$project" --env-file "$env_file" \
-f docker/docker-compose.yml \
-f docker/docker-compose.webrtc-local-test.yml \
-f docker/docker-compose.webrtc-test.yml \
up -d --build postgresql heimdall mediamtx synthetic-camera synthetic-camera-publisher
```
Complete first-admin setup, create a site, put its generated test site token in
the disposable `.env`, and start `heimdall-agent` from the same Compose files.
Create and assign an online camera with the synthetic source RTSP URL, then open
its detail page and start live video. Verify an ungranted user is denied, stop
and disable the camera, and check the Agent process and WHEP session are closed.
Use unique ports and the unique network value for each run. Tear down only this
project with `down --volumes --remove-orphans`, confirm its containers, named
volumes and network are gone, and delete its temporary environment/secret files.
This recipe is HTTP/RTSP loopback-only; production configuration remains RTSPS
and HTTPS with a trusted certificate.
A source-built disposable acceptance on 5 November 2026 decoded a 640×360 synthetic
frame through the actual `live-view.js` module in Chromium. WHEP resource deletion
returned 200, Central session release returned 204, and disabling the camera
reduced the Agent publisher count from one to zero. The project teardown left no
containers, volumes, or network. MediaMTX origins and public ICE host must be passed
through its `MTX_WEBRTCALLOWORIGINS` and `MTX_WEBRTCADDITIONALHOSTS` environment
variables; placeholders inside `mediamtx.yml` are not expanded.
+3 -3
View File
@@ -1,6 +1,6 @@
# CI Gitea et images Heimdall
La chaîne active est `.gitea/workflows/build.yml`. Chaque PR lance le job léger `CI policy`, qui détecte les fichiers concernés. Si seuls la documentation ou les fichiers hors périmètre changent, les builds, tests, images et scans sont ignorés ; sinon ils s'exécutent avant que la politique réussisse. Les PR qui touchent le code valident la compilation, les suites .NET concernées, les archives, les images CPU amd64 et les contrôles de sécurité. Le job `verify` compile, teste et contrôle les dépendances NuGet. Les jobs `server_image` et `agent_image` construisent et scannent leurs images séparément après `verify` ; ils peuvent tourner en parallèle sur deux runners autorisés. `CI policy` doit être configuré comme contrôle obligatoire de `main`. Les pushes sur `main` restent filtrés par chemins et les tags `v*` gardent leur parcours complet : ils exécutent toutes les suites et le job de release reconstruit les images de version.
La chaîne active est `.gitea/workflows/build.yml`. Chaque PR lance le job léger `CI policy`, qui détecte les fichiers concernés. Si seuls la documentation ou les fichiers hors périmètre changent, les builds, tests, images et scans sont ignorés ; sinon ils s'exécutent avant que la politique réussisse. Les PR qui touchent le code valident la compilation, les suites .NET concernées, les archives, les images CPU amd64 et le build/scan de l’image Agent CUDA optionnelle, sans exiger de matériel GPU. Le job `verify` compile, teste et contrôle les dépendances NuGet. Les jobs `server_image`, `agent_image` et `agent_gpu_image` construisent et scannent leurs images séparément après `verify` ; ils peuvent tourner en parallèle sur des runners autorisés. `CI policy` doit être configuré comme contrôle obligatoire de `main`. Les pushes sur `main` restent filtrés par chemins et les tags `v*` gardent leur parcours complet : ils exécutent toutes les suites et le job de release reconstruit les images de version.
## Sélection des runners
@@ -8,7 +8,7 @@ Les jobs exigent `runs-on: [ubuntu-latest, build-agent]`. Déclarer `build-agent
Chaque runner lit sa configuration au démarrage. Ne pas rediriger `sources.tordais.cc` vers `host-gateway` dans `container.options` : cela a empêché les checkouts. Le workflow ne publie pas de rapports comme artefacts distants : les fichiers `artifacts/` sont utilisés dans le job (par exemple pour le seuil de couverture), puis disparaissent avec celui-ci. Le run historique #442 a signalé `CreateArtifact: EHOSTUNREACH`; aucun job courant ne dépend du service artefacts pour réussir.
Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_ENDPOINT` et échoue immédiatement si elle est absente. Renseigner l’URL API de la forge sans coder son domaine dans le dépôt.
Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Avant de démarrer Renovate, il vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API.
`scripts/ci/cleanup-docker.sh` journalise l'espace et élimine avant/après les builds les anciennes images Heimdall, les volumes Trivy abandonnés, les couches de build inutilisées depuis plus de 30 minutes et les images pendantes. Il ne purge pas les volumes, réseaux ou images nommées des autres projets. Le run #194 sur `runner-odin` a récupéré 95,89 Go avant build et 7,703 Go après job ; les 1 965 tests, deux images et scans ont réussi.
@@ -25,7 +25,7 @@ Après validation de `verify` sur `main`, chaque job d'image publie son tag immu
Aucun tag Git n'est requis. Les PR ne reçoivent pas de secret de publication et ne poussent aucune image. Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets d'organisation `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN` doivent être disponibles ; le token doit autoriser l'écriture dans les deux dépôts Docker Hub. Les identifiants sont transmis par stdin à `docker login` et stockés seulement dans une configuration temporaire supprimée en sortie.
Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` conservent le job séparé de release, après validation de `verify`. Le job reconstruit les archives depuis le commit vérifié et prépare la publication signée. Il nécessite en plus `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64`. La release reste en brouillon jusqu'à promotion explicite.
Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` conservent le job séparé de release, après validation de `verify`. Le job reconstruit et scanne les trois images, puis publie les images CPU et CUDA de l’Agent et joint leurs manifestes au manifeste ECDSA signé. Il nécessite en plus `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64`. La release reste en brouillon jusqu'à promotion explicite.
## Renovate
+26 -33
View File
@@ -1,39 +1,32 @@
# GPU device access and inference status
The default Agent uses `CPUExecutionProvider`. The published Agent image only
contains the CPU ONNX Runtime package. GPU detection and inventory report host
hardware; they do not mean that frame inference is running on that hardware.
The default Agent image and install path use `CPUExecutionProvider` and do not
require NVIDIA. The optional amd64 CUDA image is built from
`docker/Dockerfile.agent.gpu` and published as `eltruncho/heimdall-agent-gpu`.
Its immutable image digest is stored in the signed `agent-image-gpu.json`
release asset. Central offers the NVIDIA install option when that signed
release metadata is present. Existing Agent Compose files remain CPU-only.
The production Agent Compose is generated in Central's UI. Save that file as
`docker-compose.yml` on the camera host. To expose hardware for inventory,
copy the matching optional overlay from this repository beside it, then run:
ONNX Runtime 1.22 GPU uses CUDA 12.8 and cuDNN 9. The optional image pins NVIDIA
`12.8.1-cudnn-runtime-ubuntu24.04` to amd64 manifest
`sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9` and
uses the separate locked GPU NuGet dependency graph. See the [ONNX Runtime CUDA
provider compatibility table](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html)
and [NVIDIA CUDA image tag](https://hub.docker.com/r/nvidia/cuda/tags?name=12.8.1-cudnn-runtime-ubuntu24.04).
```sh
# NVIDIA
docker compose \
-f docker-compose.yml \
-f docker-compose.gpu-nvidia.yml \
--profile gpu-nvidia-inventory up -d heimdall-agent
The installer sets `Agent__InferenceExecutionProvider=CUDA` and requests all
NVIDIA devices for that variant. CUDA initialization failure logs a warning
and falls back to CPU. A physical GPU, compatible host driver and NVIDIA
Container Toolkit are required; see the [NVIDIA Container Toolkit install guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html).
# AMD ROCm devices
docker compose \
-f docker-compose.yml \
-f docker-compose.gpu-amd.yml \
--profile gpu-amd-inventory up -d heimdall-agent
The `docker-compose.gpu-{nvidia,amd,intel}.yml` files remain inventory-only
overlays. For local development, the CPU default is
`docker/docker-compose.agent.dev.yml`; use
`docker/docker-compose.agent.dev.gpu-nvidia.yml` with `--profile gpu-nvidia` to
select the opt-in CUDA runtime, which fixes the Compose target to amd64 for its architecture-pinned NVIDIA base. Intel and AMD inventory hosts may need
`VIDEO_GID` and `RENDER_GID` set to host group IDs that can access `/dev/dri`.
# Intel render device
docker compose \
-f docker-compose.yml \
-f docker-compose.gpu-intel.yml \
--profile gpu-intel-inventory up -d heimdall-agent
```
For local development, use the same overlay with
`docker/docker-compose.agent.dev.yml`. For Intel and AMD hosts, set `VIDEO_GID` and `RENDER_GID` to
the host group IDs that can access `/dev/dri`. The NVIDIA option requires the
NVIDIA Container Toolkit and Docker Compose GPU device reservations.
These overlays only expose devices for Agent inventory. They do not enable
GPU-accelerated ONNX inference. Enabling that requires a GPU-specific runtime
image, selecting and reporting the provider actually attached to the ONNX
session, and validation on real supported hardware with a CPU fallback.
The image and Compose build acceptance and physical CUDA execution have not
been run for this change. Local tests cover CPU fallback, CPU/GPU installer
configuration and signed CPU/GPU release manifests; hardware execution remains
open.
+6 -6
View File
@@ -27,9 +27,9 @@ Les critères d’installation varient selon navigateur ; manifeste et contexte
| Rendu | App.razor impose InteractiveServer, prerender désactivé | Conserver en V1 ; écran hors ligne indépendant de Blazor |
| Manifeste | `manifest.webmanifest` est lié dans `App.razor` ; nom, langue, couleurs, scope `/` et icône SVG sont définis | Valider l’installation sur les navigateurs ciblés ; ajouter des icônes raster si nécessaire |
| Icônes | Favicon existant et icône SVG PWA déclarée `any maskable` | Vérifier le rendu réel ; fournir les variantes raster et Apple touch si requises par les plateformes ciblées |
| Service worker | `service-worker.js` versionne le cache public et ne sert la page hors connexion qu’en échec de navigation GET même origine | Valider le cycle de mise à jour et le rollback sur build publié |
| Service worker | `service-worker.js` versionne le cache public et ne sert la page hors connexion qu’en échec de navigation GET même origine ; une nouvelle version attend désormais l’action de rechargement | Parcours local publié testé par E2E ; valider les appareils et le rollback sur un déploiement |
| Hors connexion | `offline.html` est une page statique ; seuls cette page, le manifeste et l’icône sont mis en cache | Vérifier les scénarios réseau sur appareils ; aucune donnée métier ou réponse authentifiée n’est disponible hors ligne |
| Reconnexion | Composant ReconnectModal et module JS existent, sans insertion trouvée dans App/Layouts | Raccorder explicitement et valider sa compatibilité au runtime |
| Reconnexion | L’indicateur Blazor d’erreur de circuit et ses actions de reprise/rechargement sont présents dans `App.razor` | Veille prolongée, changement réseau et reprise de session restent à valider sur appareils |
| Web Push | Aucun PushSubscription, PushManager ou configuration VAPID | Construire backend et client |
| Notifications | SignalR, email, ntfy et préférences existent | Réutiliser la sélection de destinataires, ajouter un canal navigateur |
| Auth | Cookie + JWT + refresh maison | Corriger les défauts SEC-01/02/07/10 de l’audit général |
@@ -37,11 +37,11 @@ Les critères d’installation varient selon navigateur ; manifeste et contexte
| Layout mobile | MudDrawer responsive, quelques règles CSS mobiles | Auditer chaque écran et dialog sur petit écran |
| Langue | `App.razor` indique `lang="fr"` ; le manifeste indique `fr-FR` | Vérifier les contenus localisés par utilisateur lorsque la localisation sera livrée |
| HTTPS/proxy | HSTS présent ; redirection conditionnelle ; pas de UseForwardedHeaders observé | Documenter TLS externe et reconnaître uniquement les proxies de confiance |
| Tests | bUnit et Playwright disponibles | Étendre aux scénarios PWA et appareils réels |
| Tests | E2E Playwright vérifie le manifeste, les icônes publiques, le contenu exact du cache et la navigation hors ligne | Installation, mises à jour à deux onglets, rollback, mobile et HTTPS restent à valider sur appareils/déploiement |
### État du socle livré par la PR #64
Le déploiement actuel suppose que Heimdall est servi à la racine de l’origine (`/`) : le manifeste, le scope, l’enregistrement du worker et ses chemins sont absolus. Un hébergement sous un préfixe (`PathBase`) n’est pas pris en charge par ce socle. Le worker ne met pas en cache le HTML de l’application, les réponses API, les hubs, les médias ou les données privées. Hors connexion, seule la page statique d’information fonctionne ; les interactions Blazor nécessitent une connexion au serveur. L’installation réelle exige une origine HTTPS reconnue (sauf localhost de développement). La validation Android/iOS/desktop, les icônes propres aux plateformes, la reprise mobile et Web Push restent à faire.
Le déploiement actuel suppose que Heimdall est servi à la racine de l’origine (`/`) : le manifeste, le scope, l’enregistrement du worker et ses chemins sont absolus. Un hébergement sous un préfixe (`PathBase`) n’est pas pris en charge. Le worker ne met pas en cache le HTML de l’application, les réponses API, les hubs, les médias ou les données privées. Hors connexion, seule la page statique d’information fonctionne ; les interactions Blazor nécessitent une connexion au serveur. L’aide d’installation utilise `beforeinstallprompt` lorsqu’il est disponible et explique sinon le menu du navigateur, notamment « Sur l’écran d’accueil » sur Safari iOS. Les mises à jour du worker restent en attente jusqu’au choix explicite « Recharger ». L’installation réelle exige une origine HTTPS reconnue (sauf localhost de développement). La validation Android/iOS/desktop, la reprise mobile, le rollback sur déploiement et Web Push restent à faire.
Sources locales principales : [App.razor](../src/Heimdall.Web/Components/App.razor), [Program.cs](../src/Heimdall.Web/Program.cs), [MainLayout](../src/Heimdall.Web/Components/Layout/MainLayout.razor), [ReconnectModal](../src/Heimdall.Web/Components/Layout/ReconnectModal.razor), [AuthStateProvider](../src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs), [NotificationService](../src/Heimdall.Infrastructure/Services/NotificationService.cs).
@@ -51,7 +51,7 @@ Sources locales principales : [App.razor](../src/Heimdall.Web/Components/App.raz
Le manifeste, son lien dans `App.razor`, l’identité stable, la langue et l’icône SVG sont livrés par la PR #64. Le déploiement supporté est à la racine de l’origine (`/`) ; `PathBase` n’est pas pris en charge. Restent à valider l’installation sur les navigateurs cibles, les icônes raster/Apple si nécessaires et les deep links disponibles avant de les proposer comme raccourcis.
L’aide d’installation progressive (événement d’installation quand disponible, instructions propres au navigateur sinon) reste à implémenter. Un navigateur sans installation doit garder une interface utilisable.
L’interface propose l’installation via l’événement natif quand le navigateur le fournit et donne des instructions de menu adaptées au navigateur sinon. Un navigateur sans installation garde une interface utilisable. Les tests E2E valident le manifeste et les ressources d’installation sans authentification ; l’installation effective exige des appareils et une origine HTTPS de déploiement.
### PWA-02 — HTTPS utilisable en auto-hébergement
@@ -80,7 +80,7 @@ Ne pas servir systématiquement `offline.html` pour toutes les navigations : une
### PWA-04 — Mise à jour sans casser les circuits
Le cache est versionné et les anciennes versions sont nettoyées. Le worker appelle actuellement `skipWaiting()` puis `clients.claim()`, ce qui active la nouvelle version sans action utilisateur. Ajouter un état « nouvelle version disponible » et une action de rechargement explicite, puis éviter une activation forcée au milieu d’un formulaire ou d’une session live. Gérer les onglets multiples et le déploiement d’une version serveur incompatible avec les assets déjà chargés. La validation doit porter sur le résultat de `dotnet publish`, pas uniquement sur le serveur de développement.
Le cache est versionné et les anciennes versions sont nettoyées à l’activation. Une nouvelle version installée reste en attente ; l’interface annonce sa disponibilité et transmet `ACTIVATE_UPDATE` uniquement après le clic sur « Recharger », puis recharge à `controllerchange`. Cela évite le remplacement forcé au milieu d’un formulaire ou d’une session live. Les E2E vérifient le shell public et la réponse hors ligne ; les onglets multiples et le rollback d’un build publié restent à vérifier sur un navigateur de déploiement.
L’URL stable et le nettoyage des caches sont en place. Il reste à établir une procédure opérateur et tester le rollback d’un worker défectueux. Une mise à jour de l’application serveur et une mise à jour du cache navigateur sont deux cycles à coordonner.
+3
View File
@@ -145,6 +145,7 @@ Cors__AllowedOrigins=$corsOrigin
TZ=Europe/Paris
REDIS_PASSWORD=$(New-RandomHex)
HEIMDALL_DATA_VOLUME=heimdall_heimdall_data
PLATE_OCR_ENABLED=false
"@
[IO.File]::WriteAllText($envPath, $envContent.TrimStart("`r", "`n"), [Text.Encoding]::ASCII)
Set-PrivateAcl -Path $envPath
@@ -165,6 +166,7 @@ HEIMDALL_DATA_VOLUME=heimdall_heimdall_data
$envContent = Ensure-EnvValue $envContent 'TZ' 'Europe/Paris'
$envContent = Ensure-EnvValue $envContent 'REDIS_PASSWORD' (New-RandomHex)
$envContent = Ensure-EnvValue $envContent 'HEIMDALL_DATA_VOLUME' 'heimdall_heimdall_data'
$envContent = Ensure-EnvValue $envContent 'PLATE_OCR_ENABLED' 'false'
[IO.File]::WriteAllText($envPath, $envContent, [Text.Encoding]::ASCII)
Set-PrivateAcl -Path $envPath
}
@@ -205,6 +207,7 @@ services:
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT}
ASPNETCORE_URLS: http://+:8080
Cors__AllowedOrigins: ${Cors__AllowedOrigins}
PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false}
ports: ["${WEB_PORT}:8080"]
volumes:
- heimdall_data:/var/lib/heimdall
+3
View File
@@ -93,6 +93,7 @@ Cors__AllowedOrigins=${cors_origin}
TZ=Europe/Paris
REDIS_PASSWORD=$(openssl rand -hex 32)
HEIMDALL_DATA_VOLUME=heimdall_heimdall_data
PLATE_OCR_ENABLED=false
EOF
chmod 600 "$env_path"
else
@@ -118,6 +119,7 @@ else
ensure_env_value TZ Europe/Paris
ensure_env_value REDIS_PASSWORD "$(openssl rand -hex 32)"
ensure_env_value HEIMDALL_DATA_VOLUME heimdall_heimdall_data
ensure_env_value PLATE_OCR_ENABLED false
chmod 600 "$env_path"
fi
@@ -159,6 +161,7 @@ services:
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT}
ASPNETCORE_URLS: http://+:8080
Cors__AllowedOrigins: ${Cors__AllowedOrigins}
PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false}
ports: ["${WEB_PORT}:8080"]
volumes:
- heimdall_data:/var/lib/heimdall
+270
View File
@@ -0,0 +1,270 @@
#!/usr/bin/env python3
"""Offline acceptance for package.sh and publish.sh using synthetic credentials and API doubles."""
import base64
import email
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import ssl
import subprocess
import sys
import tempfile
import threading
from email import policy
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
ROOT = Path(__file__).resolve().parents[2]
REPOSITORY = 'arnaud.dartois/Heimdall'
TAG = 'v1.2.3'
DOCKER_TOKEN = 'offline-docker-token-not-valid'
RELEASE_TOKEN = 'offline-gitea-token-not-valid'
SERVER_DIGEST = 'sha256:' + '1' * 64
AGENT_DIGEST = 'sha256:' + '2' * 64
GPU_AGENT_DIGEST = 'sha256:' + '3' * 64
def run(command, *, cwd, env, label):
result = subprocess.run(command, cwd=cwd, env=env, capture_output=True, text=True)
if result.returncode:
output = (result.stdout + result.stderr).replace(DOCKER_TOKEN, '[redacted]').replace(RELEASE_TOKEN, '[redacted]')
if label == 'publish.sh':
provenance_path = cwd / 'artifacts/packages/provenance.json'
if provenance_path.exists():
output += '\nOffline provenance: ' + json.dumps(json.loads(provenance_path.read_text()), sort_keys=True)
raise RuntimeError(f'{label} failed ({result.returncode}):\n{output[-12000:]}')
return result.stdout
def main():
artifacts_dir = ROOT / 'artifacts'
if artifacts_dir.exists():
raise RuntimeError('Refusing to overwrite or remove an existing artifacts/ directory; run from a clean worktree.')
with tempfile.TemporaryDirectory(prefix='heimdall-release-offline-') as temp_name:
temp = Path(temp_name)
cert = temp / 'localhost.pem'
private_cert_key = temp / 'localhost-key.pem'
release_key = temp / 'release-key.pem'
fakebin = temp / 'bin'
fakebin.mkdir()
docker_log = temp / 'docker-commands.jsonl'
release_state = {'draft': None, 'assets': {}, 'authorized': 0}
subprocess.run([
'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-sha256', '-days', '1', '-nodes',
'-keyout', str(private_cert_key), '-out', str(cert), '-subj', '/CN=127.0.0.1',
'-addext', 'subjectAltName=IP:127.0.0.1',
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(['openssl', 'ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', str(release_key)],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
signing_key_b64 = base64.b64encode(release_key.read_bytes()).decode('ascii')
docker_stub = r'''#!/usr/bin/env python3
import json, os, sys
args = sys.argv[1:]
log = os.environ['OFFLINE_DOCKER_LOG']
with open(log, 'a') as f: f.write(json.dumps(args) + '\n')
if args[:1] == ['build']:
target = args[args.index('-t') + 1]
sys.exit(0)
if args[:2] == ['login', 'docker.io']:
if sys.stdin.read().strip() != os.environ['DOCKERHUB_TOKEN'] or os.environ.get('DOCKERHUB_USERNAME') != 'offline-user':
sys.exit(11)
sys.exit(0)
if args[:2] == ['manifest', 'inspect']:
sys.exit(1) # Simulate absent remote tags; never call a registry.
if args[:1] == ['tag']:
sys.exit(0)
if args[:1] == ['push']:
sys.exit(0) # Simulated push only; no registry client exists in this stub.
if args[:2] == ['image', 'inspect']:
image = args[2].split(':', 1)[0]
if image.endswith('heimdall-agent-gpu'):
digest = os.environ['OFFLINE_GPU_DIGEST']
elif image.endswith('heimdall-agent'):
digest = os.environ['OFFLINE_AGENT_DIGEST']
else:
digest = os.environ['OFFLINE_SERVER_DIGEST']
print(image + '@' + digest)
sys.exit(0)
if args[:1] == ['save']:
from pathlib import Path
Path(args[args.index('-o') + 1]).write_bytes(b'offline-image-archive')
sys.exit(0)
if args[:2] == ['volume', 'create']:
print(args[2])
sys.exit(0)
if args[:1] == ['create']:
print('offline-scanner-container')
sys.exit(0)
if args[:1] == ['cp'] or args[:1] == ['rm'] or args[:2] == ['volume', 'rm']:
sys.exit(0)
if args[:2] == ['start', '--attach']:
print('{"Results":[]}')
sys.exit(0)
if args[:1] == ['inspect']:
print('exited 0')
sys.exit(0)
sys.exit(12)
'''
docker_path = fakebin / 'docker'
docker_path.write_text(docker_stub)
docker_path.chmod(0o700)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args):
return
def _authorized(self):
ok = self.headers.get('Authorization') == 'token ' + RELEASE_TOKEN
if ok:
release_state['authorized'] += 1
return ok
def _json(self, status, value):
payload = json.dumps(value).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
if not self._authorized():
self._json(401, {})
return
path = urlsplit(self.path).path
if path.endswith('/releases/tags/' + TAG):
self._json(404, {'message': 'not found'})
elif path.endswith('/releases/7301/assets'):
self._json(200, [])
else:
self._json(404, {'message': 'unexpected request'})
def do_POST(self):
if not self._authorized():
self._json(401, {})
return
path = urlsplit(self.path).path
body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
if path.endswith('/releases'):
release = json.loads(body)
assert release['tag_name'] == TAG
assert release['draft'] is True
assert release['target_commitish'] == subprocess.check_output(
['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
release_state['draft'] = release
self._json(201, {'id': 7301, 'draft': True,
'html_url': 'https://gitea.test/releases/7301'})
return
if path.endswith('/releases/7301/assets'):
content_type = self.headers.get('Content-Type')
message = email.message_from_bytes(
b'Content-Type: ' + content_type.encode() + b'\r\nMIME-Version: 1.0\r\n\r\n' + body,
policy=policy.default,
)
parts = list(message.iter_parts())
assert len(parts) == 1
filename = parts[0].get_filename()
assert filename and filename not in release_state['assets']
release_state['assets'][filename] = parts[0].get_payload(decode=True)
self._json(201, {'id': 8000 + len(release_state['assets']), 'name': filename})
return
self._json(404, {'message': 'unexpected request'})
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert, private_cert_key)
server.socket = context.wrap_socket(server.socket, server_side=True)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
origin = f'https://127.0.0.1:{server.server_port}'
env = os.environ.copy()
env.update({
'PATH': str(fakebin) + os.pathsep + os.environ['PATH'],
'SSL_CERT_FILE': str(cert),
'NO_PROXY': '127.0.0.1,localhost',
'no_proxy': '127.0.0.1,localhost',
'BUILD_REF': 'refs/tags/' + TAG,
'BUILD_REPOSITORY': REPOSITORY,
'BUILD_RUN_ID': 'offline-acceptance',
'BUILD_SERVER_URL': origin,
'EXPECTED_BUILD_SERVER_URL': origin,
'DOCKERHUB_USERNAME': 'offline-user',
'DOCKERHUB_TOKEN': DOCKER_TOKEN,
'RELEASE_TOKEN': RELEASE_TOKEN,
'RELEASE_SIGNING_KEY_B64': signing_key_b64,
'OFFLINE_DOCKER_LOG': str(docker_log),
'OFFLINE_SERVER_DIGEST': SERVER_DIGEST,
'OFFLINE_AGENT_DIGEST': AGENT_DIGEST,
'OFFLINE_GPU_DIGEST': GPU_AGENT_DIGEST,
})
run(['bash', 'scripts/ci/package.sh'], cwd=ROOT, env=env, label='package.sh')
run(['bash', 'scripts/ci/publish.sh'], cwd=ROOT, env=env, label='publish.sh')
packages = ROOT / 'artifacts/packages'
public_key = temp / 'release-public.pem'
public_key.write_bytes(release_state['assets']['agent-release-public.pem'])
manifest_bytes = release_state['assets']['agent-update-manifest.json']
signature = temp / 'manifest.sig'
signature.write_bytes(release_state['assets']['agent-update-manifest.sig'])
manifest = json.loads(manifest_bytes)
assert manifest['version'] == TAG
assert manifest['containerImage'] == 'eltruncho/heimdall-agent'
assert manifest['containerImageDigest'] == AGENT_DIGEST
assert manifest['containerImageGpu'] == 'eltruncho/heimdall-agent-gpu'
assert manifest['containerImageGpuDigest'] == GPU_AGENT_DIGEST
provenance = json.loads(release_state['assets']['provenance.json'])
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/' + TAG
agent_image = json.loads(release_state['assets']['agent-image.json'])
assert agent_image == {'digest': AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent'}
gpu_agent_image = json.loads(release_state['assets']['agent-image-gpu.json'])
assert gpu_agent_image == {'digest': GPU_AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent-gpu'}
for platform, digest in manifest['assets'].items():
archive = f'heimdall-agent-{platform}-{TAG.removeprefix("v")}.tar.gz'
assert hashlib.sha256(release_state['assets'][archive]).hexdigest() == digest
subprocess.run(['openssl', 'dgst', '-sha256', '-verify', str(public_key),
'-signature', str(signature), str(packages / 'agent-update-manifest.json')],
check=True, stdout=subprocess.DEVNULL)
checksums = release_state['assets']['SHA256SUMS'].decode().splitlines()
for line in checksums:
digest, filename = line.split(maxsplit=1)
filename = filename.lstrip('* ')
assert filename in release_state['assets'], f'missing checksum asset {filename}'
assert hashlib.sha256(release_state['assets'][filename]).hexdigest() == digest, filename
image_digests = release_state['assets']['image-digests.txt'].decode().splitlines()
assert len(image_digests) == 6
assert sum(AGENT_DIGEST in item for item in image_digests) == 2
assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 2
docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()]
assert sum(call[:1] == ['build'] for call in docker_calls) == 3
pushes = {call[1] for call in docker_calls if call[:1] == ['push']}
assert len(pushes) == 6
assert pushes == {
f'eltruncho/heimdall:sha-{commit}', f'eltruncho/heimdall:1.2.3',
f'eltruncho/heimdall-agent:sha-{commit}', f'eltruncho/heimdall-agent:1.2.3',
f'eltruncho/heimdall-agent-gpu:sha-{commit}', f'eltruncho/heimdall-agent-gpu:1.2.3',
}
assert sum(call[:1] == ['login'] for call in docker_calls) == 1
assert release_state['draft']['draft'] is True
assert len(release_state['assets']) >= 9
assert release_state['authorized'] >= 7
print(f'Offline release simulation passed: package archives, P-256 signature, {len(release_state["assets"])} draft assets, checksums, CPU/GPU image digests, and six simulated pushes.')
print('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.')
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
if artifacts_dir.exists():
shutil.rmtree(artifacts_dir)
if __name__ == '__main__':
main()
+1
View File
@@ -13,6 +13,7 @@ EF_CORE_EXCEPTIONS = {
"src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs": "PostgreSQL VACUUM/REINDEX and catalog inspection",
"src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs": "PostgreSQL partition DDL and catalog inspection",
"src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs": "transaction-scoped PostgreSQL advisory lock",
"src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs": "transaction-scoped PostgreSQL advisory lock for serialized recording quota checks",
"src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs": "idempotent PostgreSQL bulk insert with ON CONFLICT DO NOTHING",
"src/Heimdall.Agent/Data/AgentOutboxDatabaseInitializer.cs": "baseline and migrate pre-EF local SQLite outbox schemas",
}
+4 -3
View File
@@ -6,13 +6,14 @@ version=$(cat artifacts/version 2>/dev/null || printf '0.0.0-ci.%s' "${sha:0:12}
: "${BUILD_REPOSITORY:?Gitea repository is required}"
source_url="${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
case "${1:-all}" in
all) components=(server agent) ;;
server|agent) components=("$1") ;;
*) echo 'Usage: images.sh [server|agent|all]' >&2; exit 2 ;;
all) components=(server agent agent-gpu) ;;
server|agent|agent-gpu) components=("$1") ;;
*) echo 'Usage: images.sh [server|agent|agent-gpu|all]' >&2; exit 2 ;;
esac
for component in "${components[@]}"; do
file=docker/Dockerfile
[[ "$component" == agent ]] && file=docker/Dockerfile.agent
[[ "$component" == agent-gpu ]] && file=docker/Dockerfile.agent.gpu
docker build --pull --platform linux/amd64 -f "$file" --build-arg "VERSION=$version" \
--label "org.opencontainers.image.revision=$sha" \
--label "org.opencontainers.image.version=$version" \
+27 -2
View File
@@ -44,19 +44,25 @@ PY
(cd artifacts/packages && sha256sum --check SHA256SUMS)
printf '%s' "${tag#v}" > artifacts/version
bash scripts/ci/images.sh
for image_component in server agent agent-gpu; do
bash scripts/ci/security.sh "$image_component"
done
# No mutation is attempted until all credentials, provenance and local builds pass.
export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT
server_image=eltruncho/heimdall
agent_image=eltruncho/heimdall-agent
agent_gpu_image=eltruncho/heimdall-agent-gpu
: "${DOCKERHUB_USERNAME:?Docker Hub user is required}"
: "${DOCKERHUB_TOKEN:?Docker Hub token is required}"
printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin
: > artifacts/image-digests.txt
for component in server agent; do
for component in server agent agent-gpu; do
if [[ "$component" == agent ]]; then
image=$agent_image
elif [[ "$component" == agent-gpu ]]; then
image=$agent_gpu_image
else
image=$server_image
fi
@@ -91,11 +97,29 @@ with open('artifacts/packages/agent-image.json','w') as f:
f.write('\n')
PY
(cd artifacts/packages && sha256sum agent-image.json >> SHA256SUMS)
python3 - "$agent_gpu_image" <<'PY'
import json,sys
repository=sys.argv[1]
matches=set()
for line in open('artifacts/image-digests.txt'):
ref=line.strip()
if '@' not in ref: continue
image,digest=ref.rsplit('@',1)
if image == repository and digest.startswith('sha256:') and len(digest) == 71:
matches.add(digest)
if len(matches) != 1:
raise SystemExit('Expected one immutable GPU agent image digest for configured repository')
with open('artifacts/packages/agent-image-gpu.json','w') as f:
json.dump({'image':repository,'digest':matches.pop()},f,sort_keys=True,separators=(',',':'))
f.write('\n')
PY
(cd artifacts/packages && sha256sum agent-image-gpu.json >> SHA256SUMS)
python3 - <<'PY'
import hashlib,json,re
from pathlib import Path
root=Path('artifacts/packages')
image=json.loads((root/'agent-image.json').read_text())
gpu_image=json.loads((root/'agent-image-gpu.json').read_text())
package_version=Path('artifacts/version').read_text().strip()
version='v'+package_version
assets={}
@@ -110,7 +134,8 @@ for path in root.glob('heimdall-agent-*.tar.gz'):
if not assets:
raise SystemExit('No agent archive to sign')
payload={'version':version,'assets':assets,'containerImage':image['image'],
'containerImageDigest':image['digest']}
'containerImageDigest':image['digest'],'containerImageGpu':gpu_image['image'],
'containerImageGpuDigest':gpu_image['digest']}
(root/'agent-update-manifest.json').write_text(
json.dumps(payload,sort_keys=True,separators=(',',':'))+'\n')
PY
+3 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
mode=${1:?Expected server, agent or latest}
case "$mode" in server|agent|latest) ;; *) echo 'Usage: push-images.sh server|agent|latest' >&2; exit 2 ;; esac
mode=${1:?Expected server, agent, agent-gpu or latest}
case "$mode" in server|agent|agent-gpu|latest) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu|latest' >&2; exit 2 ;; esac
sha=$(git rev-parse HEAD)
if [[ "$mode" == latest ]]; then components=(server agent); else components=("$mode"); fi
export DOCKER_CONFIG
@@ -11,6 +11,7 @@ repository() {
case "$1" in
server) printf 'eltruncho/heimdall' ;;
agent) printf 'eltruncho/heimdall-agent' ;;
agent-gpu) printf 'eltruncho/heimdall-agent-gpu' ;;
esac
}
: "${DOCKERHUB_USERNAME:?Docker Hub user is required}"
+60
View File
@@ -0,0 +1,60 @@
import { pathToFileURL } from 'node:url';
const endpoint = process.env.RENOVATE_ENDPOINT;
const token = process.env.RENOVATE_TOKEN;
const repository = 'arnaud.dartois/Heimdall';
export function validateEndpoint(value) {
let parsed;
try {
parsed = new URL(value);
} catch {
throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
}
if (parsed.protocol !== 'https:' || parsed.username || parsed.password ||
parsed.search || parsed.hash || !parsed.pathname.replace(/\/$/, '').endsWith('/api/v1')) {
throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
}
return parsed.href.replace(/\/$/, '');
}
export async function checkGiteaAccess(apiEndpoint, accessToken, fetchImpl = fetch) {
const root = `${validateEndpoint(apiEndpoint)}/`;
const urls = [new URL('user', root), new URL(`repos/${repository}`, root)];
for (const url of urls) {
let response;
try {
response = await fetchImpl(url, {
headers: { Authorization: `token ${accessToken}`, Accept: 'application/json' },
signal: AbortSignal.timeout(10_000),
});
} catch (error) {
throw new Error(`Gitea API preflight could not connect (${error?.name ?? 'network error'}).`);
}
if (!response.ok) {
const detail = response.status === 401 || response.status === 403
? 'Check that RENOVATE_TOKEN is active and has repository read and write access.'
: 'Check GITEA_API_ENDPOINT and the Gitea API availability.';
throw new Error(`Gitea API preflight failed with HTTP ${response.status}. ${detail}`);
}
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
if (!token) {
console.error('RENOVATE_TOKEN is missing. Configure it as a Gitea Actions secret.');
process.exitCode = 1;
} else {
try {
await checkGiteaAccess(endpoint, token);
console.log('Renovate token authenticated with Gitea and can read the target repository.');
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}
}
+36
View File
@@ -0,0 +1,36 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { checkGiteaAccess, validateEndpoint } from './renovate-preflight.mjs';
test('accepts an HTTPS Gitea API endpoint and trims its trailing slash', () => {
assert.equal(validateEndpoint('https://forge.example/api/v1/'), 'https://forge.example/api/v1');
});
test('rejects non-HTTPS, malformed, and non-API endpoints', () => {
for (const value of ['http://forge.example/api/v1', 'https://forge.example/', 'not a URL']) {
assert.throws(() => validateEndpoint(value), /HTTPS URL ending in \/api\/v1/);
}
});
test('checks identity and repository reads without exposing the token', async () => {
const calls = [];
await checkGiteaAccess('https://forge.example/api/v1', 'secret-token', async (url, options) => {
calls.push({ url: url.href, authorization: options.headers.Authorization });
return { ok: true, status: 200 };
});
assert.deepEqual(calls.map(call => new URL(call.url).pathname), [
'/api/v1/user', '/api/v1/repos/arnaud.dartois/Heimdall',
]);
assert.ok(calls.every(call => call.authorization === 'token secret-token'));
});
test('reports authentication status without printing response details or credentials', async () => {
await assert.rejects(
checkGiteaAccess('https://forge.example/api/v1', 'secret-token', async () => ({
ok: false, status: 403,
})),
error => error.message.includes('HTTP 403') &&
error.message.includes('repository read and write access') &&
!error.message.includes('secret-token'),
);
});
+2 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
mode=${1:-all}
case "$mode" in dependencies|server|agent|all) ;; *) echo 'Usage: security.sh [dependencies|server|agent|all]' >&2; exit 2 ;; esac
case "$mode" in dependencies|server|agent|agent-gpu|all) ;; *) echo 'Usage: security.sh [dependencies|server|agent|agent-gpu|all]' >&2; exit 2 ;; esac
skip_restore=false
if [[ $# -gt 1 ]]; then
if [[ "$mode" == dependencies && $# == 2 && "${2}" == --no-restore ]]; then
@@ -71,7 +71,7 @@ scan_image() (
exit 1
)
case "$mode" in
all) components=(server agent) ;;
all) components=(server agent agent-gpu) ;;
*) components=("$mode") ;;
esac
for component in "${components[@]}"; do
+59
View File
@@ -83,6 +83,56 @@ class TestPlanTests(unittest.TestCase):
self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS))
self.assertEqual(planner.plan(['docs/README.md'])['suites'], [])
class GpuAgentImageTests(unittest.TestCase):
def test_cpu_default_stays_independent_of_nvidia_runtime(self):
dockerfile = (REPO_ROOT/'docker/Dockerfile.agent').read_text()
compose = (REPO_ROOT/'docker/docker-compose.agent.dev.yml').read_text()
self.assertNotIn('nvidia/cuda', dockerfile)
self.assertNotIn('Agent__InferenceExecutionProvider: CUDA', compose)
self.assertNotIn('driver: nvidia', compose)
def test_gpu_runtime_and_optional_overlay_pin_cuda_runtime_and_provider(self):
dockerfile = (REPO_ROOT/'docker/Dockerfile.agent.gpu').read_text()
compose = (REPO_ROOT/'docker/docker-compose.agent.dev.gpu-nvidia.yml').read_text()
self.assertIn('nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9', dockerfile)
self.assertIn('Microsoft.ML.OnnxRuntime.Gpu', (REPO_ROOT/'src/Heimdall.Agent/Heimdall.Agent.csproj').read_text())
self.assertIn('Agent__InferenceExecutionProvider: CUDA', compose)
self.assertIn('driver: nvidia', compose)
self.assertIn('capabilities: [gpu]', compose)
self.assertIn('image: heimdall-agent:gpu-local', compose)
state_init = compose.split(' agent-state-init:', 1)[1]
self.assertIn('dockerfile: docker/Dockerfile.agent.gpu', state_init)
class NativeAgentUpdateTests(unittest.TestCase):
def test_supervisor_rolls_back_failed_startup_to_previous_release(self):
with tempfile.TemporaryDirectory(prefix='hmd-supervisor-test-') as temporary:
root = Path(temporary)
old_release = root/'releases'/'v1.0.0'
new_release = root/'releases'/'v1.0.1'
old_release.mkdir(parents=True)
new_release.mkdir()
(old_release/'Heimdall.Agent.dll').write_bytes(b'old synthetic release')
(new_release/'Heimdall.Agent.dll').write_bytes(b'new synthetic release')
current = root/'current'
current.symlink_to(new_release, target_is_directory=True)
pending = root/'pending-update.json'
pending.write_text(json.dumps({'version': '1.0.1', 'previous': str(old_release)}))
dotnet = root/'fake-dotnet'
dotnet.write_text('#!/bin/sh\nexit 1\n')
dotnet.chmod(0o755)
environment = os.environ.copy()
environment['Agent__UpdateInstallRoot'] = str(root)
environment['HEIMDALL_DOTNET'] = str(dotnet)
result = subprocess.run(
[sys.executable, str(REPO_ROOT/'install/agent-supervisor.py')],
env=environment, capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 75, result.stderr)
self.assertEqual(current.resolve(), old_release.resolve())
self.assertFalse(pending.exists())
self.assertIn('previous release restored', result.stderr)
class AdvisoryTests(unittest.TestCase):
def check(self, data):
with tempfile.TemporaryDirectory() as temp:
@@ -150,5 +200,14 @@ class ReleaseTests(unittest.TestCase):
with self.assertRaisesRegex(SystemExit, 'already public'):
self.execute(public=True)
class OfflineReleaseAcceptanceTests(unittest.TestCase):
def test_publish_signs_and_uploads_cpu_and_gpu_image_manifests(self):
result = subprocess.run(
[sys.executable, str(ROOT/'accept-release-offline.py')],
cwd=REPO_ROOT, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn('CPU/GPU image digests', result.stdout)
self.assertIn('six simulated pushes', result.stdout)
if __name__ == '__main__':
unittest.main()
+4
View File
@@ -21,6 +21,10 @@ for gpu in nvidia amd intel; do
--profile "gpu-$gpu-inventory"
done
compose -f docker/docker-compose.agent.dev.yml \
-f docker/docker-compose.agent.dev.gpu-nvidia.yml \
--profile gpu-nvidia
for required in DATABASE_URL POSTGRES_PASSWORD JWT__KEY JWT__REFRESHKEY; do
if env "$required=" docker compose --env-file .env.example \
-f docker/docker-compose.yml config --quiet >/dev/null 2>&1; then
+39
View File
@@ -0,0 +1,39 @@
---
name: agent-runtime-acceptance
description: Validate Heimdall Agent reconnect, camera configuration replacement, acknowledgement, and runtime diagnostics without camera hardware.
---
# Heimdall Agent runtime acceptance
Read `AGENTS.md`, the Agent item in `todo.md`, and `skills/heimdall-dotnet/SKILL.md` before changing Agent runtime behavior.
## Camera configuration synchronization
- `ConfigReceiverService` fetches the complete camera settings snapshot after initial connection and reconnection; `CameraConfigStore.ReplaceCentral` validates the digest and publishes all assignments atomically.
- The Central acknowledgement is keyed to that exact digest. Retry network failures and HTTP 408/429/5xx at most three times with short bounded delays; stop on permanent 4xx responses. Do not log the API key, camera URLs, configuration payload, or response body.
- Keep the latest applied snapshot active when an acknowledgement is rejected. A later config reload/reconnect fetches and acknowledges the current snapshot again.
- `FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt` uses an in-process Kestrel Central simulator: config GET is served once; ACK receives 503 then 204; both posts must carry the same digest; the camera snapshot change event fires once; and Central records one successful ACK. `HEIMDALL_ACK_FIXTURE_PORT` pins the listener for Compose, while the API key fixture can be injected through `HEIMDALL_ACK_FIXTURE_API_KEY`.
- Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values.
## Central log upload contract
- Agent log levels must use the exact `AgentLogLevel` names accepted by Central's parser: `Information` and `Warning` (not the common aliases `Info`/`Warn`), alongside `Trace`, `Debug`, `Error`, and `Critical`.
- Keep `ToCentralLevel_MapsMicrosoftNamesToAgentContract` asserting both the emitted name and that Central's enum parser accepts it at the corresponding severity.
- Agent logging is API-key authenticated. A source-built disposable Compose check can register a synthetic Agent, submit one entry at each severity to `/api/agents/{id}/logs`, and read them back through the authorized Central log query. Keep generated credentials and project resources isolated and clean up exact locally built tags per the Compose recipe.
## Local checks
```bash
dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore
```
For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. This SDK-only recipe builds no local images; keep the shared upstream SDK image. Install an EXIT cleanup trap before starting, tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source even on failure. The acceptance record must state `local image tags: none`; if future changes add a local image build, record its unique tag and remove/verify that exact tag in the same trap. Serialize Docker acceptance when another source build is using the shared daemon.
This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`.
For camera enable/disable timing, distinguish Central's requested state, the exact configuration digest acknowledged by the Agent, and actual FFmpeg process release. A status transition alone is not proof that capture stopped. Poll `/proc/<pid>/comm` (or an equivalent exact process identity that cannot match the harness command); measure stop convergence separately from config ACK convergence. The synthetic-camera acceptance must cover initial OFF, ON, OFF, ON, restart while ON, then OFF and restart while OFF with the persisted Agent identity, asserting the newest digest after each update. Record the observed OFF latency and keep the item open if it exceeds the product's 2-second expectation. Every attempt uses a new project and exact source-built Central/Agent tags, records both before build, and removes/verifies them plus all project resources in its EXIT trap.
## Acceptance boundary
In-memory SignalR/HTTP fixtures and a local Agent container validate reconnect and runtime behavior without a physical camera. Mark real-camera stream stability, resource release on the deployed host, and LAN discovery as open until they pass on representative hardware and network equipment.
+30
View File
@@ -0,0 +1,30 @@
---
name: heimdall-agent-update-acceptance
description: Validate Heimdall native Agent install, signed update, startup health, and rollback behavior.
---
# Native Agent update acceptance
Use this skill when changing `install/install-agent.sh`, `install/install-agent.ps1`, `install/agent-supervisor.py`, or `install/agent-update-supervisor.ps1`.
## Linux rollback simulation
- Run `python3 -m unittest discover -s scripts/ci -p 'test_*.py' -k supervisor_rolls_back_failed_startup_to_previous_release`.
- The test creates two synthetic release directories and a `current` link to the candidate, writes a pending-update marker, and injects a fake `dotnet` executable that exits immediately with failure.
- Verify the supervisor returns 75, atomically points `current` back at the prior release, removes `pending-update.json`, and reports that the previous release was restored. The fixture must live in `TemporaryDirectory` and leave no files behind.
- This covers only the startup-failure rollback branch. It does not validate HTTP update discovery, signed archive verification, a 60-second healthy startup window, systemd, Windows service behavior, or a real Agent host.
## Local and host acceptance boundary
- Keep `HEIMDALL_SOURCE_BASE_URL` limited to Heimdall-owned installer assets; vendor runtimes and dependencies must use their official distribution channels.
- For updates, exercise both successful and rejected signatures before installation. Preserve the previous release until the candidate has reported the expected version and stayed healthy for the configured stability interval.
- Use a temporary install root and fake runtime for local failure/rollback tests. Never point these tests at `/usr/local`, a real systemd service, production credentials, or an installed Agent state directory.
- Report Linux and Windows real-host install/update/rollback as open until each OS has been exercised with a real service and the expected signing configuration.
## Central installer asset delivery
- `Heimdall.Web.csproj` publishes the Linux/Windows Agent installers and their supervisors under `wwwroot/install/`; `Program.ConfigureMiddleware` serves them through ASP.NET Core static files.
- ASP.NET Core's default MIME table does not recognize `.py`. Add `.py` to a `FileExtensionContentTypeProvider` explicitly or `/install/agent-supervisor.py` returns 404 despite being present in `wwwroot`.
- For changes to these assets or static-file configuration, build Central from the current source in a disposable Compose project and GET `/install/install-agent.sh` and `/install/agent-supervisor.py`. Require HTTP 200 and byte-for-byte equality with their source files. Also require `/healthz` healthy.
- Follow `skills/compose-disposable-recipe/SKILL.md`: use generated credentials, isolated ports/project volumes/network, a unique Central image tag, and an EXIT trap installed before build. Verify all project containers, volumes, and networks are gone and remove/verify absence of the exact local image tag. Keep shared base images.
- A successful local acceptance proves the source-built Central serves the files; it does not prove a deployed Central image has been rebuilt or restarted. Confirm deployed endpoints separately before calling an incident resolved.
+40
View File
@@ -0,0 +1,40 @@
---
name: analysis-job-pipeline
description: Implement and verify analysis job types across Heimdall Central scheduling and Agent inference.
---
# Heimdall analysis job pipeline
Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet/SKILL.md`. For database behavior, also follow `skills/ef-core-persistence/SKILL.md`.
## Current supported job types
- `ObjectDetection`: return every detection produced by the configured YOLO COCO model.
- `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`).
- `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`). Keep the model label, confidence, box and class index in the result.
- `MotionDetection`: capture two frames from the already active RTSP stream 500 ms apart, downscale both to 32×18, and compare normalized luminance. A changed pixel must differ by at least 0.12; at least 2% changed pixels returns one `motion` detection with changed-region bounds and changed-pixel ratio as confidence. This CPU-only temporal detector does not require the YOLO model; lighting changes and camera shake may produce motion, so tune/measure it against representative cameras before relying on alerts.
- The Web request whitelist, Central scheduler whitelist/capability requirements, and Agent parser must agree. The Agent accepts enum names and numeric enum values on the wire. Reject unsupported kinds instead of recording a successful empty result.
- Face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection.
- Jobs stay assigned to the Agent currently responsible for the camera. Keep the attempt ID, atomic claims, retries and late-result rejection intact when adding types.
- Result delivery retries transport failures, timeouts and HTTP 5xx with bounded backoff. A 409/404 attempt is no longer current and stops immediately; other HTTP 4xx responses are permanent for that submission and must also stop immediately so a bad result cannot block the Agent's next poll. Log the status code and job ID only; do not read or log Central response bodies.
## Required validation
1. Unit-test Agent type parsing, motion comparison for identical/changed frames, and exact COCO class filtering for the object/person/vehicle types, including empty results and unsupported types.
2. Run PostgreSQL scheduler tests proving CPU/RAM requirements for supported types and refusal of unsupported types. Do not substitute EF InMemory for relational behavior.
3. Run the PostgreSQL integration scenario through the Web API: create each supported job, dispatch to the assigned online Agent, claim it with the Agent API key, submit a result, and verify persisted completion. Verify unsupported type requests receive HTTP 400.
4. Build Central from the changed source in a uniquely tagged disposable Compose project with generated credentials, loopback-only ports, project-owned volumes/network, empty Sentry DSN, and OCR disabled unless the scenario explicitly needs it. Bootstrap synthetic Admin/site/camera, register and heartbeat a synthetic Agent, assign the camera, submit supported and unsupported job types, and verify the lease/result boundary where practical.
5. Tear down that exact Compose project, verify zero project containers/volumes/networks, remove every source-built image tag from this recipe and verify each exact tag is absent. Retain shared Postgres/.NET base images. Never use broad prune commands.
6. Keep hardware, camera-stream inference, and real multi-Agent deployment claims separate from synthetic database/API acceptance.
For event-handler unit tests, initialize every queried set on the `IApplicationDbContext` substitute with `MockDbSetHelper`, including empty optional sets such as `Recordings`. An unconfigured NSubstitute `DbSet` throws from EF's `IQueryable.Provider` when the handler applies `AsNoTracking` or async LINQ. Use PostgreSQL integration tests for provider translation and persistence behavior; this unit fixture is only for handler branching and notification behavior.
The shared Playwright `E2ETestBase.GotoWithCircuitAsync` dismisses the install-help banner after each navigation. Loopback is a secure browser context, so PWA UI appears in these tests and can intercept clicks on dialogs; browser E2E assertions should exercise the intended application controls after dismissing that unrelated notice.
## Current local acceptance evidence
Result delivery has a focused Agent test: `SendResultAsync_DoesNotRetryPermanentClientRejection` returns after one HTTP 400. The supported result JSON uses web defaults (`classIndex`, not `ClassIndex`). The disposable source Compose acceptance below validates the Central job API and persisted result contract; keep transport retry behavior covered by the Agent HTTP-handler test.
On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections, not video inference.
Motion detection implementation and acceptance (5 November 2026): Agent compares two frames 500 ms apart from the active stream at 32×18 luminance; threshold is 0.12 per pixel and 2% changed pixels, and output is one normalized `motion` region. Central API/scheduler accept the type and its 1-core/512-MB/3-minute capability limits. Tests passed: Agent selection/comparison 13/13, PostgreSQL scheduler 27/27, Web/PostgreSQL API contract 3/3. Source-built disposable Compose project `hmd-motion-1793890915-22844` registered a real Agent container, started a synthetic moving RTSP stream, assigned the camera, created a MotionDetection job, and verified the Agent result with label `motion` and normalized bounds persisted in PostgreSQL. The project was torn down and verified at zero containers/volumes/networks; unique Central/Agent tags were removed and verified absent. Camera shake, exposure/lighting changes and representative real-camera thresholds remain unvalidated.
+28
View File
@@ -0,0 +1,28 @@
---
name: backup-restore
description: Validate Heimdall PostgreSQL and protected-volume backups using isolated Compose projects and the production backup/restore scripts.
---
# Heimdall backup and restore
Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/restore*.sh`, the backup Compose, or the disaster-recovery runbook.
## Project-specific behavior
- PostgreSQL backups use `docker/scripts/backup.sh` and restores use `restore.sh`. Supply credentials through a generated `POSTGRES_PASSWORD_FILE` or a generated environment file; never reuse `docker/.env`, production secrets, or live volumes.
- `backup-protected-data.sh` archives the Central data volume, including local objects and `dp-keys`. Restore with `restore-protected-data.sh` only while Central is stopped. The script overlays files and deliberately keeps unrelated target files.
- PostgreSQL and protected-volume archives are separate snapshots. The application does not coordinate them into one atomic point in time.
- `test-backup-restore.sh` uses a named isolated network, `tmpfs` for its disposable PostgreSQL data directory, and a temporary host directory. Its cleanup must leave no container, network, or anonymous volume.
## Acceptance
1. Read `docker/backup/README.md` and `docker/scripts/test-backup-restore.sh` before changing the flow.
2. Run the script and require all assertions to pass, including row/FK integrity, object/key digests, and Data Protection key permissions.
3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions.
4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO.
5. Install an EXIT cleanup trap before build/start. Tear down only the disposable project with `docker compose -p <name> down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files even on a failed assertion. These fixtures use upstream PostgreSQL/RustFS images and build no local image unless a recipe change explicitly adds one; retain those upstream images. If adding a local build, record its unique tag and remove/verify that exact tag in the same trap after teardown. Never use `--rmi all` or broad prune commands.
6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox). Do not rely on the retired MinIO client download URL. The scripts pass configured S3 credentials explicitly to AWS CLI for each invocation.
7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed.
8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data.
These backup recipes use shared upstream PostgreSQL/RustFS images and do not build a Heimdall image by default; retain those base images. Record `local image tags: none` for such a run. If a changed recipe adds any local build, tag it uniquely for the Compose project and remove/verify that exact tag after teardown in the same EXIT trap, even on failure. Do not use image-prune commands.
+21
View File
@@ -0,0 +1,21 @@
---
name: camera-access-groups
description: Implement and validate Heimdall user-to-camera grants and group camera access through the administration UI and API.
---
# Camera access and groups
Camera visibility is the union of direct camera grants, site-wide grants, legacy user site assignments, and cameras granted to groups the user belongs to. Keep that union in `CameraAccessService` and `ResourceAccess`; do not reimplement partial scope rules in controllers or UI queries. Site and camera resource checks must continue to run at API/application boundaries, including snapshots, events, hubs, and agent assignment.
Manage group-camera membership through the authenticated `api/groups/{groupId}/cameras` endpoints. The administration page loads all sites and their cameras with bounded paging, displays site names beside cameras, and adds/removes grants through the API. Treat failed loads and mutations as errors; do not optimistically report success.
When changing this area, verify:
- `ResourceAccessTests` for the role/grant matrix, live group membership revocation, and union of direct plus group grants.
- `HttpIsolationTests` and the affected API integration tests for real HTTP authorization outcomes.
- `GroupsPageTests` for site/camera labels and the UI add/remove request sequence.
- PostgreSQL integration tests for persistence or query changes; do not use EF InMemory as relational proof.
- The disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md` for behavior or deployment changes, using a unique project, network, credentials, ports, and volumes.
- If Compose builds Central from source, record a project-unique tag and install an EXIT cleanup trap before build/start. After teardown remove and verify absence of that exact tag even on failure; retain shared base images and report cleanup errors.
Use synthetic camera metadata in automated tests. Physical RTSP, snapshot and reconnect behavior is a separate Agent/camera acceptance and must be reported as unverified unless run against real hardware.
+17
View File
@@ -0,0 +1,17 @@
---
name: camera-assignment
description: Implement and verify assignment of Heimdall cameras to online Agents using persisted assignment history and actual Agent capabilities.
---
# Heimdall camera assignment
Read `AGENTS.md`, the camera/Agent assignment sections of `todo.md`, and `skills/heimdall-dotnet/SKILL.md`. For persistence changes, also follow `skills/ef-core-persistence/SKILL.md`.
- Keep assignment scoped to the camera's site and online Agents. Persist assignment/release history and update `Camera.AgentId` in the same EF Core unit of work.
- Assignment strategy must use evidence actually supplied by the relevant entity. Do not infer Agent inference hardware from camera-side protocol flags such as PTZ or camera-native motion detection.
- `GpuPriority` prefers Agents reporting `HasGpu`; if none are GPU-capable, it falls back to all online Agents. Workload balancing remains deterministic within the eligible candidates.
- Camera discovery currently does not populate `Camera.HasMotionDetection`; treat that legacy field as unknown/false and do not use it for Agent placement until a camera capability probe supplies verified data.
- Add PostgreSQL relational tests for strategy selection, failover, and assignment history. Do not use EF InMemory to verify concurrency or transaction semantics.
- For every behavior change, build a uniquely tagged disposable Docker Compose acceptance stack from the changed source, exercise the changed assignment through the API or service boundary against PostgreSQL, and use generated credentials, ports, volumes, and project name. Install an EXIT trap before build/start; tear down only that project, verify zero project containers/volumes/networks, remove each locally built image tag and verify it absent. Preserve shared base images and test exit status. Follow `skills/compose-disposable-recipe/SKILL.md`.
Current validated behavior: `GpuPriority` selects a GPU Agent for a camera even when camera motion capability is false; PostgreSQL test evidence is recorded in `todo.md`.
+53
View File
@@ -0,0 +1,53 @@
---
name: camera-toggle-acceptance
description: Validate that Central camera enable/disable changes stop and resume the real Agent FFmpeg capture process and persist across Agent restarts.
---
# Camera enable/disable lifecycle
Read `AGENTS.md`, the Toggle caméra #59/#199 entry in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing this flow.
## Implementation path
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central.
- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest.
- `GetEffectiveAgentConfigQuery` emits `camera.<id>.enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`.
- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera.
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
## Local verification
Run the focused Agent lifecycle suites:
```bash
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --filter 'FullyQualifiedName~CameraStreamServiceTests|FullyQualifiedName~SnapshotPipelineServiceTests' --no-restore
```
These tests cover session idempotence, process termination, and synchronization without claiming a full Central/Agent workflow.
## Central + Agent disposable acceptance
- Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images.
- Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials.
- Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent.
- Toggle ON and confirm an Agent `ffmpeg` pull process exists against the synthetic path. Toggle OFF and verify the API says Disabled, Agent reports no assigned stream via its active process count and the FFmpeg process disappears in under 2 seconds. Toggle ON and verify the process returns within 10 seconds.
- Restart the Agent while ON; verify it reuses its single existing identity and restarts capture within 10 seconds. Then toggle OFF, restart again, and verify the camera remains Disabled and no capture process returns.
- Use `docker top` only to count FFmpeg processes; never print its command lines because they contain the RTSP URL. Record elapsed durations and sanitized HTTP statuses only.
- Install an EXIT cleanup trap before the first build/start. Teardown only the named Compose project, verify zero containers/volumes/networks, remove each exact project-unique Central/Agent image tag and verify absent, then delete the temporary environment and scripts. Keep the original test status and fail if cleanup verification fails.
This acceptance proves the source-built Central/Agent software lifecycle with a synthetic RTSP stream. It does not validate hardware codecs, physical cameras, LAN multicast, or deployed-host timing.
## Observed simulator pitfalls
- Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines.
- Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result.
- On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above.
- Current disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but have not yet proved toggle timing or restart persistence. Treat #59/#199 as open until a corrected process measurement completes the whole cycle.
## Latest source-built run
The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding self-counting by the measurement shell. It confirmed the Disabled baseline at zero processes and progressed through ON, OFF, ON, then Agent restart while ON with capture restored. The next OFF returned Central state Disabled and effective Agent config `enabled=false`, with zero FFmpeg processes, but the latest config digest was not acknowledged inside the two-second OFF bound. Therefore the full OFF/ON/restart acceptance is still incomplete; do not mark #59/#199 complete. Investigate whether Agent ACK version is stale or the API config digest changes after toggle, while keeping the OFF process release measurement distinct from ACK convergence.
## Sixth source-built run
The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold.
+8 -3
View File
@@ -24,11 +24,12 @@ Use this skill when changing the Linux or Windows Central installer, its generat
- Use the maintained `nickfedor/watchtower` image at an explicit version, `--label-enable`, a 24-hour interval, and `--cleanup`. Cleanup removes superseded images after an update; it must never remove Docker volumes or database files.
- Apply `pull_policy: always` to published Docker images in deployment Compose files so a manual `docker compose up` checks the registry. Leave local development-only images alone and keep the updater itself version-pinned.
- The Docker socket mount grants Watchtower broad control of the host. Document this risk and the lack of staged rollout/rollback; do not describe automatic updates as a production-safe rollback system.
- For each published Ubuntu-based Central, CPU Agent, or CUDA Agent runtime image, update the package index, apply the package security updates required by current Trivy findings, install runtime packages, and clear apt lists in one layer. Keep a broader OS upgrade only where that image already establishes the policy (the CUDA image); verify every final image with the pinned Trivy scanner at HIGH/CRITICAL severity. A passing application build does not clear OS package advisories.
## Runtime image package security
- The server and CPU Agent runtime images inherit Ubuntu 24.04 from the pinned ASP.NET image. When Trivy identifies a fixed Ubuntu package in the shared base, remediate both Dockerfiles and enforce the minimum patched version at build time. The NVIDIA Agent runtime already runs an OS package upgrade during build.
- Run Central + PostgreSQL from source in a disposable Compose project, verify health and native Agent asset URLs, then scan the built Central and CPU Agent images with the same pinned Trivy scanner and HIGH/CRITICAL policy used by CI. Require no findings and perform exact-tag cleanup. See `skills/container-image-security/SKILL.md`.
- The server and CPU Agent runtime images inherit Ubuntu 24.04 from the pinned ASP.NET image. When Trivy identifies a fixed Ubuntu package in the shared base, remediate both Dockerfiles and enforce the minimum patched version at build time. For `CVE-2026-109518`, explicitly upgrade `apt` and `libapt-pkg6.0t64` to at least Ubuntu `2.8.4ubuntu0.1` before runtime packages. The NVIDIA Agent runtime keeps its existing full OS upgrade and asserts the patched APT version too.
- Run Central + PostgreSQL from source in a disposable Compose project, verify health and native Agent asset URLs, then scan Central, CPU Agent, and any changed CUDA image with the same pinned Trivy scanner and HIGH/CRITICAL policy used by CI. Require no findings and perform exact-tag cleanup. See `skills/container-image-security/SKILL.md`.
## Re-running the installer
@@ -40,4 +41,8 @@ Use this skill when changing the Linux or Windows Central installer, its generat
## Acceptance
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and scoped teardown. Never connect the recipe to a deployed Docker daemon or production data.
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
When a runtime Dockerfile changes for OS security updates, source-build and health-check the corresponding Central/Agent image, then scan its saved image archive with the pinned Trivy version and the same `HIGH,CRITICAL` severities used by CI. Record the finding IDs and fixed package versions; do not hide a nonzero scan behind application acceptance.
If acceptance builds a local Central/helper image, record its project-unique tag before build and remove/verify that exact tag in the same cleanup trap, including on failure. Do not remove registry/base images or use `--rmi all` or broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup.
+62 -6
View File
@@ -12,15 +12,71 @@ Use this skill for every Heimdall behavior, deployment, or operational change. R
- Build from the current source with a unique Compose project name. Do not test against the production hostname, database, image volumes, secrets, or credentials.
- Put generated `.env` and secret files under a temporary directory outside the repository. Use synthetic test identities and cryptographically random local passwords.
- Use an unused loopback host port and Compose-managed volumes whose names include the unique project name. Do not join production or shared networks.
- Never use broad Docker cleanup such as `docker system prune`. Remove only the test project with `docker compose -p <unique-name> down --volumes --remove-orphans`.
- After cleanup, check that the test project has no containers or volumes. Remove its temporary files and keep logs free of credentials.
- Give each locally built acceptance image a project-unique tag, for example `heimdall:<project>-acceptance`; do not build under `latest`, `local`, or a tag that existed before the recipe. Use a temporary Compose override to set the unique image tag while preserving the source build context. Record all generated tags before starting.
- Never use broad Docker cleanup such as `docker system prune`, `docker image prune`, or `docker rmi $(docker images -q)`. Remove only the test project with `docker compose -p <unique-name> down --volumes --remove-orphans`.
- After teardown, check that the project has no containers, volumes, or networks. For every locally built image tag, run `docker image rm <exact-recipe-tag>` if it exists, then verify `docker image inspect <exact-recipe-tag>` fails. Remove the temporary Compose override/env/source files. Do not remove shared upstream base images (for example PostgreSQL, .NET SDK, or MediaMTX) or images owned by another recipe/project.
- Put teardown and exact-tag image removal in the same cleanup trap so both success and failure paths clean up. Do not reuse another acceptance recipe's locally built image: build a uniquely tagged image for this recipe and remove it in this recipe's cleanup path.
- A recipe is not complete until every local application image tag created by that recipe has been removed and verified absent. `docker compose down` does not remove images. Apply this even when the behavioral assertion fails; keep generated upstream/base images and unrelated project images untouched.
- These requirements apply to every Docker-based acceptance recipe, including SDK-only test containers, third-party mocks, one-shot helpers, and failure/partial-build paths. Such recipes must explicitly state whether they build any local images. If they build none, leave upstream images intact and still verify cleanup of project containers, volumes, and networks. If they build any local image (Heimdall or helper), record its unique tag before build and remove/verify it absent in the same `EXIT` cleanup trap, even if Compose startup or the build fails.
- Cleanup must preserve the recipe's original exit status, attempt teardown and removal of every recorded tag independently, and report cleanup failures rather than silently declaring acceptance complete. Never use `--rmi all` because it can remove shared or unrelated images.
- **Mandatory local image cleanup:** before the first build, enumerate and record every recipe-owned image tag that may be created (application, SDK/test harness, mock, one-shot helper). Use a unique tag for each locally built image. The EXIT trap must remove each exact recorded tag after project teardown and verify it is absent, regardless of whether build, startup, assertions, or teardown failed. Do not count an image as shared merely because its Dockerfile uses a shared base; only remove recipe-built tags, and retain upstream images. If no image is built locally, explicitly say so and verify the project resources are gone. Never leave recipe-created local images behind.
### Required cleanup trap pattern
Use one `EXIT` trap installed before the first build or Compose start. Record
exact local tags in an array before building; leave the array empty when the
recipe builds no images. Cleanup actions must be independent so a failed
Compose teardown cannot skip image and temporary-file cleanup. Preserve the
original status and return a failure if any cleanup verification fails:
```bash
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
down --volumes --remove-orphans || cleanup_failed=1
# Query all three resource kinds by Compose project label; do not infer
# absence from `compose down`'s exit code alone.
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
rm -rf -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable recipe cleanup failed for project %s\\n' "$project" >&2
status=1
fi
exit "$status"
}
trap cleanup EXIT
```
The label queries must succeed and return empty results for containers,
volumes, and networks. Do not include upstream images in `local_image_tags`. Recipe records must state
the project name, whether local images were built, exact tags and absence
checks (or explicitly “none”), plus project-resource cleanup results. A Docker
recipe that reports teardown without the image-tag check is incomplete.
## Acceptance workflow
1. Inspect the Compose file and interpolation requirements before starting it. Generate a temporary environment file with unique database/JWT secrets and a distinct loopback port.
2. Start the minimal Central + PostgreSQL stack from source with `docker compose -p <unique-name> --env-file <temp-env> -f docker/docker-compose.yml up -d --build`.
3. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path.
4. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files.
5. Tear down the named project and its volumes in a cleanup path. Verify removal and delete temporary files.
2. Generate a temporary Compose image override. For example:
```yaml
services:
heimdall:
image: heimdall:${ACCEPTANCE_PROJECT}-central
```
Put `ACCEPTANCE_PROJECT=<unique-name>` in the temporary env file and include both Compose files in every command. This overrides only the image tag; the checked-in source build context is retained. Use similarly unique tags for any Agent or helper image built from this checkout.
3. Start the minimal Central + PostgreSQL stack from source with `docker compose -p <unique-name> --env-file <temp-env> -f docker/docker-compose.yml -f <temp-image-override> up -d --build`.
4. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path.
5. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files.
6. Install an `EXIT` trap before the first build/start operation. The trap must preserve the test command's exit status, run `docker compose ... down --volumes --remove-orphans`, verify no project containers/volumes/networks remain, remove every recorded project-unique locally built image tag and verify each is absent, then delete temporary environment, secrets, override, and copied-source files. Attempt each cleanup action even if an earlier cleanup action fails; surface any cleanup failure. Retain shared upstream/base images. Do not use Compose `--rmi all` or broad prune commands.
If Docker access is unavailable, request the required local permission or explain the blocker; do not substitute a production deployment or claim the recipe passed.
+2 -2
View File
@@ -7,8 +7,8 @@ description: Diagnose and repair vulnerabilities in Heimdall Central and Agent c
Read `AGENTS.md`, the image-scan result in `todo.md`, `skills/compose-disposable-recipe/SKILL.md`, and `skills/central-auto-updates/SKILL.md` before changing runtime images or their publication path.
Heimdall server, CPU Agent, and NVIDIA Agent images use Ubuntu 24.04 runtime layers. When Trivy reports a fixed Ubuntu package, update only the affected package unless the project already establishes a broader OS-upgrade policy. For `CVE-2026-109518`, upgrade `apt` and `libapt-pkg6.0t64` after `apt-get update` and assert the `apt` version is at least `2.8.4ubuntu0.1` before installing runtime tools. Keep Trivy severity and exit thresholds unchanged. Apply the remediation to each affected runtime image; the NVIDIA image already upgrades its base OS packages.
Heimdall server, CPU Agent, and NVIDIA Agent images use Ubuntu 24.04 runtime layers. When Trivy reports a fixed Ubuntu package, update the affected packages unless the image already establishes a broader OS-upgrade policy. For `CVE-2026-109518`, all three runtime Dockerfiles explicitly upgrade `apt` and `libapt-pkg6.0t64` after `apt-get update` and assert that `apt` is at least `2.8.4ubuntu0.1` before installing runtime tools. The NVIDIA image retains its existing full OS upgrade as well. Keep Trivy severity and exit thresholds unchanged.
For acceptance, build Central and CPU Agent from the changed checkout under unique Compose image tags with synthetic credentials, loopback ports, project-scoped volumes/network, and an EXIT cleanup trap. Verify Central health and the native Agent installer and supervisor URLs. Scan each built image with the same pinned Trivy version, vulnerability DB repositories, and HIGH/CRITICAL exit policy used by `scripts/ci/security.sh`. A passing acceptance requires zero HIGH/CRITICAL findings, successful teardown, no project containers/volumes/networks, and removal plus absence checks for every exact local tag. Retain upstream base and scanner images.
For acceptance, build Central, CPU Agent, and NVIDIA Agent from the changed checkout under unique Compose image tags with synthetic credentials, loopback ports, project-scoped volumes/network, and an EXIT cleanup trap. Verify Central health and the native Agent installer and supervisor URLs; build the NVIDIA image without claiming GPU runtime validation. Scan all three built images with the same pinned Trivy version, vulnerability DB repositories, and HIGH/CRITICAL exit policy used by `scripts/ci/security.sh`. A passing acceptance requires zero HIGH/CRITICAL findings, successful teardown, no project containers/volumes/networks, and removal plus absence checks for every exact local tag. Retain upstream base and scanner images.
The CI image scan is a merge gate. Do not publish or merge around a failed scan; inspect the report and correct the affected package, then rerun the complete workflow. Keep `todo.md` evidence split between disposable local acceptance and the actual CI publication run.
@@ -0,0 +1,32 @@
---
name: deployment-guide-acceptance
description: Keep Heimdall's Docker installation and backup guides aligned with the actual Compose assets and validate source-built installation flows in a disposable project.
---
# Heimdall deployment guide acceptance
Read `AGENTS.md`, `todo.md`, `docs/docker-compose.md`, and the relevant Compose and focused skills before changing deployment instructions.
## Project-specific documentation checks
- Central production is PostgreSQL plus Heimdall Web. The development Compose builds Central from source; the interactive Linux/Windows installers create deployment files without cloning the repository.
- Production Agent Compose is generated in Central for the selected site and pins the image digest. The repository's Agent Compose files are development or optional hardware overlays only.
- Recording quota is configured through `RECORDING_STORAGE_QUOTA_MAX_BYTES`; absent an override, Central uses 1 TiB.
- The Central image installs Tesseract plus English language data. `PLATE_OCR_ENABLED` is mapped to `PlateOcr__Enabled` by the development and production Compose files and both Linux/Windows installer templates. New installs default it to false; upgrades preserve an existing value and add false if absent. If documented, explain that OCR is an operator-uploaded crop processed locally, not automatic video detection or face recognition; mention temporary crop deletion and that OCR candidates do not establish identity.
- The scheduled backup service installs AWS CLI, Bash, and GNU coreutils. The backup scripts select AWS CLI in this image and use S3-compatible configuration; do not instruct operators to download the retired MinIO `mc` URL.
- Optional Compose projects depend on the documented external core network and, where stated, the Central data volume. Do not describe an optional service as part of required startup.
## Disposable installation acceptance
1. Follow the local development installation commands in `docs/docker-compose.md` from the changed checkout. Create a unique project, isolated bridge, generated database/JWT credentials and unused loopback ports under a temporary directory. Do not copy production `.env`, use the default credentials unchanged, or use deployed volumes/networks.
2. Run Compose config validation, build Central from source, start PostgreSQL and Central, then verify PostgreSQL health, Central `/healthz`, bootstrap status, and the documented opt-in default for OCR.
3. When documentation covers OCR enablement, set `PLATE_OCR_ENABLED=true` in the generated temporary env and verify the option reaches the container, then exercise the synthetic crop path. Also verify false by default. Do not infer real camera accuracy.
4. Install an EXIT cleanup trap before build/start. Tear down only the named project with `down --volumes --remove-orphans`; verify zero project containers, volumes, and networks. Remove temporary environment and secret files even if build or assertions fail.
5. Record a unique tag for each locally built Central/helper image before build. After teardown, remove and verify absence of each exact tag. Keep shared upstream runtime/database images, preserve test exit status, report cleanup errors, and never use `--rmi all` or prune images broadly.
6. Keep Windows installer execution, production recovery, external S3 services, and real hardware acceptance open unless independently run on those targets.
When the Docker daemon is reserved by another acceptance, perform static source/config review and record the Compose run as pending. Never launch an overlapping project to satisfy this recipe.
## Latest local attempt
On 5 November 2026, Compose configuration and installer-source assertions passed, but the source build acceptance did not complete: BuildKit's docker-buildx client remained blocked for over eight minutes after its compiler child disappeared, with no project containers created. The command was interrupted; its cleanup trap confirmed zero project containers, volumes, and networks and removed the generated env. A follow-up Compose project hmd-ocr-env-safe-1793874420 reused the previously source-built Central OCR image (the current checkout rebuild was still blocked) to exercise the changed Compose wiring: default PlateOcr__Enabled=false and explicit true after recreate both reported healthy. Sentry__Dsn was explicitly empty. Cleanup verified zero containers, volumes, and networks. These are partial recipe results: the reused application image was not a uniquely built image for this recipe, and no exact-tag removal/absence check is recorded. Repeat the source build and probe with a fresh project tag before treating deployment-guide Compose acceptance as complete. An earlier attempt without the Sentry override emitted synthetic EF log events to the configured GlitchTip; no real credentials/data were used. The Compose environment mapping is verified; rebuilding this exact checkout and Windows installer execution remain unverified. pwsh was not installed, so the Windows installer was reviewed statically only.
+1
View File
@@ -13,6 +13,7 @@ Use this skill whenever changing how application or Agent data is read or writte
- Verify PostgreSQL translation, transaction boundaries, concurrency and deletion semantics against PostgreSQL integration tests when those behaviors matter. Do not use EF InMemory as proof of relational behavior.
- Do not issue CRUD through ADO.NET or hand-written SQL. Raw SQL through EF is an exception for database-specific capabilities that LINQ cannot express or for measured performance needs. Keep it parameterized, add an adjacent `EF Core exception:` comment with the reason, and add a test for its behavior.
- Migrations, test database setup, PostgreSQL maintenance/partition DDL, and locks with no portable EF equivalent are valid exceptions. Keep provider-specific code in Infrastructure or a dedicated adapter; do not spread it into use cases.
- When adding an approved raw EF operation, add its exact source path and a short capability rationale to `scripts/ci/check-efcore-usage.py`'s `EF_CORE_EXCEPTIONS` allowlist, keep an adjacent `EF Core exception:` comment, and cover the behavior with a relational test. The scanner intentionally ignores comments when locating a call; a comment alone does not allowlist a new production source.
- Never enable sensitive-data logging in production. Do not log connection strings or persisted secret values.
Before editing, inspect this repository's `AGENTS.md`, `todo.md`, model configuration, latest migration, and callers. After editing, run the relevant suite and CI persistence policy check, then update the corresponding TODO item with evidence and remaining deployment checks.
+1
View File
@@ -13,5 +13,6 @@ Use this skill when changing account bootstrap, signup, login routing, user crea
- Existing installations with users skip setup and keep their accounts. The bootstrap flow must not overwrite or replace existing users.
- Update FR/EN resources, route behavior, API client behavior, and tests together. Remove public registration links and ensure direct calls to the old registration route are rejected after setup.
- For every implementation change, follow `compose-disposable-recipe` and validate both an empty database (setup and first admin) and an initialized database (setup closed, anonymous registration rejected, admin account creation available).
- Record a unique tag for every source-built Central image and install an EXIT cleanup trap before build/start. Remove the project and verify zero containers/volumes/networks, then remove and verify absence of each exact local tag even after failure; retain shared PostgreSQL/.NET base images and report cleanup errors.
Never use credentials supplied for a real deployment in tests. Use generated credentials in the disposable Compose environment and sanitize logs.
+33
View File
@@ -0,0 +1,33 @@
---
name: heimdall-gpu-inference
description: Build and verify Agent ONNX Runtime provider selection, CPU fallback, and GPU package variants in Heimdall.
---
# Heimdall Agent ONNX inference
Use this skill when changing ONNX Runtime packages, execution provider configuration, Agent inference startup, or GPU deployment support.
## Project-specific workflow
- The default Agent build and published `docker/Dockerfile.agent` remain CPU-only. Do not add NVIDIA runtime/device requirements to the default Agent Compose files. CUDA support is opt-in through `docker/Dockerfile.agent.gpu`, `docker/docker-compose.agent.dev.gpu-nvidia.yml`, and a separately signed release image manifest.
- Configure provider choice through `Agent:InferenceExecutionProvider` (environment variable `Agent__InferenceExecutionProvider`). `CPU` is the default. `CUDA` is optional and valid only in a runtime containing the official ONNX Runtime GPU package plus compatible CUDA/cuDNN native libraries and host driver access.
- Keep the CPU and GPU NuGet dependency graphs in their separate lock files. Restore each variant explicitly and in locked mode after changing dependencies:
```sh
dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode
dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRuntime=GPU --locked-mode
```
- The Agent checks for detected NVIDIA hardware before enumerating ONNX providers or creating a session; some ONNX Runtime GPU builds can fault during native provider discovery when no driver device is attached, before managed fallback handling is possible. It reports the provider configured on the resulting session. If CUDA is requested but unavailable or session construction fails, log the reason without sensitive payloads and construct a CPU session. Keep provider selection isolated behind `OnnxExecutionProviderSelection` so the fallback can be tested without hardware.
- Add tests for CPU-only selection, successful CUDA selection, missing CUDA provider, and CUDA session initialization failure. Also exercise the repository YOLO fixture with the CPU provider so package changes preserve real inference.
- Test the default Agent test suite and the GPU package variant where the local machine permits. GPU package tests may need a larger non-`/tmp` output directory because ONNX GPU and image-processing NuGet packages ship native assets for multiple operating systems. The real-model test searches upward from the test output for `models/yolov8n.onnx`; keep output under the repository or place the fixture alongside the test output.
- Any runtime/image or Compose behavior change requires the disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md`. Keep hardware-only validation open unless NVIDIA, AMD, or Intel hardware is actually exercised. A successful CPU fallback test does not prove GPU execution.
- Record unique tags for the locally built CUDA Agent and any Central/helper fixture image before building. Install an EXIT trap before the build/start; after stopping the project, remove each exact local tag independently and verify it is absent, including after failed builds/assertions. Preserve the test exit status and report cleanup errors. Retain shared CUDA/runtime base layers; never use `--rmi all` or `docker image prune`.
- The current pinned GPU image pairs ONNX Runtime 1.22 with NVIDIA CUDA 12.8.1/cuDNN 9.8.0.87 on amd64. The CUDA runtime base is pinned by the architecture-specific manifest digest in `docker/Dockerfile.agent.gpu`; the dev overlay targets `linux/amd64` and the Dockerfile uses that target rather than a constant `FROM --platform` override. Refresh the digest only after checking the ONNX Runtime compatibility table and obtaining the matching NVIDIA registry digest.
## Current limitation
The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. On 5 November 2026, the post-fix GPU image built from this source with locked GPU restore. Rendered Compose confirmed CPU has no NVIDIA device requirement and the opt-in overlay selects the GPU image. A local disposable runtime check launched the GPU image without NVIDIA devices on an isolated network and tmpfs state: logs confirmed no GPU detection, fallback to `CPUExecutionProvider`, and YOLO model initialization; a synthetic HTTP Central mock accepted registration and heartbeat (200/204), and `/healthz` returned 200. The repository `RealOnnx_CpuModel_ProcessesFullHdImage` test passed 1/1 with `HeimdallOnnxRuntime=GPU`. The mock did not implement configuration/jobs, so no camera frame traversed the Agent/Central loop; a synthetic frame and persisted inference observation remain open. The exact acceptance image tag and container were removed and verified absent; tmpfs, mock listener, and temporary state were gone. The earlier disposable Central/PostgreSQL bootstrap also passed. Physical CUDA execution still requires NVIDIA hardware.
Additional full-loop acceptance attempt, 5 November 2026: disposable Compose project `hmgpu-loop-929b670e` rendered with CUDA package selection, no NVIDIA reservation, and empty Sentry DSN. Central and the Agent GPU image were built from this checkout under `heimdall:hmgpu-loop-929b670e-central` and `heimdall-agent:hmgpu-loop-929b670e-gpu` (GPU image inspected at 3.56 GB). The Compose/Buildx client remained waiting after image export and before any service/container was created, so no Central bootstrap, Agent health, camera configuration, job, frame processing, or database observation was exercised. After stopping only that build handle, cleanup verified 0 containers/0 volumes/0 networks, both exact image tags absent, and the temporary directory absent. `docker buildx ls` and `docker ps` responded afterward; this does not establish successful runtime acceptance. Keep the frame-through-job-loop evidence open. An earlier duplicate-target attempt (`hmgpu-loop-e9377c0b`) was also cleaned with 0/0/0 and both exact image tags absent.
+38
View File
@@ -0,0 +1,38 @@
---
name: group-access
description: Implement and accept Heimdall group membership and camera grants through the Admin UI and protected API.
---
# Group membership and camera access
The Admin group editor is `src/Heimdall.Web/Components/Pages/Admin/GroupsPage.razor`.
Its API adapter is `HeimdallApiClient`; route templates must match
`GroupsController`. Member listing is `GET /api/groups/{groupId}/users`, add is
`POST /api/groups/{groupId}/users/{userId}`, and removal is
`DELETE /api/groups/{groupId}/users/{userId}`. Camera grants use the sibling
`/cameras` endpoints. Keep member selection name/email based in the UI; do not
ask administrators to copy opaque user IDs.
Authorization is additive: effective camera access is the union of active
site-wide, direct, legacy, and live group grants, subject to role permissions
and deleted-resource checks. Removing one grant must preserve another valid
grant. Soft-deleted groups must stop granting access immediately.
## Acceptance
1. Run focused Web tests for `GroupsPageTests`, `HeimdallApiClientTests`, and
`ResourceAccessTests`. Assert API HTTP method/path, UI member identity and
camera/site labels, and add/remove behavior.
2. Build the source in a uniquely named disposable Compose project with
generated PostgreSQL/JWT credentials, loopback port, named volumes, and a
project-specific network. Bootstrap the first Admin through the setup API;
create a group, add a member using the production route, read the member
list, remove the member, and verify the empty list. Use only synthetic data.
3. Install an EXIT cleanup trap before build/start. Tear down that exact project
with volumes and orphans, verify there are no project containers, volumes,
or networks, remove exact local image tags and verify they are absent, and
delete generated secret files even if an assertion fails.
4. Record each project-unique local image tag before build. Retain shared
upstream PostgreSQL/.NET runtime images; never use `--rmi all` or prune.
5. Update `todo.md` with the exact evidence and keep physical/deployment-only
claims separate from local acceptance.
+27
View File
@@ -0,0 +1,27 @@
---
name: heartbeat-failover
description: Validate that stale Agents are marked offline and assigned cameras move safely to online peers.
---
# Heimdall heartbeat and Agent failover
Read `AGENTS.md`, the Heartbeat/failover item in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing this path.
## Behavior contract
- Use the configured global heartbeat interval or per-Agent override, bounded to 5–300 seconds. A stale Agent is not eligible for new work.
- The failover sweep owns the stale-to-Offline transition and camera reassignment. Do not add a competing heartbeat monitor that races this transition.
- Preserve camera assignment history: close the old row and create a new active row for an online Agent in the same site. If there is no replacement, clear the active assignment and let periodic reconciliation retry when an Agent recovers.
- Use short-lived EF Core contexts and test status, camera ownership, and assignment history against PostgreSQL.
## Required validation
1. Run the PostgreSQL tests in `HeartbeatMonitorJobTests`, `AgentFailoverJobTests`, and `CameraAssignmentServiceTests`.
2. Run the integration scenario with two registered Agents: heartbeat both, assign a camera to the source, age only the source heartbeat past the maximum accepted timeout, execute the real `AgentFailoverJob` and `CameraAssignmentService`, then verify the source is Offline, the online peer owns the camera, and both assignment records retain the correct released/active state.
3. Before any build/start, install an EXIT cleanup trap. Build Central from the changed source in a unique disposable Compose project. Generate database/JWT credentials, use unique loopback ports, network, volumes and image tag, empty Sentry DSN, bootstrap a synthetic admin/site and two synthetic Agents, and assign a synthetic camera. Age the source heartbeat only in the disposable PostgreSQL fixture and let the real Hangfire recurring failover job run; verify the active assignment and historical rows through API/PostgreSQL.
4. The trap tears down that project with volumes/orphans, verifies zero project containers, volumes and networks, then removes and verifies absence of the exact source-built Central image tag even on failure. Keep upstream Postgres/.NET base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or broad image pruning.
5. Mark physical Agent loss, network partitions and multi-host timing as unverified unless exercised against deployed Agents.
## Current local evidence
5 November 2026: new relational integration scenario passed 1/1. Disposable source-built project `hmd-failover-1793882220-a9bc9c` registered two Agents, assigned the synthetic camera to the first, aged its heartbeat to 900 seconds, and observed the real Hangfire failover mark it Offline and move the camera to the still-online peer. PostgreSQL confirmed the previous assignment was released and the replacement assignment active. Teardown left zero containers/volumes/networks and removed/verified absence of the exact Central image tag. This proves the local scheduled path and relational state, not a real network partition or deployed multi-host timing.
+1
View File
@@ -25,5 +25,6 @@ Read `AGENTS.md`, the `AUTH-BOOTSTRAP` entry in `todo.md`, and the Identity wiri
- Keep PostgreSQL-specific transaction and concurrency guarantees in Infrastructure. Use relational integration tests for bootstrap races, recovery-code redemption, session revocation, and migration compatibility.
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update `todo.md`, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands.
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
+31
View File
@@ -0,0 +1,31 @@
---
name: mdns-camera-discovery
description: Implement and validate HomeKit camera discovery from DNS-SD mDNS announcements in Heimdall Agent.
---
# Heimdall mDNS camera discovery
Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing discovery behavior.
## Ownership and data flow
- `Heimdall.Mdns/MdnsClient` owns UDP multicast and DNS-SD PTR/SRV/TXT/A parsing. Keep network operations cancellable and dispose sockets per operation.
- `HomeKitMdnsProbe` maps only categories 17 (camera) and 18 (doorbell) into Agent discovery records.
- `NetworkCameraScanner` is the Agent-side source of LAN probes. Preserve HomeKit metadata when its TCP scan has already found the same IP. Central persists and returns metadata; it must not probe the camera LAN.
- Resolve an accessory address from an A record attached to the instance or from the exact SRV target hostname. Never use another advertisement's arbitrary A record as a fallback.
- At Central confirmation, persist only capabilities proven by the discovery result and selected stream. Derive RTSP port from the selected RTSP URL (554 default for RTSP, 322 for RTSPS when omitted) or a probed RTSP port, HTTP port from the HTTP probe, and ONVIF service port from the device-service URL. Do not confuse UDP WS-Discovery port 3702 with the camera's HTTP ONVIF service port. Do not claim PTZ, audio, snapshot, or native motion support unless the probe actually verifies it.
## Synthetic acceptance
- Build synthetic DNS response packets with PTR `_hap._tcp.local` → instance, SRV instance → hostname/port, TXT `ci`, `sf`, `id`, `md`, and A hostname → address. Include an unrelated A record to verify strict SRV association.
- Verify camera and doorbell categories are kept, unrelated categories are filtered, `sf=0` maps to paired, and missing SRV-target A does not invent an address.
- Verify `HomeKitMdnsProbe` maps address/name/id/model/category/pairing/port into its Agent contract, and cancellation yields an empty result.
- Run the focused Agent tests and the full Agent test project after changes.
- The synthetic packet path validates DNS assembly and mapping only. A disposable Compose test can exercise the Agent source in isolation; only a real camera on a representative LAN validates multicast routing and hardware behavior. Keep that item open until such a run exists.
- The PostgreSQL integration scenario `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` exercises confirmation from discovery metadata through persisted camera fields, including an ONVIF service port distinct from UDP 3702. Preserve that relational coverage when changing confirmation mapping.
## Disposable Compose
Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN.
This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`.
@@ -0,0 +1,27 @@
---
name: notification-delivery-acceptance
description: Validate Heimdall's global SMTP and ntfy settings, test actions, and notification delivery without external providers.
---
# Heimdall notification delivery acceptance
Read `AGENTS.md`, PIPE-10/FEAT-05 in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing notification delivery.
## Configuration contract
- Settings created through the UI are stored with lowercase keys. `AppSettingReader` must normalize requested keys before its exact EF query; callers use mixed-case literals for legacy reasons.
- SMTP reads `email.smtphost`, `email.smtpport`, `email.username`, `email.password`, `email.fromaddress`, `email.fromname`, and `email.usessl`.
- ntfy reads `ntfy.baseurl` and `ntfy.token`; test messages use the same configured service and should fail visibly when it rejects or cannot be reached.
- Keep SMTP/ntfy secrets out of responses and logs. Outbox delivery remains at-least-once; a provider acceptance followed by a lost DB acknowledgement can duplicate a notification.
## Required simulated validation
1. Run `AppSettingReaderTests`, notification service/outbox tests, and the PostgreSQL outbox integration tests.
2. Use a disposable Compose project from the changed Central source with PostgreSQL, an isolated ntfy service and Mailpit. Generate database/JWT credentials, use an internal project-only network and no published ports, explicitly empty the Sentry DSN, and keep real SMTP/ntfy credentials out of the environment.
3. Bootstrap a synthetic Admin and save SMTP/ntfy settings through `/api/settings`, matching UI key names. Call `/api/settings/ntfy/test` and `/api/settings/email/test`; verify ntfy returns success and Mailpit stores the synthetic recipient message.
4. Install an EXIT cleanup trap before build/start. Tear down only the project with volumes/orphans, verify zero project containers/volumes/networks, then remove/verify absence of the exact source-built Central image tag even on failure. Retain shared ntfy/Mailpit/PostgreSQL/Python base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or broad prune commands.
5. Report local service acceptance separately from delivery to a real SMTP relay, hosted ntfy server, or user device.
## Current local evidence
On 5 November 2026, `AppSettingReaderTests` passed 9/9. The first disposable provider run showed ntfy success but SMTP failure: the UI stored lowercase keys while `EmailService` queried mixed-case values. `AppSettingReader.GetAsync` now lowercases trimmed keys; tests cover the SMTP and AI URL callers. The source-built isolated project `hmd-notify-mock-1793882996-2efa06` then passed both Admin settings/API test routes, ntfy HTTP 2xx, and SMTP test delivery captured in Mailpit. No ports were published and the bridge was internal. Cleanup verified zero containers/volumes/networks and removed/verified absence of the exact Central image tag. Real external delivery remains unvalidated.
+24
View File
@@ -0,0 +1,24 @@
---
name: heimdall-pwa
description: Implement and accept Heimdall's root-hosted, online-first Blazor PWA without persisting private application data.
---
# Heimdall PWA
The supported PWA deployment is at the web origin root (`/`). The Blazor app uses Interactive Server, so camera, event, account and administration screens require a live server circuit. Offline mode is an informational page only; never add authenticated HTML, API results, media, credentials or SignalR traffic to CacheStorage or replay mutations offline.
## Implementation map
- `src/Heimdall.Web/Components/App.razor` links the web manifest and raster/Apple icons and loads `js/pwa-register.js`.
- `wwwroot/manifest.webmanifest` defines stable root scope, standalone display and PNG/SVG icons.
- `wwwroot/service-worker.js` caches only `/offline.html`, `/manifest.webmanifest` and `/pwa-icon.svg`. It falls back only for failed same-origin GET navigations and excludes API, auth, Blazor, hubs, health, metrics and operational/documentation paths.
- The worker must remain waiting after an update. `pwa-register.js` shows a reload action for a waiting worker; only that action sends `ACTIVATE_UPDATE`, then reloads after `controllerchange`. Do not unconditionally call `skipWaiting()` or `clients.claim()` because this can replace resources during an active form or live session.
- Installation UI is progressive: use `beforeinstallprompt` where the browser provides it; otherwise explain the platform's browser-menu installation steps. Browsers without PWA installation support must keep the site usable.
## Acceptance
1. Run `tests/Heimdall.E2E.Tests` with its disposable PostgreSQL fixture and Chromium. Check unauthenticated manifest and icon access, exact public-shell contents, offline navigation fallback, and absence of cached private content.
2. Build the changed source through the disposable Central + PostgreSQL Compose recipe in `skills/compose-disposable-recipe/SKILL.md`; probe `/healthz`, `/manifest.webmanifest`, `/service-worker.js` and the offline page. Use unique project/ports/credentials/volumes and install an EXIT cleanup trap before build/start. Remove the project, verify zero containers/volumes/networks, then remove and verify absence of each exact project-unique local image tag, even after failure; retain shared upstream images and report cleanup errors.
Assign the locally built Central image a project-unique tag; remove and verify that exact tag after teardown, while retaining shared .NET/PostgreSQL bases.
3. Review `docs/pwa.md` and deployment instructions for HTTPS, root hosting, reverse proxy/WebSocket support, update and rollback behavior. Report physical iOS/Android/desktop installation, HTTPS proxy, and mobile sleep/network testing only when run on those real environments.
4. Keep the PWA backlog open for validations that require real browsers/devices or remote push infrastructure. Do not claim Web Push exists without a tested VAPID backend, subscriptions, revocation and permission-aware delivery.
+22
View File
@@ -0,0 +1,22 @@
---
name: release-automation
description: Build, sign, verify, and publish Heimdall tagged releases without exposing signing keys or publishing from pull requests.
---
# Heimdall tagged release workflow
Use this skill for changes to `scripts/ci/package.sh`, `publish.sh`, `release-gitea.py`, release signing, Docker image tags, or the Gitea release job.
## Release invariants
- A release tag must be `vMAJOR.MINOR.PATCH[-prerelease]`, point to a commit on `main`, and pass the complete `verify` job before publication starts.
- `RELEASE_SERVER_URL` must be the expected HTTPS forge origin and must match `BUILD_SERVER_URL`; the publisher rejects paths, query strings, user info, and host/port mismatches.
- Use a dedicated Gitea `RELEASE_TOKEN`, Docker Hub credentials, and a base64 encoded ECDSA P-256 key only in the tagged release job. Never make them available to PR jobs or print them.
- Do not overwrite published image tags owned by another commit or mutate an already published Gitea release. Releases remain drafts until an operator promotes them.
- The release includes deterministic Web and Agent archives, provenance, checksums, the public key, immutable image digests, and a signed Agent update manifest.
## Offline end-to-end acceptance
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. The acceptance script invokes the real `package.sh` and `publish.sh`, but creates disposable ECDSA P-256 credentials and substitutes both publication boundaries: a local TLS Gitea API double records only draft release/assets, and a fake Docker CLI records tags and simulates registry digests. It verifies archive hashes, manifest signature, checksums, asset uploads, and expected image tags/digests. The fake CLI must never call a registry, and the API server must bind only to loopback, suppress request logging, and reject non-synthetic authorization.
This simulation proves local packaging/signing/orchestration only. It does not prove the Actions secrets, runner network, Docker Hub/Gitea behavior, native Agent installation, or rollback. Keep the release item open in `todo.md` until a real tagged run and the relevant host validation have succeeded.
+16
View File
@@ -0,0 +1,16 @@
---
name: renovate-automation
description: Diagnose and maintain Renovate dependency updates through Gitea Actions without exposing bot credentials.
---
# Heimdall Renovate workflow
Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependency-update failures.
- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `GITEA_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files.
- The endpoint must be the HTTPS Gitea API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values.
- HTTP 401/403 means the secret is missing, expired, revoked, or lacks repository access. Configure a bot token with repository read and write access so Renovate can open pull requests. Read preflight success does not prove write access; confirm a successful run that opens or updates a PR.
- Use `node --test scripts/ci/renovate-preflight.test.mjs` to test endpoint validation and sanitized auth failures locally. Do not run Renovate locally with production credentials.
- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Install an EXIT cleanup trap before startup, preserve the test exit status, remove that exact project, and confirm it leaves no containers, volumes, or networks; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored.
- The mock-preflight recipe uses a shared upstream Node image and creates no local images. Retain that base image. If the recipe adds a locally built mock/helper/application image, record its unique tag and remove/verify only that exact tag in the same cleanup trap, including on failure. Do not use `--rmi all` or broad prune commands.
- For operational changes, update the P0 Renovate status in `todo.md` with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence.
+21
View File
@@ -0,0 +1,21 @@
---
name: server-healthchecks
description: Keep Heimdall container health probes aligned with the HTTP methods accepted by its ASP.NET health endpoints.
---
# Heimdall server health checks
Use this workflow when changing `Dockerfile` health checks, Central Compose health checks, or Web health endpoint routing.
- Central and Agent containers probe `/healthz` on port 8080 (the development Agent may bind its host-mapped port). ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy.
- In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD.
- Apply this to both `docker/Dockerfile`/Central Compose and `docker/Dockerfile.agent`/Agent development Compose. Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required.
- For acceptance, build the changed Central or Agent image from source under a project-unique tag in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Install an EXIT cleanup trap before build/start. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy. In cleanup remove only that project with `down --volumes --remove-orphans`, verify no labeled containers/volumes/networks remain, remove and inspect each exact local image tag even on failure, and retain shared base images. Preserve the test exit status and report cleanup failures.
## Metrics scrape acceptance
For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. Remove and verify absence of that recipe's unique server image tag afterward.
On 5 November 2026, project hmd-metrics-scrape-1793874584 reused the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This is a partial Docker recipe result: it did not build a unique image for this scrape, so no exact-tag image removal was performed. Repeat the check with a fresh project-unique source-built tag before treating the Docker acceptance as complete. This local check does not validate a deployed Prometheus server or alert thresholds.
PostgreSQL readiness regression checks were also rerun locally on 5 November 2026: HealthControllerTests passed 5/5 with the disposable Testcontainers database. The Testcontainers reaper and database stopped after the run; unrelated labeled database services were left untouched.
+14
View File
@@ -0,0 +1,14 @@
---
name: site-ntfy-creation
description: Maintain and accept the site-specific ntfy topic through Heimdall site creation.
---
# Site ntfy creation
The site topic is an optional destination used by notification delivery. Creation crosses a JSON DTO, `SitesController`, `CreateSiteCommand`, `CreateSiteHandler`, and `Site`; every layer must carry `NtfyTopic`. Keep the optional DTO parameter last/defaulted to preserve existing clients. The Sites page already sends it in `CreateSiteAsync`.
## Acceptance
1. Extend the PostgreSQL API integration test to POST a unique site name and `ntfyTopic`, then GET that site and assert `SiteResponse.NtfyTopic` equals the submitted topic. This catches JSON binding, controller mapping, and relational persistence together.
2. Run the focused integration test against the repository PostgreSQL fixture.
3. Follow `skills/compose-disposable-recipe/SKILL.md` to run a source-built disposable Compose stack. Bootstrap an isolated admin, create a site with a topic through `POST /api/sites`, read it back, and verify the topic. Remove the exact project and locally built tags and verify no project containers, volumes, or networks remain.
+28
View File
@@ -0,0 +1,28 @@
---
name: video-recording
description: Implement and validate Heimdall Agent video segments, central recording storage, access checks, ranges, and retention.
---
# Heimdall video recording
Recording is opt-in per camera (`RecordingEnabled`, default false). Agent capture is a separate FFmpeg process and only runs while the assigned camera's RTSP stream is already active. Keep RTSP values out of logs, command strings printed to logs, and failure responses.
- Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries.
- Keep continuous recording (`RecordingEnabled`) and event-triggered recording (`EventRecordingEnabled`) as separate per-camera opt-ins. Event mode watches the same active Agent stream, durably records detection trigger windows under the Agent state directory with owner-only permissions, starts FFmpeg on the event, and stops 30 seconds after the latest event by default (`Agent:RecordingEventPostRollSeconds`, validated from 5 to 300 seconds). It does not record pre-roll. Disabling event mode, disabling/removing the camera assignment, or stopping its stream clears pending trigger windows and stops the process.
- Map the primary video stream and optional first audio stream into MP4 segments. Copy compatible video without re-encoding and encode optional audio as AAC at a bounded 128 kbit/s so common RTSP audio codecs are playable in browsers; feeds without audio must still record successfully. Keep privacy/operator consent in the per-camera recording opt-in.
- Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port.
- Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback.
- Central quota is configured with `RECORDING_STORAGE_QUOTA_MAX_BYTES` in Compose (application key `Recordings:StorageQuota:MaxBytes`, default 1 TiB). Options are validated on startup; a segment that would exceed the aggregate persisted recording bytes receives HTTP 507 and its uploaded object is removed. The PostgreSQL advisory transaction lock makes the aggregate check atomic across simultaneous Agent uploads; upload bytes finish before acquiring the short metadata lock. Give each upload attempt a unique object key below its recording ID so a racing idempotent retry cannot overwrite the winning segment; remove the losing attempt's object even when both use the same camera.
- The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL.
- Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance.
- Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior.
- `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` seeds a manifest and MP4 into a temporary spool, returns 503 then 204 from a mock Central, and proves the segment remains through failure, reuses the same idempotency URL/API-key boundary, and is deleted only after success.
- For acceptance, install an EXIT cleanup trap before build/start, then build Central and Agent from this changed source with unique image tags in a disposable Compose project. Publish a synthetic RTSP stream containing H.264 video and AAC-compatible audio through MediaMTX; register and assign the Agent, enable recording, and prove a segment reaches Central through the live Agent RTSP loop. Verify ffprobe sees video and audio in a downloaded segment, scoped listing/range download, and unauthorized denial. Remove only that Compose project, confirm its containers/volumes/network are gone, and remove/verify every recipe-built local image tag.
- For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks.
- Run `RecordingEventAssociationTests` against PostgreSQL: upload a segment and verify that only same-camera events in the half-open interval `[timestamp, timestamp + duration)` receive its recording ID; events at either outside boundary remain unlinked. This confirms relational translation and event/recording association without claiming event-triggered capture.
- Event recording is an independent opt-in from continuous recording. Central sends `event_recording_enabled` in the per-Agent camera configuration; the Agent persists one atomic marker per camera before attempting the HTTP event outbox write, so outbox capacity or delivery cannot suppress capture. Each qualifying event refreshes the configured post-roll (5–300 seconds, default 30). Motion, person, vehicle, unknown-person, face, and plate events can refresh that window. The Agent starts FFmpeg only while the camera stream is active and the marker remains live. Clear markers when event recording is disabled, the camera is disabled, or assignment is removed. The marker is bounded to one file per camera and survives Agent restart.
- For event-triggered acceptance, enable only `EventRecordingEnabled` through CameraDetail/API, use an assigned Agent and active synthetic RTSP stream, and prove the Agent starts capture and uploads a segment. Verify event association for both event-first and recording-first arrival. Restart the Agent during an active window and prove capture resumes from the marker; disable the toggle and prove uploads stop after configuration settles. Keep real-camera codec and timing validation separate.
- For each recording recipe, record project-unique tags for locally built Central, Agent, or helper images and remove/verify those exact tags after Compose teardown in the same EXIT trap, including on build/assertion failure. Retain shared PostgreSQL/MediaMTX base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or `image prune`. Follow `skills/compose-disposable-recipe/SKILL.md`.
- Do not reuse an app/helper tag built by a different acceptance recipe. Build this recipe's changed source under fresh project-unique tags; record `local image tags: none` only for genuinely upstream-only test containers. Every run note must list the exact local tags as absent, or explicitly state no local images were built.
On 5 November 2026, disposable Compose project `hmd-event-e2e-1793899172-25617` built Central and Agent from this source with locked .NET 10 restore. The actual Agent registered from the generated site token, consumed an animated H.264/AAC RTSP stream, emitted MotionDetected, uploaded an event-only segment while continuous recording remained off, and Central associated the event with that recording. Restarting the Agent while the post-roll marker was active produced another segment; disabling event recording through the API left the recording count stable after configuration settled. PostgreSQL event-first and recording-first association tests both pass. The focused `RecordingTriggerStoreTests` passed 3/3 in SDK Compose project `hmd-trigger-unit-1793899683-6893`. Cleanup traps removed exact local tags `heimdall:hmd-event-e2e-1793899172-25617-central` and `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, verified both absent, and confirmed zero project containers, volumes, and networks; the unit-test recipe built no local images and also left zero project resources. Synthetic motion thresholds were lowered for deterministic event generation. Real-camera codecs/timing remain unvalidated.
+48
View File
@@ -0,0 +1,48 @@
---
name: vision-identity
description: Implement Heimdall's opt-in, self-hosted plate OCR and preserve the licensing/privacy gates for camera face and plate identity.
---
# Vision identity in Heimdall
Read `AGENTS.md` and FEAT-03/UI-02 in `todo.md`. Current API contract only supports a human-triggered OCR request with an operator-supplied JPEG/PNG plate crop. It does not infer plate boxes from video frames or recognize faces.
## Plate OCR currently implemented
- `PlateOcr:Enabled` defaults to false. Explicitly enable the on-prem Central option to offer OCR; the camera detail UI sends only the file the user selected.
- Central uses the system Tesseract executable and English LSTM data. Tesseract engine and the official `tessdata_best` model data declare Apache-2.0. Do not add other OCR or detection weights without reviewing their exact asset licenses and provenance.
- The controller requires a human principal with `Camera.Write`, camera scope, JPEG/PNG signature, configured byte limit (at most 512 KiB), and rate limits. OCR rejects malformed, oversized, or over-4-megapixel crops and times out after a bounded interval.
- OCR runs on the Heimdall Central host. The image is written to a random temporary path and deleted in `finally`; do not log the crop, extracted text, embedding, or raw image path.
- Store only the normalized plate candidate, confidence, and a `LicensePlateDetected` event. The API may return a unique exact vehicle/person as a suggestion, but it does not persist identity links during OCR. `CameraDetail` presents the suggestion for operator review; the operator must explicitly confirm a vehicle. The confirmation API requires a human principal with both camera and vehicle write permissions, verifies access to the camera, the event-to-observation association, and an exact normalized plate match, and writes the observation/event links together. Never treat OCR output as verified identity.
- OCR observations remain unassigned until a human confirms an association; unassigned plate rows are purged after 30 days. `CleanupLicensePlatesJob` also removes `LicensePlateDetected` events older than 30 days, including their label and metadata. If an event has stored snapshots, it deletes those objects from the exact captured destination before deleting the database row. Events with missing/incomplete storage provenance are retained with a warning rather than deleting from a guessed destination. Vehicle-owned plate records remain governed by their explicit vehicle lifecycle. Keep the wider privacy review open before production enablement.
## Face-model gate
ONNX Runtime is already used by the Agent and is MIT licensed. A model runtime license does not grant rights to a particular model's weights or training data. InsightFace's model-zoo documentation restricts its distributed pretrained weights to non-commercial research. ONNX Model Zoo's ArcFace/UltraFace listing points to sourced models but does not establish one blanket weight/data license. Do not bundle SFace, ArcFace, YuNet, or plate-detector weights unless the exact asset and training-data rights are reviewed. An operator-provided model also needs a documented tensor/preprocessing contract, stable model ID stored with enrollments, explicit opt-in, deletion/retention semantics, and representative accuracy testing before face matches can create events.
Official sources reviewed:
- [Tesseract engine license and command-line formats](https://github.com/tesseract-ocr/tesseract)
- [Official `tessdata_best` license](https://github.com/tesseract-ocr/tessdata_best)
- [Official `tessdata` language-data license](https://github.com/tesseract-ocr/tessdata)
- [Official Tesseract data-file compatibility guidance](https://github.com/tesseract-ocr/tessdoc/blob/main/Data-Files.md)
- [ONNX Runtime repository license](https://github.com/microsoft/onnxruntime)
- [ONNX Model Zoo sourcing and model catalog](https://github.com/onnx/models/blob/main/README.md)
- [InsightFace model-zoo license statement](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md)
## Human confirmation workflow
- Keep mismatches and ambiguous candidate lists unlinked until an operator selects a vehicle and confirms.
- Confirm with the observation ID, event ID and selected vehicle ID; reject anonymous or camera-scoped requests, mismatched plates, unrelated events, and conflicting existing links.
- Preserve the matching UI/API behavior with component/controller tests and handler tests. API authorization and camera scope stay at the Web boundary; the application handler independently checks camera access before persistence.
## Acceptance
1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test.
2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. The historical entry does not record removal and exact-tag absence verification for the image; treat this recipe's image cleanup as unverified and repeat it before relying on that portion of acceptance.
3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing.
4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The historical record for this bootstrap does not name a locally built image tag or document an exact image absence check; treat image cleanup as unverified and repeat it before relying on that part of the acceptance. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used.
5. Human confirmation acceptance passed in source-built disposable project `hmd-plate-link-1793880442-bff1ca`: the synthetic OCR crop returned `AB-123-CD` at confidence 0.912; a vehicle with another plate was rejected with HTTP 422; PostgreSQL showed both links null before confirmation; explicit confirmation returned 200 and both `license_plates.VehicleId` and `camera_events.VehicleId` were populated; anonymous confirmation returned 401. Cleanup verified zero containers, volumes and networks and removed/verified absence of the exact `heimdall:hmd-plate-link-1793880442-bff1ca-central` image tag. Two earlier recipe attempts had harness-only readiness/SQL identifier mistakes; each exact project and tag was cleaned and absence checked.
6. Keep assigning the locally built Central image a unique project tag and remove/verify that exact tag on every recipe completion, including failure paths. Retain shared .NET/ASP.NET base images and never use broad image pruning.
7. These acceptances cover one synthetic crop and the API persistence/confirmation path only. They do not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or the suitability of the retention period under an external privacy review.
8. Plate-event retention is covered by `CleanupLicensePlatesJobTests` (SQLite: expired plate event removed, recent plate and unrelated events retained; captured snapshot objects removed first; storage deletion failure retains the event) and `PlateEventRetentionPostgresTests` (PostgreSQL EF translation/deletion). The disposable Compose project `hmd-plate-retention-pg-1793885533-16210` ran the PostgreSQL test from the mounted changed source with locked restore, generated credentials, and project-scoped database/NuGet volumes; result 1/1. Teardown removed and verified zero project containers/volumes/networks. The recipe builds no Heimdall image; shared PostgreSQL/SDK base images are retained. This validates the local retention mechanics, not the external privacy policy or any production retention requirement.
+95
View File
@@ -0,0 +1,95 @@
# Live WebRTC implementation and acceptance
The current vertical provides Agent RTSP re-publishing, Central camera-scoped
Data Protection tickets and MediaMTX auth, and a camera detail WHEP player.
`FEAT-01` stays open until the disposable synthetic acceptance below passes
and external network behavior is measured.
## Required architecture
- Keep camera assignment and stream lifecycle in Agent. Only an enabled camera
present in the current Central assignment snapshot may be published. Stop the
publisher when assignment, enablement, configuration, or Agent lifetime ends.
- Use MediaMTX as the WebRTC/WHEP media server. Agent publishes the camera's
browser-compatible H.264 stream to a camera-ID path. The relay passes video
through and optionally maps the first audio track, transcoding it to Opus for
WebRTC browser compatibility; a source without audio must still publish.
Prefer passthrough when the source video codec is compatible; otherwise make
video transcoding an explicit, bounded option. PTZ remains separate.
- Central issues random, short-lived, purpose-separated publish and read claims
scoped to one camera and one action. Protect claims with the shared Heimdall
Data Protection key ring. MediaMTX HTTP auth must validate exact path, action,
protocol, expiry, Agent assignment for publish, and current user camera rights
for read. Never put RTSP credentials, Central API keys, or reusable TURN
credentials in browser-visible URLs or logs.
- Browser obtains a read session from the authenticated camera API and performs
WHEP with that short-lived bearer token. ICE servers and public WHEP URL must
come from deployment configuration, never source-code hostnames. Do not issue
static TURN credentials to the browser.
- Bound simultaneous Agent publishers and viewers, request duration, retries,
FFmpeg process count, and session lifetime. Ensure cancellation/config changes
reap child processes and release permits.
## Implementation references
Use MediaMTX's maintained documentation as the protocol reference:
- [WHEP/WebRTC read](https://mediamtx.org/docs/read/webrtc)
- [HTTP authentication callbacks](https://mediamtx.org/docs/features/authentication)
- [ICE, TURN, codec and latency details](https://mediamtx.org/docs/features/webrtc-specific-features)
- [Configuration reference](https://mediamtx.org/docs/references/configuration-file)
- [RTSP camera/source behavior](https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/08-rtsp-cameras-and-servers.md)
- [MediaMTX license](https://github.com/bluenviron/mediamtx/blob/main/LICENSE)
Use H.264 without B-frames for browser compatibility and latency. Validate
actual negotiation in browsers; a successful RTSP publish does not prove WHEP.
## Required acceptance
Run from changed source in an isolated disposable Compose project with unique
project name, generated credentials, ports and volumes. The optional
`docker/docker-compose.webrtc-test.yml` starts a local-only generated H.264
camera feed. Use `docker/docker-compose.webrtc-local-test.yml` plus
`docker/docker-compose.webrtc-test.yml` with the core `docker-compose.yml` in one
unique project. Set unique generated database/JWT credentials, loopback ports,
`HEIMDALL_NETWORK_NAME`, `HEIMDALL_MEDIAMTX_AUTH_URL`, WHEP/publish URLs, and the
Central browser origin in an env file outside the repository. Start Central,
MediaMTX and the synthetic feed first; bootstrap the first admin and site, then
place the generated synthetic site token in the disposable env file and start
the Agent. Configure its assigned camera against the host loopback RTSP port. Do not depend on a physical camera. Verify all of the following:
1. An assigned Agent receives only its assigned camera's short-lived publish
credential and publishes synthetic H.264 to that camera path.
2. An authorized user obtains a short-lived read claim and a browser-compatible
WHEP session; the browser receives decoded frames. With synthetic audio,
prove the browser negotiates audio and video; playback starts muted for
autoplay compatibility and the native controls allow the viewer to enable it.
3. An unassigned Agent, cross-camera claim, wrong action/path/protocol, expired
token, and user without camera access are rejected.
4. Disable/reassign camera, stop Agent, end viewer, and expire claim; verify the
matching processes/sessions terminate and resource counts return to baseline.
5. Logs and API errors contain no credentials, raw tokens, RTSP URLs, or ICE
secrets. Verify configured ICE/TURN candidate behavior separately.
6. Install an EXIT trap before the first image build/start. Tear down only that
Compose project with volumes/orphans, then verify its containers, volumes
and network are gone. Independently remove and verify absence of every
project-unique local image tag built by this recipe (Central, Agent, or
helper), even after a failed build/assertion; preserve shared MediaMTX and
other upstream base images. Preserve the test exit status and report cleanup
failures. Do not use `--rmi all` or broad image-prune commands.
For this recipe the locally built tags are Central and Agent; record their
exact project-unique values before building. The synthetic RTSP source uses
the upstream MediaMTX and FFmpeg images, which remain installed. The cleanup
record is complete only after both local tags have been removed and an
exact-tag `docker image inspect` confirms absence.
Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and Agent relay tests pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Its historical record lacks exact-tag image absence checks, so repeat this recipe under the cleanup requirements above before treating cleanup as fully verified. Physical camera, LAN, external TURN and PTZ remain unvalidated. Synthetic audio codec and browser-track acceptance is recorded separately below; keep FEAT-01 open for its remaining external items.
## Synthetic audio acceptance
Run a disposable Compose source build plus a synthetic H.264+sine RTSP publisher. The source-built Agent tests must assert the relay command maps `0:a:0?`, converts audio to Opus, and does not disable audio. The Compose stream must be pulled from the relay and inspected to confirm H.264 video and Opus audio. Also run the authenticated WHEP browser flow and assert its media stream contains both tracks; no physical camera or external TURN claim follows from this recipe. Build app images with unique tags and remove/verify those exact tags in the same EXIT cleanup trap, or explicitly record `local image tags: none` for SDK/upstream-only test runs.
`LiveViewTests.Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay` uses its fake peer by default for an isolated UI contract test. For the real-media path, set `HEIMDALL_TEST_LIVE_WHEP_URL` to the disposable MediaMTX `/path/whep` endpoint before running the same test. It then uses Chromium's real RTCPeerConnection and waits for a decoded video frame (`videoWidth > 0`) plus a live audio track. Pair this with a project-isolated MediaMTX service and synthetic H.264/Opus publisher, configured with a loopback WHEP port, a matching loopback ICE UDP candidate, and wildcard origins only on the throwaway test server. The test still mocks only Central's short-lived read-session response; the earlier Central permission/ticket test remains the evidence for that boundary. Teardown must remove and verify all project resources and any exact local image tags.
On 5 November 2026, disposable project `hmd-whep-audio-1793905588-381987` ran MediaMTX plus an animated 640×360 H.264 and 48 kHz sine/Opus publisher. The source-built Web/E2E assembly used the real `live-view.js` and Chromium against `http://127.0.0.1:<ephemeral>/live/whep`; `LiveViewTests` passed 1/1 with a decoded video frame, live audio track, and muted autoplay. Central's session response was stubbed, so this proves browser/media negotiation and decoding, not production auth or external ICE/TURN. Cleanup verified zero project containers, volumes and networks; no local images were built and the temporary Compose file was removed.
+19
View File
@@ -51,6 +51,21 @@ public sealed class AgentOptions
/// <summary>Directory for persisting agent identity state. Defaults to /var/lib/heimdall on Linux.</summary>
public string? StateDirectory { get; init; }
/// <summary>Length of completed MP4 segments created for recording-enabled cameras.</summary>
[Range(5, 300)]
public int RecordingSegmentSeconds { get; init; } = 60;
/// <summary>Seconds to keep event-triggered capture running after the latest detection.</summary>
[Range(5, 300)]
public int RecordingEventPostRollSeconds { get; init; } = 30;
/// <summary>Upper bound for queued completed recordings kept locally while Central is unavailable.</summary>
[Range(typeof(long), "16777216", "107374182400")]
public long RecordingSpoolMaxBytes { get; init; } = 1_073_741_824;
/// <summary>FFmpeg executable used for opt-in segment recording.</summary>
public string RecordingFfmpegPath { get; init; } = "ffmpeg";
/// <summary>Max retries for agent registration (default: 5).</summary>
[Range(1, 20)]
public int RegistrationMaxRetries { get; init; } = 5;
@@ -95,6 +110,10 @@ public sealed class AgentOptions
/// </summary>
public AnalysisMode AnalysisMode { get; init; } = AnalysisMode.Local;
/// <summary>ONNX execution provider. CPU is the default; CUDA requires a compatible NVIDIA runtime built with the GPU package.</summary>
[RegularExpression("^(CPU|CUDA)$")]
public string InferenceExecutionProvider { get; init; } = "CPU";
/// <summary>
/// URL of the remote analysis broker (required when AnalysisMode = Remote).
/// Supply the broker URL through deployment configuration when remote analysis is enabled.
+11 -1
View File
@@ -9,6 +9,15 @@
<NoWarn>$(NoWarn);NU1902</NoWarn>
</PropertyGroup>
<!-- Keep the default Agent lean and portable. The CUDA container uses a separate, pinned lock file. -->
<PropertyGroup Condition="'$(HeimdallOnnxRuntime)' == 'GPU'">
<NuGetLockFilePath>packages.gpu.lock.json</NuGetLockFilePath>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
</PropertyGroup>
<PropertyGroup Condition="'$(HeimdallOnnxRuntime)' != 'GPU'">
<NuGetLockFilePath>packages.lock.json</NuGetLockFilePath>
</PropertyGroup>
<!-- Microsoft.Extensions.Hosting and Microsoft.Extensions.Http are provided implicitly by Microsoft.NET.Sdk.Web -->
<ItemGroup>
@@ -25,7 +34,8 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.13" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.13" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.13" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.22.0" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.22.0" Condition="'$(HeimdallOnnxRuntime)' != 'GPU'" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.Gpu" Version="1.22.0" Condition="'$(HeimdallOnnxRuntime)' == 'GPU'" />
<PackageReference Include="OpenTelemetry" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.17.0-beta.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" />
+8 -1
View File
@@ -6,6 +6,7 @@ using Heimdall.Agent.Logging;
using Heimdall.Agent.Services;
using Heimdall.Application.Discovery;
using Heimdall.Application.Metrics;
using Heimdall.Domain.Enums;
using Heimdall.Mdns;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
@@ -131,6 +132,7 @@ builder.Services.AddHostedService<CameraStatusReporterService>(sp => sp.GetRequi
builder.Services.AddSingleton<DetectionReporterService>();
builder.Services.AddSingleton<IDetectionReporter>(sp => sp.GetRequiredService<DetectionReporterService>());
builder.Services.AddHostedService<DetectionReporterService>(sp => sp.GetRequiredService<DetectionReporterService>());
builder.Services.AddSingleton<RecordingTriggerStore>();
builder.Services.AddSingleton<DiscoveryScanTrigger>();
builder.Services.AddSingleton<AgentCredentialStore>();
builder.Services.AddSingleton<RuntimeLogLevel>();
@@ -149,7 +151,10 @@ builder.Services.AddSingleton<CameraConfigStore>();
builder.Services.AddSingleton<FrameAnalyzerService>(sp => new FrameAnalyzerService(
sp.GetRequiredService<ILogger<FrameAnalyzerService>>(),
sp.GetRequiredService<CircuitBreaker>(),
sp.GetRequiredService<PipelineDegradationManager>()));
sp.GetRequiredService<PipelineDegradationManager>(),
inference: null,
inferenceExecutionProvider: sp.GetRequiredService<IOptions<AgentOptions>>().Value.InferenceExecutionProvider,
cudaDeviceAvailable: sp.GetRequiredService<GpuDetectorService>().GetInfo().GpuType == GpuAcceleration.NvidiaCuda));
builder.Services.AddSingleton<CameraStreamService>();
builder.Services.AddSingleton<FrameResizer>();
builder.Services.AddSingleton<RemoteFrameBrokerService>();
@@ -169,6 +174,8 @@ builder.Services.AddSingleton(sp => new SnapshotPipelineService(new SnapshotPipe
sp.GetRequiredService<IRemoteFrameBroker>(),
sp.GetRequiredService<FrameResizer>())));
builder.Services.AddHostedService(sp => sp.GetRequiredService<SnapshotPipelineService>());
builder.Services.AddHostedService<AgentRecordingService>();
builder.Services.AddHostedService<LiveCameraRelayService>();
// Log capture & upload to Central (ticket #50)
builder.Services.AddSingleton<LogBufferService>();
@@ -11,7 +11,9 @@ public sealed record AgentCameraConfig(
string RtspUrl,
string? SubRtspUrl,
bool Enabled,
Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null)
Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null,
bool RecordingEnabled = false,
bool EventRecordingEnabled = false)
{
/// <summary>
/// URL used for AI capture: the low-res sub-stream when available,
@@ -0,0 +1,333 @@
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Heimdall.Agent.Services;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent;
/// <summary>
/// Starts an opt-in FFmpeg segment process for enabled cameras, persists completed
/// segments under the Agent state volume, and retries uploads until Central acknowledges them.
/// </summary>
public sealed class AgentRecordingService : BackgroundService
{
private const long MaxSegmentBytes = 100 * 1024 * 1024;
private static readonly TimeSpan LoopDelay = TimeSpan.FromSeconds(5);
private readonly CameraConfigStore _cameras;
private readonly CameraStreamService _streams;
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly IHttpClientFactory _clients;
private readonly ILogger<AgentRecordingService> _logger;
private readonly RecordingTriggerStore _triggers;
private readonly Dictionary<Guid, RecordingSession> _sessions = [];
private readonly SemaphoreSlim _lifecycle = new(1, 1);
private string _spoolRoot = string.Empty;
public AgentRecordingService(CameraConfigStore cameras, CameraStreamService streams, AgentState state,
IOptions<AgentOptions> options, IHttpClientFactory clients, ILogger<AgentRecordingService> logger,
RecordingTriggerStore? triggers = null)
{
_cameras = cameras;
_streams = streams;
_state = state;
_options = options.Value;
_clients = clients;
_logger = logger;
_triggers = triggers ?? new RecordingTriggerStore(options);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var stateDirectory = _options.StateDirectory ??
(OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
_spoolRoot = Path.GetFullPath(Path.Combine(stateDirectory, "recordings"));
Directory.CreateDirectory(_spoolRoot);
if (OperatingSystem.IsLinux())
File.SetUnixFileMode(_spoolRoot, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
try
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await ReconcileAsync(stoppingToken).ConfigureAwait(false);
await UploadCompletedSegmentsAsync(stoppingToken).ConfigureAwait(false);
await TrimSpoolAsync(stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
catch (Exception ex)
{
_logger.LogWarning("Recording loop failed (error type {ErrorType})", ex.GetType().Name);
}
await Task.Delay(LoopDelay, stoppingToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
finally
{
foreach (var cameraId in _sessions.Keys.ToArray())
await StopSessionAsync(cameraId, CancellationToken.None).ConfigureAwait(false);
}
}
private async Task ReconcileAsync(CancellationToken ct)
{
await _lifecycle.WaitAsync(ct).ConfigureAwait(false);
try
{
var configured = _cameras.Cameras.ToDictionary(c => c.CameraId);
await _triggers.ClearExceptAsync(configured.Values
.Where(camera => camera.Enabled && camera.EventRecordingEnabled)
.Select(camera => camera.CameraId).ToHashSet(), ct).ConfigureAwait(false);
foreach (var (cameraId, session) in _sessions.ToArray())
{
if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled ||
camera.RtspUrl != session.RtspUrl || !_streams.IsStreamActive(cameraId) || session.Process.HasExited)
{
await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
continue;
}
if (!camera.RecordingEnabled && !(camera.EventRecordingEnabled &&
(await _triggers.GetStatusAsync(cameraId, ct).ConfigureAwait(false)).IsActive))
await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
}
foreach (var camera in configured.Values.Where(c => c.Enabled &&
(c.RecordingEnabled || c.EventRecordingEnabled) &&
!string.IsNullOrWhiteSpace(c.RtspUrl)))
{
var triggerStatus = camera.EventRecordingEnabled
? await _triggers.GetStatusAsync(camera.CameraId, ct).ConfigureAwait(false)
: RecordingTriggerStore.RecordingTriggerStatus.Inactive;
var shouldRecord = camera.RecordingEnabled || triggerStatus.IsActive;
if (shouldRecord && _streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId))
StartSession(camera, camera.RecordingEnabled ? null : triggerStatus.FirstTriggeredAtUtc);
}
}
finally { _lifecycle.Release(); }
}
private void StartSession(AgentCameraConfig camera, DateTime? triggeredAtUtc)
{
var cameraRoot = Path.Combine(_spoolRoot, camera.CameraId.ToString("N"));
var sessionDirectory = Path.Combine(cameraRoot, Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(sessionDirectory);
if (OperatingSystem.IsLinux())
File.SetUnixFileMode(sessionDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
var startedAt = triggeredAtUtc ?? DateTime.UtcNow;
File.WriteAllText(Path.Combine(sessionDirectory, "started-at.txt"), startedAt.ToString("O", CultureInfo.InvariantCulture));
var startInfo = CreateStartInfo(_options.RecordingFfmpegPath, camera.RtspUrl!, sessionDirectory,
_options.RecordingSegmentSeconds);
Process? process = null;
try
{
process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
if (!process.Start()) throw new InvalidOperationException("FFmpeg did not start");
var session = new RecordingSession(camera.CameraId, camera.RtspUrl!, sessionDirectory, startedAt, process);
_sessions[camera.CameraId] = session;
session.ErrorDrain = DrainStandardErrorAsync(process);
_logger.LogInformation("Video recording started for camera {CameraId}", camera.CameraId);
}
catch (Exception ex)
{
process?.Dispose();
_logger.LogWarning("Video recording could not start for camera {CameraId} (error type {ErrorType})",
camera.CameraId, ex.GetType().Name);
}
}
internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string rtspUrl, string sessionDirectory,
int segmentSeconds)
{
var info = new ProcessStartInfo
{
FileName = ffmpegPath,
RedirectStandardInput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
foreach (var argument in new[]
{
"-hide_banner", "-loglevel", "error", "-rtsp_transport", "tcp", "-i", rtspUrl,
"-map", "0:v:0", "-map", "0:a:0?", "-c:v", "copy", "-c:a", "aac", "-b:a", "128k",
"-f", "segment", "-segment_time",
segmentSeconds.ToString(CultureInfo.InvariantCulture), "-segment_format", "mp4",
"-reset_timestamps", "1", "-segment_list", Path.Combine(sessionDirectory, "segments.csv"),
"-segment_list_type", "csv", "-segment_list_size", "10000",
Path.Combine(sessionDirectory, "segment-%06d.mp4")
}) info.ArgumentList.Add(argument);
return info;
}
private static async Task DrainStandardErrorAsync(Process process)
{
try
{
while (await process.StandardError.ReadLineAsync().ConfigureAwait(false) is not null) { }
}
catch (IOException) { }
catch (ObjectDisposedException) { }
}
private async Task StopSessionAsync(Guid cameraId, CancellationToken ct)
{
await _lifecycle.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_sessions.TryGetValue(cameraId, out var session))
await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
}
finally { _lifecycle.Release(); }
}
private async Task StopSessionCoreAsync(Guid cameraId, RecordingSession session, CancellationToken ct)
{
_sessions.Remove(cameraId);
try
{
if (!session.Process.HasExited)
{
try { await session.Process.StandardInput.WriteLineAsync("q").ConfigureAwait(false); }
catch (IOException) { }
try { await session.Process.WaitForExitAsync(ct).WaitAsync(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false); }
catch (TimeoutException) { session.Process.Kill(entireProcessTree: true); }
catch (InvalidOperationException) { }
}
if (session.ErrorDrain is not null) await session.ErrorDrain.ConfigureAwait(false);
_logger.LogInformation("Video recording stopped for camera {CameraId}", cameraId);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception ex)
{
_logger.LogDebug("FFmpeg cleanup failed for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name);
}
finally { session.Process.Dispose(); }
}
private async Task UploadCompletedSegmentsAsync(CancellationToken ct)
{
if (!Directory.Exists(_spoolRoot)) return;
foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories))
{
ct.ThrowIfCancellationRequested();
if (!Guid.TryParseExact(Directory.GetParent(Directory.GetParent(manifest)!.FullName)!.Name, "N", out var cameraId))
continue;
DateTime startedAt;
try
{
startedAt = DateTime.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(manifest)!, "started-at.txt")),
CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind).ToUniversalTime();
}
catch (IOException) { continue; }
catch (FormatException) { continue; }
string[] rows;
try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); }
catch (IOException) { continue; }
foreach (var row in rows)
{
var fields = row.Split(',');
if (fields.Length < 3) continue;
var fileName = Path.GetFileName(fields[0]);
if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal) ||
!double.TryParse(fields[1], CultureInfo.InvariantCulture, out var startSeconds) ||
!double.TryParse(fields[2], CultureInfo.InvariantCulture, out var endSeconds)) continue;
var duration = endSeconds - startSeconds;
if (duration is < 1 or > 300 || !double.IsFinite(duration) || !double.IsFinite(startSeconds)) continue;
var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName);
if (!File.Exists(path)) continue;
var info = new FileInfo(path);
if (info.Length > MaxSegmentBytes)
{
_logger.LogWarning("Dropping oversized video segment for camera {CameraId} ({SizeBytes} bytes)", cameraId, info.Length);
info.Delete();
continue;
}
await UploadSegmentAsync(cameraId, path, startedAt.AddSeconds(startSeconds), duration, ct).ConfigureAwait(false);
}
}
}
private async Task UploadSegmentAsync(Guid cameraId, string path, DateTime timestamp, double duration, CancellationToken ct)
{
var relativePath = Path.GetRelativePath(_spoolRoot, path).Replace(Path.DirectorySeparatorChar, '/');
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(relativePath));
var recordingId = new Guid(hash.AsSpan(0, 16));
var url = $"api/cameras/{cameraId:D}/recordings/{recordingId:D}/content?timestamp={Uri.EscapeDataString(timestamp.ToString("O", CultureInfo.InvariantCulture))}&durationSeconds={duration.ToString(CultureInfo.InvariantCulture)}";
try
{
using var request = new HttpRequestMessage(HttpMethod.Put, url);
request.Headers.Add("X-API-Key", _state.ApiKey);
await using var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan);
request.Content = new StreamContent(input);
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4");
request.Content.Headers.ContentLength = input.Length;
using var response = await _clients.CreateClient("Central").SendAsync(request,
HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Video segment upload returned HTTP {StatusCode} for camera {CameraId}",
(int)response.StatusCode, cameraId);
return;
}
input.Close();
File.Delete(path);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (HttpRequestException ex)
{
_logger.LogWarning("Video segment upload failed for camera {CameraId} (error type {ErrorType})",
cameraId, ex.GetType().Name);
}
catch (IOException ex)
{
_logger.LogWarning("Video segment could not be read or removed for camera {CameraId} (error type {ErrorType})",
cameraId, ex.GetType().Name);
}
}
private async Task TrimSpoolAsync(CancellationToken ct)
{
var ready = new List<FileInfo>();
foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories))
{
string[] rows;
try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); }
catch (IOException) { continue; }
foreach (var row in rows)
{
var fileName = Path.GetFileName(row.Split(',')[0]);
if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal)) continue;
var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName);
if (File.Exists(path)) ready.Add(new FileInfo(path));
}
}
var total = ready.Sum(file => file.Length);
foreach (var file in ready.OrderBy(file => file.LastWriteTimeUtc))
{
if (total <= _options.RecordingSpoolMaxBytes) break;
ct.ThrowIfCancellationRequested();
var size = file.Length;
try
{
file.Delete();
total -= size;
_logger.LogWarning("Dropping oldest queued video segment for camera {CameraId}; local recording spool reached its configured limit",
Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(file.FullName))));
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
}
private sealed record RecordingSession(Guid CameraId, string RtspUrl, string Directory,
DateTime StartedAt, Process Process)
{
public Task? ErrorDrain { get; set; }
}
}
@@ -82,13 +82,13 @@ public sealed class AnalysisJobPollingService : BackgroundService
private async Task<AnalysisResult> ExecuteJobAsync(LeasedJob job, CancellationToken ct)
{
if (!IsObjectDetection(job.JobType))
if (!TryGetSupportedJobType(job.JobType, out var jobType))
return Failure(job.AttemptId, "Unsupported analysis job type");
var camera = _cameras.Cameras.FirstOrDefault(c => c.CameraId == job.CameraId && c.Enabled);
if (camera is null || !_streams.IsStreamActive(job.CameraId))
return Failure(job.AttemptId, "Camera is not assigned, enabled, or streaming");
if (!_analyzer.ModelAvailable)
if (jobType != AnalysisJobType.MotionDetection && !_analyzer.ModelAvailable)
return Failure(job.AttemptId, "Object detection model is unavailable");
Snapshot? frame;
@@ -103,6 +103,27 @@ public sealed class AnalysisJobPollingService : BackgroundService
if (frame is null)
return Failure(job.AttemptId, "Camera frame capture failed or timed out");
if (jobType == AnalysisJobType.MotionDetection)
{
await Task.Delay(TimeSpan.FromMilliseconds(500), ct).ConfigureAwait(false);
Snapshot? nextFrame;
try
{
nextFrame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
nextFrame = null;
}
if (nextFrame is null)
return Failure(job.AttemptId, "Camera frame capture failed or timed out");
var motion = MotionDetectionAnalyzer.Compare(frame.JpegData, nextFrame.JpegData);
return new AnalysisResult(job.AttemptId, true, null, motion
.Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex))
.ToArray());
}
var confidence = TryGetMinConfidence(job.ParametersJson, out var requestedConfidence)
? requestedConfidence
: camera.DetectionProfile?.MinConfidence ?? FrameAnalyzerService.DefaultMinConfidence;
@@ -110,12 +131,13 @@ public sealed class AnalysisJobPollingService : BackgroundService
if (analysis is null)
return Failure(job.AttemptId, "Object detection was unavailable or saturated");
return new AnalysisResult(job.AttemptId, true, null, analysis.Detections
var detections = SelectDetections(jobType, analysis.Detections);
return new AnalysisResult(job.AttemptId, true, null, detections
.Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex))
.ToArray());
}
private async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId,
internal async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId,
AnalysisResult result, CancellationToken ct)
{
var retryDelay = TimeSpan.FromSeconds(2);
@@ -133,6 +155,13 @@ public sealed class AnalysisJobPollingService : BackgroundService
jobId, result.AttemptId);
return;
}
if ((int)response.StatusCode is >= 400 and < 500)
{
_logger.LogError(
"Analysis result for job {JobId} was permanently rejected with HTTP {StatusCode}; stopping retries",
jobId, (int)response.StatusCode);
return;
}
_logger.LogWarning("Analysis result for job {JobId} was rejected with HTTP {StatusCode}; retrying",
jobId, (int)response.StatusCode);
}
@@ -154,14 +183,37 @@ public sealed class AnalysisJobPollingService : BackgroundService
}
}
private static bool IsObjectDetection(JsonElement type) => type.ValueKind switch
internal static IReadOnlyList<DetectionResult> SelectDetections(
AnalysisJobType jobType, IReadOnlyList<DetectionResult> detections) => jobType switch
{
JsonValueKind.String => string.Equals(type.GetString(), nameof(AnalysisJobType.ObjectDetection),
StringComparison.OrdinalIgnoreCase),
JsonValueKind.Number => type.TryGetInt32(out var value) && value == (int)AnalysisJobType.ObjectDetection,
_ => false,
AnalysisJobType.ObjectDetection => detections,
AnalysisJobType.PersonDetection => detections.Where(IsPerson).ToArray(),
AnalysisJobType.VehicleClassification => detections.Where(IsVehicle).ToArray(),
_ => [],
};
private static bool IsPerson(DetectionResult detection) =>
detection.ClassIndex == 0 || string.Equals(detection.Label, "person", StringComparison.OrdinalIgnoreCase);
private static bool IsVehicle(DetectionResult detection) =>
detection.ClassIndex is 2 or 3 or 5 or 7 || detection.Label.ToLowerInvariant() is "car" or "motorcycle" or "bus" or "truck";
internal static bool TryGetSupportedJobType(JsonElement type, out AnalysisJobType jobType)
{
if (type.ValueKind == JsonValueKind.String && Enum.TryParse(type.GetString(), true, out jobType))
return IsSupported(jobType);
if (type.ValueKind == JsonValueKind.Number && type.TryGetInt32(out var value) && Enum.IsDefined(typeof(AnalysisJobType), value))
{
jobType = (AnalysisJobType)value;
return IsSupported(jobType);
}
jobType = default;
return false;
}
private static bool IsSupported(AnalysisJobType type) => type is AnalysisJobType.ObjectDetection or
AnalysisJobType.PersonDetection or AnalysisJobType.VehicleClassification or AnalysisJobType.MotionDetection;
private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []);
private static bool TryGetMinConfidence(string? parametersJson, out float confidence)
@@ -181,8 +233,8 @@ public sealed class AnalysisJobPollingService : BackgroundService
private sealed record LeasedJob(Guid JobId, Guid CameraId, Guid AttemptId, JsonElement JobType,
string? ParametersJson);
private sealed record AnalysisDetection(string Label, float Confidence, float X, float Y,
internal sealed record AnalysisDetection(string Label, float Confidence, float X, float Y,
float Width, float Height, int? ClassIndex);
private sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error,
internal sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error,
IReadOnlyList<AnalysisDetection> Detections);
}
@@ -102,6 +102,8 @@ public sealed class CameraConfigStore
"rtsp" => existing with { RtspUrl = value },
"sub_rtsp" => existing with { SubRtspUrl = value },
"enabled" => existing with { Enabled = ParseBool(value) },
"recording_enabled" => existing with { RecordingEnabled = ParseBool(value) },
"event_recording_enabled" => existing with { EventRecordingEnabled = ParseBool(value) },
"profile" => existing with { DetectionProfile = ParseProfile(value) },
_ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field))
};
@@ -14,6 +14,7 @@ namespace Heimdall.Agent.Services;
/// </summary>
public sealed class ConfigReceiverService : BackgroundService
{
private const int CameraConfigAckMaxAttempts = 3;
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly ILogger<ConfigReceiverService> _logger;
@@ -374,11 +375,10 @@ public sealed class ConfigReceiverService : BackgroundService
// arrives — even if it is empty, drop the local fallback.
_cameraStore.MarkCentralReceived();
using var ack = await http.PostAsJsonAsync(
$"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack",
new { version }, ct).ConfigureAwait(false);
if (!ack.IsSuccessStatusCode)
_logger.LogWarning("Camera configuration ACK was rejected: {StatusCode}", ack.StatusCode);
var acknowledged = await AcknowledgeCameraConfigurationAsync(http, version, ct).ConfigureAwait(false);
if (!acknowledged)
_logger.LogWarning("Camera configuration ACK could not be persisted after {Attempts} attempts",
CameraConfigAckMaxAttempts);
}
catch (Exception ex)
{
@@ -386,6 +386,38 @@ public sealed class ConfigReceiverService : BackgroundService
}
finally { _reloadLock.Release(); }
}
private async Task<bool> AcknowledgeCameraConfigurationAsync(HttpClient http, string version, CancellationToken ct)
{
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack";
for (var attempt = 1; attempt <= CameraConfigAckMaxAttempts; attempt++)
{
try
{
using var response = await http.PostAsJsonAsync(url, new { version }, ct).ConfigureAwait(false);
if (response.IsSuccessStatusCode) return true;
_logger.LogWarning("Camera configuration ACK attempt {Attempt} was rejected with HTTP {StatusCode}",
attempt, (int)response.StatusCode);
if (response.StatusCode is not (System.Net.HttpStatusCode.RequestTimeout or
System.Net.HttpStatusCode.TooManyRequests) && (int)response.StatusCode < 500)
return false;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException)
{
_logger.LogWarning("Camera configuration ACK attempt {Attempt} failed ({ErrorType})",
attempt, ex.GetType().Name);
}
if (attempt < CameraConfigAckMaxAttempts)
await Task.Delay(TimeSpan.FromMilliseconds(250 * attempt), ct).ConfigureAwait(false);
}
return false;
}
}
/// <summary>
@@ -46,6 +46,8 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
private readonly AgentState _state;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<DetectionReporterService> _logger;
private readonly CameraConfigStore? _cameras;
private readonly RecordingTriggerStore? _recordingTriggers;
private readonly string _databasePath;
private readonly PooledDbContextFactory<AgentEventsDbContext> _contextFactory;
private readonly ConcurrentDictionary<(Guid CameraId, EventType Type), DateTime> _lastQueued = new();
@@ -72,10 +74,23 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
IHttpClientFactory httpClientFactory,
ILogger<DetectionReporterService> logger,
IOptions<AgentOptions> options)
: this(state, httpClientFactory, logger, options, null, null)
{
}
public DetectionReporterService(
AgentState state,
IHttpClientFactory httpClientFactory,
ILogger<DetectionReporterService> logger,
IOptions<AgentOptions> options,
CameraConfigStore? cameras,
RecordingTriggerStore? recordingTriggers)
{
_state = state;
_httpClientFactory = httpClientFactory;
_logger = logger;
_cameras = cameras;
_recordingTriggers = recordingTriggers;
var stateDirectory = options.Value.StateDirectory
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
_databasePath = Path.Combine(stateDirectory, "agent-events.db");
@@ -114,6 +129,24 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
cameraId, type, confidence, label, metadataJson, occurredAt ?? now, eventId ?? Guid.NewGuid());
try
{
// Persist the capture request as soon as the qualifying event is observed.
// The durable HTTP outbox can reject a report (or the process can stop
// before the outbox transaction); recording must not depend on delivery.
if (ShouldTriggerRecording(type) && _cameras?.Cameras.Any(camera =>
camera.CameraId == cameraId && camera.EventRecordingEnabled) == true && _recordingTriggers is not null)
{
try
{
await _recordingTriggers.RegisterAsync(cameraId, request.OccurredAt ?? now, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception ex)
{
_logger.LogWarning("Could not persist event recording trigger for camera {CameraId} (error type {ErrorType})",
cameraId, ex.GetType().Name);
}
}
var queued = await EnqueueAsync(request, snapshotJpeg, ct).ConfigureAwait(false);
if (!queued)
return false;
@@ -438,6 +471,10 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
or System.Net.HttpStatusCode.Gone
or System.Net.HttpStatusCode.UnprocessableEntity;
private static bool ShouldTriggerRecording(EventType type) => type is
EventType.MotionDetected or EventType.PersonDetected or EventType.VehicleDetected or
EventType.UnknownPerson or EventType.FaceRecognized or EventType.LicensePlateDetected;
/// <summary>Map a detection label to its event category.</summary>
public static EventType? MapDetectionToEventType(string label)
{
@@ -53,26 +53,37 @@ public sealed class DockerUpdateService : BackgroundService
_options.UpdatePublicKeyPath, _options.UpdatePublicKeyPem);
if (!string.Equals(signed.Version, release.Version, StringComparison.Ordinal) ||
!string.Equals(signed.ContainerImage, release.ContainerImage, StringComparison.Ordinal) ||
!string.Equals(signed.ContainerImageDigest, release.ContainerImageDigest, StringComparison.OrdinalIgnoreCase))
!string.Equals(signed.ContainerImageDigest, release.ContainerImageDigest, StringComparison.OrdinalIgnoreCase) ||
!string.Equals(signed.ContainerImageGpu, release.ContainerImageGpu, StringComparison.Ordinal) ||
!string.Equals(signed.ContainerImageGpuDigest, release.ContainerImageGpuDigest, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("Docker image differs from the signed release manifest");
var latest = release.Version;
var current = _options.Version;
if (!IsNewerVersion(current, latest)) { _logger.LogInformation("Up to date ({V})", current); return; }
_logger.LogInformation("Update available: {C} -> {A}", current, latest);
if (!IsSha256Digest(release.ContainerImageDigest))
var useCudaImage = string.Equals(_options.InferenceExecutionProvider, "CUDA", StringComparison.OrdinalIgnoreCase);
if (useCudaImage && (string.IsNullOrWhiteSpace(release.ContainerImageGpu) ||
!IsSha256Digest(release.ContainerImageGpuDigest)))
{
_logger.LogWarning("Release does not provide a signed CUDA Agent image; leaving the current GPU Agent unchanged");
return;
}
var selectedDigest = useCudaImage ? release.ContainerImageGpuDigest : release.ContainerImageDigest;
var selectedImage = useCudaImage ? release.ContainerImageGpu : release.ContainerImage;
if (!IsSha256Digest(selectedDigest))
{
_logger.LogError("Update manifest has no valid immutable agent image digest; refusing tag-based update");
return;
}
var cid = info.ContainerId;
if (string.IsNullOrEmpty(cid)) return;
var image = release.ContainerImage;
var image = selectedImage;
if (image is null || !IsValidImageRepository(image))
{
_logger.LogError("Update manifest has no valid agent image repository; refusing update");
return;
}
var full = image + "@" + release.ContainerImageDigest;
var full = image + "@" + selectedDigest;
_logger.LogInformation("Pulling {Image}...", full);
var (pe, po) = await RunDocker(["pull", full], ct);
if (pe != 0) { _logger.LogError("docker pull failed: {O}", po); return; }
@@ -254,6 +265,8 @@ public sealed class DockerUpdateService : BackgroundService
[JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; init; }
[JsonPropertyName("containerImage")] public string? ContainerImage { get; init; }
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; }
[JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; init; }
[JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; init; }
[JsonPropertyName("signedManifest")] public string? SignedManifest { get; init; }
[JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; init; }
}
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using ImageMagick;
using OnnxSessionOptions = Microsoft.ML.OnnxRuntime.SessionOptions;
namespace Heimdall.Agent.Services;
@@ -50,7 +51,8 @@ public sealed class FrameAnalyzerService : IDisposable
private long _rejectedFrames;
public long RejectedFrames => Interlocked.Read(ref _rejectedFrames);
public bool ModelAvailable => _modelLoaded;
public string ExecutionProvider => "CPUExecutionProvider";
private string _executionProvider = OnnxExecutionProviderSelection.CpuProviderName;
public string ExecutionProvider => _executionProvider;
private readonly CircuitBreaker? _circuitBreaker;
private readonly PipelineDegradationManager? _degradationManager;
@@ -109,7 +111,8 @@ public sealed class FrameAnalyzerService : IDisposable
PipelineDegradationManager? degradationManager) : this(logger, circuitBreaker, degradationManager, null) { }
internal FrameAnalyzerService(ILogger<FrameAnalyzerService> logger, CircuitBreaker? circuitBreaker,
PipelineDegradationManager? degradationManager, Func<byte[], float, DetectionResult[]>? inference, string? modelPath = null)
PipelineDegradationManager? degradationManager, Func<byte[], float, DetectionResult[]>? inference,
string? modelPath = null, string inferenceExecutionProvider = "CPU", bool cudaDeviceAvailable = true)
{
_testInference = inference;
_logger = logger;
@@ -122,13 +125,7 @@ public sealed class FrameAnalyzerService : IDisposable
{
try
{
using var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions
{
InterOpNumThreads = 1,
IntraOpNumThreads = 2, // spec §16: limit CPU threads for agent
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
};
_session = new InferenceSession(_modelPath, sessionOptions);
_session = CreateSession(_modelPath, inferenceExecutionProvider, cudaDeviceAvailable, out _executionProvider);
_inputName = _session.InputMetadata.Keys.Single();
var input = _session.InputMetadata[_inputName];
var output = _session.OutputMetadata.Values.Single();
@@ -142,8 +139,8 @@ public sealed class FrameAnalyzerService : IDisposable
_numClasses = outputMeta.Dimensions.Length >= 2 ? outputMeta.Dimensions[1] - 4 : 80;
_logger.LogInformation(
"FrameAnalyzer initialized with model: {ModelPath} (input: {InputName}, classes: {Classes})",
_modelPath, _inputName, _numClasses);
"FrameAnalyzer initialized with model: {ModelPath} (input: {InputName}, classes: {Classes}, execution provider: {ExecutionProvider})",
_modelPath, _inputName, _numClasses, _executionProvider);
}
catch (Exception ex)
{
@@ -169,6 +166,43 @@ public sealed class FrameAnalyzerService : IDisposable
_processingLoop = Task.Run(() => ProcessingLoopAsync(_cts.Token));
}
private InferenceSession CreateSession(string modelPath, string requestedProvider, bool cudaDeviceAvailable, out string actualProvider)
{
// Do not initialize/enumerate native CUDA providers when hardware detection
// says no NVIDIA device is attached; some ORT GPU builds can fault inside
// native provider discovery before managed fallback handling is possible.
var availableProviders = cudaDeviceAvailable
? OrtEnv.Instance().GetAvailableProviders()
: Array.Empty<string>();
return OnnxExecutionProviderSelection.CreateSession(
requestedProvider,
availableProviders,
() =>
{
using var options = OnnxSessionOptions.MakeSessionOptionWithCudaProvider(0);
ConfigureSessionOptions(options);
return new InferenceSession(modelPath, options);
},
() =>
{
using var options = new OnnxSessionOptions();
ConfigureSessionOptions(options);
return new InferenceSession(modelPath, options);
},
reason => _logger.LogWarning(
"CUDA ONNX execution provider could not be used ({Reason}); falling back to CPU",
reason),
out actualProvider,
cudaDeviceAvailable);
}
private static void ConfigureSessionOptions(OnnxSessionOptions options)
{
options.InterOpNumThreads = 1;
options.IntraOpNumThreads = 2; // Limit CPU threads for Agent even when CUDA is preferred.
options.GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL;
}
/// <summary>
/// Submit a JPEG frame for analysis. Returns a task that completes when
/// analysis is done. If the queue is full, explicitly rejects the new frame.
@@ -0,0 +1,121 @@
using System.Diagnostics;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
/// <summary>Re-publishes assigned primary streams to the configured Central MediaMTX.</summary>
public sealed class LiveCameraRelayService(
AgentState state,
IOptions<AgentOptions> options,
CameraConfigStore cameras,
IHttpClientFactory clients,
ILogger<LiveCameraRelayService> logger) : BackgroundService
{
private const int MaxPublishers = 2;
private readonly Dictionary<Guid, Relay> _relays = [];
private readonly Dictionary<Guid, DateTimeOffset> _retryAt = [];
private sealed record Relay(Process Process, DateTimeOffset RenewAt);
private sealed record PublishSession(string Url, DateTimeOffset RenewAt);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
while (!stoppingToken.IsCancellationRequested)
{
try { await SynchronizeAsync(stoppingToken); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
catch (Exception ex) { logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); }
try { await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
}
}
finally { await StopAllAsync(); }
}
private async Task SynchronizeAsync(CancellationToken ct)
{
var assigned = SelectAssignedCameras(cameras);
foreach (var id in _relays.Keys.Where(id => !assigned.ContainsKey(id)).ToArray())
await StopAsync(id);
foreach (var camera in assigned.Values)
{
if (_relays.TryGetValue(camera.CameraId, out var relay) && !relay.Process.HasExited &&
relay.RenewAt > DateTimeOffset.UtcNow) continue;
await StopAsync(camera.CameraId);
if (state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(state.ApiKey) ||
_retryAt.GetValueOrDefault(camera.CameraId) > DateTimeOffset.UtcNow) continue;
if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = DateTimeOffset.UtcNow.AddSeconds(20);
}
}
internal static IReadOnlyDictionary<Guid, AgentCameraConfig> SelectAssignedCameras(CameraConfigStore cameras) =>
cameras.HasCentralConfiguration
? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.RtspUrl))
.Take(MaxPublishers).ToDictionary(c => c.CameraId)
: new Dictionary<Guid, AgentCameraConfig>();
private static bool IsRtspSource(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) &&
(uri.Scheme.Equals("rtsp", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("rtsps", StringComparison.OrdinalIgnoreCase));
private async Task<bool> StartAsync(AgentCameraConfig camera, CancellationToken ct)
{
var client = clients.CreateClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", state.ApiKey);
using var response = await client.PostAsync(
$"{options.Value.CentralUrl.TrimEnd('/')}/api/live-media/agents/{state.AgentId:D}/cameras/{camera.CameraId:D}/publish-session",
content: null, ct);
if (!response.IsSuccessStatusCode) return false;
var session = await response.Content.ReadFromJsonAsync<PublishSession>(cancellationToken: ct);
if (session is null || !Uri.TryCreate(session.Url, UriKind.Absolute, out var destination)) return false;
var start = CreateStartInfo("ffmpeg", camera.RtspUrl, destination);
try
{
var process = Process.Start(start);
if (process is null) return false;
_ = DrainErrorsAsync(process);
_relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30));
logger.LogInformation("Live relay started for camera {CameraId}", camera.CameraId);
return true;
}
catch (Exception ex) { logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; }
}
internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string source, Uri destination)
{
var start = new ProcessStartInfo { FileName = ffmpegPath, UseShellExecute = false,
RedirectStandardError = true, RedirectStandardOutput = false, CreateNoWindow = true };
foreach (var arg in new[] { "-nostdin", "-hide_banner", "-loglevel", "error", "-fflags", "nobuffer", "-flags", "low_delay", "-rtsp_transport", "tcp", "-i", source,
"-map", "0:v:0", "-map", "0:a:0?", "-c:v", "copy", "-c:a", "libopus", "-b:a", "64k", "-f", "rtsp", "-rtsp_transport", "tcp", destination.ToString() })
start.ArgumentList.Add(arg);
return start;
}
private static async Task DrainErrorsAsync(Process process)
{
try { while (await process.StandardError.ReadLineAsync() is not null) { } }
catch (IOException) { }
}
private async Task StopAsync(Guid cameraId)
{
if (!_relays.Remove(cameraId, out var relay)) return;
try
{
if (!relay.Process.HasExited) relay.Process.Kill(entireProcessTree: true);
await relay.Process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3));
}
catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or TimeoutException)
{ logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); }
finally { relay.Process.Dispose(); }
}
private async Task StopAllAsync()
{
foreach (var cameraId in _relays.Keys.ToArray()) await StopAsync(cameraId);
}
}
@@ -16,6 +16,17 @@ namespace Heimdall.Agent.Services;
/// </summary>
public class LogUploadService : BackgroundService
{
internal static string ToCentralLevel(LogLevel level) => level switch
{
LogLevel.Trace => "Trace",
LogLevel.Debug => "Debug",
LogLevel.Information => "Information",
LogLevel.Warning => "Warning",
LogLevel.Error => "Error",
LogLevel.Critical => "Critical",
_ => "Info"
};
private readonly IHttpClientFactory _httpClientFactory;
private readonly LogBufferService _buffer;
private readonly AgentState _state;
@@ -73,7 +84,7 @@ public class LogUploadService : BackgroundService
entries = entries.Select(e => new
{
timestampUtc = e.TimestampUtc,
level = e.Level.ToString(),
level = ToCentralLevel(e.Level),
message = e.Message,
exception = e.Exception,
source = e.Source
@@ -0,0 +1,61 @@
using ImageMagick;
namespace Heimdall.Agent.Services;
/// <summary>Compares two nearby frames at low resolution to detect temporal pixel changes.</summary>
internal static class MotionDetectionAnalyzer
{
private const int Width = 32;
private const int Height = 18;
private const double PixelDifferenceThreshold = 0.12;
private const double ChangedPixelRatioThreshold = 0.02;
public static DetectionResult[] Compare(byte[] previousJpeg, byte[] currentJpeg)
{
using var previous = Decode(previousJpeg);
using var current = Decode(currentJpeg);
using var previousPixels = previous.GetPixels();
using var currentPixels = current.GetPixels();
var changed = 0;
var minX = Width;
var minY = Height;
var maxX = -1;
var maxY = -1;
for (var y = 0; y < Height; y++)
for (var x = 0; x < Width; x++)
{
var before = Luminance(previousPixels.GetPixel(x, y).ToColor()!);
var after = Luminance(currentPixels.GetPixel(x, y).ToColor()!);
if (Math.Abs(after - before) < PixelDifferenceThreshold) continue;
changed++;
minX = Math.Min(minX, x);
minY = Math.Min(minY, y);
maxX = Math.Max(maxX, x);
maxY = Math.Max(maxY, y);
}
var ratio = changed / (double)(Width * Height);
if (ratio < ChangedPixelRatioThreshold || maxX < minX || maxY < minY)
return [];
return
[
new DetectionResult("motion", (float)Math.Clamp(ratio, 0, 1),
minX / (float)Width, minY / (float)Height,
(maxX - minX + 1) / (float)Width, (maxY - minY + 1) / (float)Height)
];
}
private static MagickImage Decode(byte[] jpeg)
{
var image = new MagickImage(jpeg);
image.Resize(new MagickGeometry(Width, Height) { IgnoreAspectRatio = true });
image.ColorSpace = ColorSpace.RGB;
return image;
}
private static double Luminance(IMagickColor<ushort> color) =>
(0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / ushort.MaxValue;
}
@@ -265,7 +265,7 @@ public NetworkCameraScanner(
/// are kept; the HomeKit* fields of the device are filled for the Central
/// ClassifyAgentDevice HomeKit path.
/// </summary>
private async Task<List<AgentDiscoveredDevice>> DiscoverHomeKitAsync(CancellationToken ct)
internal async Task<List<AgentDiscoveredDevice>> DiscoverHomeKitAsync(CancellationToken ct)
{
var devices = new List<AgentDiscoveredDevice>();
try
@@ -0,0 +1,56 @@
namespace Heimdall.Agent.Services;
/// <summary>Builds an ONNX session using the requested provider when the runtime can attach it, otherwise using CPU.</summary>
internal static class OnnxExecutionProviderSelection
{
public const string CpuProviderName = "CPUExecutionProvider";
public const string CudaProviderName = "CUDAExecutionProvider";
public static TSession CreateSession<TSession>(
string requestedProvider,
IReadOnlyCollection<string> availableProviders,
Func<TSession> createCudaSession,
Func<TSession> createCpuSession,
Action<string> reportFallback,
out string actualProvider,
bool cudaDeviceAvailable = true)
where TSession : class
{
ArgumentNullException.ThrowIfNull(availableProviders);
ArgumentNullException.ThrowIfNull(createCudaSession);
ArgumentNullException.ThrowIfNull(createCpuSession);
ArgumentNullException.ThrowIfNull(reportFallback);
if (string.Equals(requestedProvider, "CUDA", StringComparison.OrdinalIgnoreCase))
{
if (!cudaDeviceAvailable)
{
reportFallback("No NVIDIA CUDA device was detected by the Agent");
}
else if (availableProviders.Contains(CudaProviderName, StringComparer.Ordinal))
{
try
{
var cudaSession = createCudaSession();
if (cudaSession is not null)
{
actualProvider = CudaProviderName;
return cudaSession;
}
reportFallback("CUDA session creation returned no session");
}
catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException)
{
reportFallback(ex.GetType().Name);
}
}
else
{
reportFallback("CUDAExecutionProvider is not registered in this ONNX Runtime build");
}
}
actualProvider = CpuProviderName;
return createCpuSession();
}
}
@@ -0,0 +1,122 @@
using System.Text.Json;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
/// <summary>Durable, bounded post-event windows used to start event-only recording after Agent restarts.</summary>
public sealed class RecordingTriggerStore : IDisposable
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private readonly string _root;
private readonly TimeSpan _postRoll;
private readonly SemaphoreSlim _gate = new(1, 1);
public RecordingTriggerStore(IOptions<AgentOptions> options)
{
var stateDirectory = options.Value.StateDirectory ??
(OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
_root = Path.GetFullPath(Path.Combine(stateDirectory, "recording-triggers"));
_postRoll = TimeSpan.FromSeconds(options.Value.RecordingEventPostRollSeconds);
}
public async Task RegisterAsync(Guid cameraId, DateTime occurredAt, CancellationToken ct = default)
{
if (cameraId == Guid.Empty) throw new ArgumentException("Camera ID is required", nameof(cameraId));
var normalizedOccurredAt = CameraEvent.NormalizeOccurredAt(occurredAt);
var directory = Path.Combine(_root, cameraId.ToString("N"));
var path = Path.Combine(directory, "trigger.json");
var temporaryPath = Path.Combine(directory, "trigger.json.tmp");
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
Directory.CreateDirectory(directory);
if (OperatingSystem.IsLinux())
{
File.SetUnixFileMode(_root, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
File.SetUnixFileMode(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
var previous = await ReadTriggerAsync(path, ct).ConfigureAwait(false);
var trigger = new RecordingTrigger(
previous is { } existing && existing.ExpiresAtUtc > DateTime.UtcNow
? Min(existing.OccurredAtUtc, normalizedOccurredAt)
: normalizedOccurredAt,
DateTime.UtcNow.Add(_postRoll));
await using (var stream = new FileStream(temporaryPath, FileMode.Create, FileAccess.Write,
FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.WriteThrough))
await JsonSerializer.SerializeAsync(stream, trigger, Json, ct).ConfigureAwait(false);
File.Move(temporaryPath, path, overwrite: true);
}
finally
{
if (File.Exists(temporaryPath)) File.Delete(temporaryPath);
_gate.Release();
}
}
public async Task<RecordingTriggerStatus> GetStatusAsync(Guid cameraId, CancellationToken ct = default)
{
var directory = Path.Combine(_root, cameraId.ToString("N"));
if (!Directory.Exists(directory)) return RecordingTriggerStatus.Inactive;
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var now = DateTime.UtcNow;
var path = Path.Combine(directory, "trigger.json");
var trigger = await ReadTriggerAsync(path, ct).ConfigureAwait(false);
if (trigger is null || trigger.ExpiresAtUtc <= now)
{
try { File.Delete(path); }
catch (IOException) { }
return RecordingTriggerStatus.Inactive;
}
return new RecordingTriggerStatus(trigger.OccurredAtUtc, trigger.ExpiresAtUtc);
}
finally { _gate.Release(); }
}
private static async Task<RecordingTrigger?> ReadTriggerAsync(string path, CancellationToken ct)
{
if (!File.Exists(path)) return null;
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
4096, FileOptions.Asynchronous | FileOptions.SequentialScan);
return await JsonSerializer.DeserializeAsync<RecordingTrigger>(stream, Json, ct).ConfigureAwait(false);
}
catch (JsonException) { return null; }
catch (IOException) { return null; }
}
private static DateTime Min(DateTime left, DateTime right) => left <= right ? left : right;
public async Task ClearExceptAsync(IReadOnlySet<Guid> enabledCameraIds, CancellationToken ct = default)
{
if (!Directory.Exists(_root)) return;
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
foreach (var directory in Directory.EnumerateDirectories(_root))
{
ct.ThrowIfCancellationRequested();
if (Guid.TryParseExact(Path.GetFileName(directory), "N", out var cameraId) &&
enabledCameraIds.Contains(cameraId)) continue;
try { Directory.Delete(directory, recursive: true); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
}
finally { _gate.Release(); }
}
public sealed record RecordingTriggerStatus(DateTime? FirstTriggeredAtUtc, DateTime? ActiveUntilUtc)
{
public static RecordingTriggerStatus Inactive { get; } = new(null, null);
public bool IsActive => ActiveUntilUtc is { } activeUntil && activeUntil > DateTime.UtcNow;
}
private sealed record RecordingTrigger(DateTime OccurredAtUtc, DateTime ExpiresAtUtc);
public void Dispose() => _gate.Dispose();
}
@@ -45,7 +45,11 @@ internal static class ReleaseSignatureVerifier
release.Assets.Any(x => string.IsNullOrWhiteSpace(x.Key) || !IsSha256(x.Value)) ||
string.IsNullOrWhiteSpace(release.ContainerImage) ||
release.ContainerImage.Contains('@') ||
!IsImageDigest(release.ContainerImageDigest))
!IsImageDigest(release.ContainerImageDigest) ||
((release.ContainerImageGpu is null) != (release.ContainerImageGpuDigest is null)) ||
(release.ContainerImageGpu is not null &&
(string.IsNullOrWhiteSpace(release.ContainerImageGpu) || release.ContainerImageGpu.Contains('@') ||
!IsImageDigest(release.ContainerImageGpuDigest))))
throw new InvalidOperationException("Signed release manifest is incomplete");
return release;
}
@@ -62,4 +66,6 @@ internal sealed class SignedAgentRelease
[JsonPropertyName("assets")] public Dictionary<string, string> Assets { get; init; } = [];
[JsonPropertyName("containerImage")] public string? ContainerImage { get; init; }
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; }
[JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; init; }
[JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; init; }
}
+2 -1
View File
@@ -11,7 +11,8 @@
"SiteToken": "",
"AgentName": "",
"HeartbeatIntervalSeconds": 30,
"RegistrationMaxRetries": 5
"RegistrationMaxRetries": 5,
"InferenceExecutionProvider": "CPU"
},
// Sentry/GlitchTip — DSN is read from Sentry:Dsn (or env Sentry__Dsn / legacy SENTRY_DSN)
// When null/empty, Sentry SDK is not initialized (graceful no-op).
+394
View File
@@ -0,0 +1,394 @@
{
"version": 1,
"dependencies": {
"net10.0": {
"Magick.NET-Q16-AnyCPU": {
"type": "Direct",
"requested": "[14.16.0, )",
"resolved": "14.16.0",
"contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==",
"dependencies": {
"Magick.NET.Core": "14.16.0"
}
},
"Microsoft.AspNetCore.SignalR.Client": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "17fMUI5gkRwR9qXXTELd5OChcFn3lkgWpiblaaELQ45zOL7VuU7HJYAYnMk+Irjf2jpRxHT7b0imy+NVIFyoYQ==",
"dependencies": {
"Microsoft.AspNetCore.Http.Connections.Client": "10.0.13",
"Microsoft.AspNetCore.SignalR.Client.Core": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Hosting.WindowsServices": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "sk3VNcYEmgwYGPF4ze/112jpaeDKSsKGhmEZ8IlhOR8F6JT+1DYaZUb14jobVXiKhuXWIKcYXV7mkSPeA4dc3g==",
"dependencies": {
"System.ServiceProcess.ServiceController": "10.0.13"
}
},
"Microsoft.ML.OnnxRuntime.Gpu": {
"type": "Direct",
"requested": "[1.22.0, )",
"resolved": "1.22.0",
"contentHash": "3Fg/O8sSwty6fCVg7pl2Xk1ROXiJOCOKr+8dQWNh8v1Be16RyF/PHugNSncasCb1yts5zB1jk4Ci+Q66I+ge4w==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Gpu.Linux": "1.22.0",
"Microsoft.ML.OnnxRuntime.Gpu.Windows": "1.22.0",
"Microsoft.ML.OnnxRuntime.Managed": "1.22.0"
}
},
"OpenTelemetry": {
"type": "Direct",
"requested": "[1.17.0, )",
"resolved": "1.17.0",
"contentHash": "rMLOTftlMlTm7+MSrvXDHnJRjVkROFNKXHZrYjOsX+LankaFG7QSflx7qRRGjoqZoirohnxmJQ7GEb9occO4Gg==",
"dependencies": {
"OpenTelemetry.Api.ProviderBuilderExtensions": "1.17.0"
}
},
"OpenTelemetry.Exporter.Prometheus.AspNetCore": {
"type": "Direct",
"requested": "[1.17.0-beta.1, )",
"resolved": "1.17.0-beta.1",
"contentHash": "eecXu43HkY7LFJDutrQ6kpwvUOMDeqLMtU+UeN225ckXw33qN/StTcdW6mTHH1jDSYdFM29vvDXB3jnFwPHkXg==",
"dependencies": {
"OpenTelemetry": "[1.17.0, 2.0.0)"
}
},
"OpenTelemetry.Extensions.Hosting": {
"type": "Direct",
"requested": "[1.17.0, )",
"resolved": "1.17.0",
"contentHash": "t1OwL/4qgboGMobYVT+UV5zgWnFqCp4Pw8lcsmzh8m2K8PQsTKkyxrC32tqYTMYny3GOW4q5cltE3dTVzLmRew==",
"dependencies": {
"OpenTelemetry": "1.17.0"
}
},
"Sentry.AspNetCore": {
"type": "Direct",
"requested": "[6.8.0, )",
"resolved": "6.8.0",
"contentHash": "yo9TeFZPgmhyu0Vj+Zq3VxRR8kDbhlNbRAQDANN+gTwETe5uDa/H1I91PntBD7jwhWa7P218bYU+LGYOipylYA==",
"dependencies": {
"Sentry.Extensions.Logging": "6.8.0"
}
},
"AutoMapper": {
"type": "Transitive",
"resolved": "16.1.1",
"contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==",
"dependencies": {
"Microsoft.IdentityModel.JsonWebTokens": "8.14.0"
}
},
"FluentValidation": {
"type": "Transitive",
"resolved": "11.11.0",
"contentHash": "cyIVdQBwSipxWG8MA3Rqox7iNbUNUTK5bfJi9tIdm4CAfH71Oo5ABLP4/QyrUwuakqpUEPGtE43BDddvEehuYw=="
},
"FluentValidation.DependencyInjectionExtensions": {
"type": "Transitive",
"resolved": "11.11.0",
"contentHash": "viTKWaMbL3yJYgGI0DiCeavNbE9UPMWFVK2XS9nYXGbm3NDMd0/L5ER4wBzmTtW3BYh3SrlSXm9RACiKZ6stlA==",
"dependencies": {
"FluentValidation": "11.11.0"
}
},
"Magick.NET.Core": {
"type": "Transitive",
"resolved": "14.16.0",
"contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ=="
},
"MediatR": {
"type": "Transitive",
"resolved": "12.5.0",
"contentHash": "vqm2H8/nqL5NAJHPhsG1JOPwfkmbVrPyh4svdoRzu+uZh6Ex7PRoHBGsLYC0/RWCEJFqD1ohHNpteQvql9OktA==",
"dependencies": {
"MediatR.Contracts": "[2.0.1, 3.0.0)"
}
},
"MediatR.Contracts": {
"type": "Transitive",
"resolved": "2.0.1",
"contentHash": "FYv95bNT4UwcNA+G/J1oX5OpRiSUxteXaUt2BJbRSdRNiIUNbggJF69wy6mnk2wYToaanpdXZdCwVylt96MpwQ=="
},
"Microsoft.AspNetCore.Http.Connections.Client": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "r9hlU+te+QWFJlUCt2C22TDKY3oMER8ayC7Qzeq6yJ5toHBKcSqshhyyaLKK1jgBuyNi4ejly0wE8ANV8TyfWQ=="
},
"Microsoft.AspNetCore.SignalR.Client.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zfCQ0/J/rATKKcpwcpQYFz8sxhvrzgGyblsATcfxqSCibRkPFmDZcFmfD0UfLi38q+VDMpwEVuzOCO3TpRy99Q=="
},
"Microsoft.Data.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "w37nz3WFmDtRfXxWEwIXX2OgqDRiwhD1JGbFwfpFCF8GkCrV/yO6Y2JF5058J2RGoI2sCcdn02wrk0yEcekWcw==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "Gge8XsSCOwcbkbdmt2UDAe6kIv9Q0vA6yb3wsTStjjexaMFLTWfc/1gH4kbhJ+zWiXRTRA4lG2sOQNVfir204w==",
"dependencies": {
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.EntityFrameworkCore": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "u/z4nTQUJ5nJEXAQekgQEQZkh0delp4gL+ESHn7Z6k037c8HC5mSNu1/YdBgxGm7DtLjhOxktNl+aQMzw6wN7A==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Abstractions": "10.0.13",
"Microsoft.EntityFrameworkCore.Analyzers": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "ARw+tZ3eiTosnK5nJPUGEzeUQcjyqCqs3qKA3lPtIRH5yJo3qIgxm7AvkZVIT9iWkS2083UsWe3Rj1MysW3p5A=="
},
"Microsoft.EntityFrameworkCore.Analyzers": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zBx6VeEz/hkhlm0BJ2V+9xebUuDDIszcKvurJceQHuZPEXuXubrL6Lneo9VZiliRyJbQlB2oNKLkJXd3gHteQA=="
},
"Microsoft.EntityFrameworkCore.Relational": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "QU/sbTtDR5wVAJRVecC1GwM7mwH8bvKOZNm+lulzMr5rhjdb8DDEFIqqdhF08JIo51DPv5uQdZ1nXoZsD5pTag==",
"dependencies": {
"Microsoft.EntityFrameworkCore": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.IdentityModel.Abstractions": {
"type": "Transitive",
"resolved": "8.14.0",
"contentHash": "iwbCpSjD3ehfTwBhtSNEtKPK0ICun6ov7Ibx6ISNA9bfwIyzI2Siwyi9eJFCJBwxowK9xcA1mj+jBWiigeqgcQ=="
},
"Microsoft.IdentityModel.JsonWebTokens": {
"type": "Transitive",
"resolved": "8.14.0",
"contentHash": "4jOpiA4THdtpLyMdAb24dtj7+6GmvhOhxf5XHLYWmPKF8ApEnApal1UnJsKO4HxUWRXDA6C4WQVfYyqsRhpNpQ==",
"dependencies": {
"Microsoft.IdentityModel.Tokens": "8.14.0"
}
},
"Microsoft.IdentityModel.Logging": {
"type": "Transitive",
"resolved": "8.14.0",
"contentHash": "eqqnemdW38CKZEHS6diA50BV94QICozDZEvSrsvN3SJXUFwVB9gy+/oz76gldP7nZliA16IglXjXTCTdmU/Ejg==",
"dependencies": {
"Microsoft.IdentityModel.Abstractions": "8.14.0"
}
},
"Microsoft.IdentityModel.Tokens": {
"type": "Transitive",
"resolved": "8.14.0",
"contentHash": "lKIZiBiGd36k02TCdMHp1KlNWisyIvQxcYJvIkz7P4gSQ9zi8dgh6S5Grj8NNG7HWYIPfQymGyoZ6JB5d1Lo1g==",
"dependencies": {
"Microsoft.IdentityModel.Logging": "8.14.0"
}
},
"Microsoft.ML.OnnxRuntime.Gpu.Linux": {
"type": "Transitive",
"resolved": "1.22.0",
"contentHash": "1llC85TrCC69e18WSBF5rAHnbvwLY9wI+wX8PUpMfQhtSehZlJImMfXoCEdPYTtvLR/5ad/wHG43LwRLSxqp+g==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.22.0"
}
},
"Microsoft.ML.OnnxRuntime.Gpu.Windows": {
"type": "Transitive",
"resolved": "1.22.0",
"contentHash": "vscA3rOmdgyOXeXWMheBC4okYGvoHEK3bOC/RudikJyR3wY4mbiukfUqa94etShJ+YQYA9q35DOz0bxrAOUOKw==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.22.0"
}
},
"Microsoft.ML.OnnxRuntime.Managed": {
"type": "Transitive",
"resolved": "1.22.0",
"contentHash": "zlG3eY5mJnx1BhYAxRwpuHCGHzl3B+cY5/se0RmlVBw6Yh6QTGjPAXdjhlBIcw6BPFhgMn9lxWPE/U3Fvis+BQ==",
"dependencies": {
"System.Numerics.Tensors": "9.0.0"
}
},
"OpenTelemetry.Api": {
"type": "Transitive",
"resolved": "1.17.0",
"contentHash": "mSBxzomZgHIJu9CyVNqyDu/n2JHEtqVgfcCD1Br0cV5iLYogjZOMqhlVLt99PEp+0KGBNUR3GXgeOdN2GR3F9g=="
},
"OpenTelemetry.Api.ProviderBuilderExtensions": {
"type": "Transitive",
"resolved": "1.17.0",
"contentHash": "Xgc3Qf9B9TFMFpx6exTdGqMWuYIT2miNzkdMPutVvT9YuMFaEovXWke1Gb6z8NxYaQbbGF38vYLuSg1JCeui5Q==",
"dependencies": {
"OpenTelemetry.Api": "1.17.0"
}
},
"Sentry": {
"type": "Transitive",
"resolved": "6.8.0",
"contentHash": "amUjwslDtdx1p8r6z4APCxM8vHCKG4CBamPpSTwxmTMoBQ2CLwx2m3CaIttJXRT/hw9S5rNfXgjol2OqADytLQ=="
},
"Sentry.Extensions.Logging": {
"type": "Transitive",
"resolved": "6.8.0",
"contentHash": "K7/Z7B8ec5c61ByzZOgxHxhcT+5yo7X6n7GchcaFI/X44Zn/ZsGqUFMqvypaILnc4JISAeppDTSiWdgWmflzbg==",
"dependencies": {
"Sentry": "6.8.0"
}
},
"SQLite": {
"type": "Transitive",
"resolved": "3.53.4",
"contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw=="
},
"SQLitePCLRaw.bundle_e_sqlite3": {
"type": "Transitive",
"resolved": "3.0.5",
"contentHash": "SW8iASIyWMrLzqabUHYQRvALhvD4ylSBsj4PgEVGwc36kQjc9xT5kSV/XQ9rU7nIpBWD+LPyX3Hlw5FzyUzGeQ==",
"dependencies": {
"SQLite": "3.53.4",
"SQLitePCLRaw.config.e_sqlite3": "3.0.5"
}
},
"SQLitePCLRaw.config.e_sqlite3": {
"type": "Transitive",
"resolved": "3.0.5",
"contentHash": "aSk8WE5tF2MybESMgtZAEyMVCAWA0nBqOMc48HFoa9UoSdtm3goDXVzNRnefeKIwE6bV9NaNXptn1F9ReMQI0Q==",
"dependencies": {
"SQLitePCLRaw.provider.e_sqlite3": "3.0.5"
}
},
"SQLitePCLRaw.core": {
"type": "Transitive",
"resolved": "3.0.5",
"contentHash": "k81AYXXRCw3Zj8rOhyBoCsx/U97KYDFI2CSKr/ijl5BwpsW/hX/4kBiDmerFaoust8nxBwa0IHQFw8MmSHRtnQ=="
},
"SQLitePCLRaw.provider.e_sqlite3": {
"type": "Transitive",
"resolved": "3.0.5",
"contentHash": "um8YSWduhhuskTG2bHfZrBqMNQOydfU8pcseT+cu5RivOGyoUbCrGXxgoRNTmRYw2VbMWnEZVVFcneZT/5dsBg==",
"dependencies": {
"SQLitePCLRaw.core": "3.0.5"
}
},
"System.Numerics.Tensors": {
"type": "Transitive",
"resolved": "9.0.0",
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
},
"System.ServiceProcess.ServiceController": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ=="
},
"heimdall.application": {
"type": "Project",
"dependencies": {
"AutoMapper": "[16.1.1, )",
"FluentValidation": "[11.11.0, )",
"FluentValidation.DependencyInjectionExtensions": "[11.11.0, )",
"Heimdall.Domain": "[1.0.0, )",
"MediatR": "[12.5.0, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
"heimdall.contracts": {
"type": "Project"
},
"heimdall.domain": {
"type": "Project",
"dependencies": {
"Heimdall.Domain.Primitives": "[1.0.0, )"
}
},
"heimdall.domain.primitives": {
"type": "Project"
},
"heimdall.mdns": {
"type": "Project"
}
},
"net10.0/linux-x64": {
"Magick.NET-Q16-AnyCPU": {
"type": "Direct",
"requested": "[14.16.0, )",
"resolved": "14.16.0",
"contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==",
"dependencies": {
"Magick.NET.Core": "14.16.0"
}
},
"Microsoft.ML.OnnxRuntime.Gpu.Linux": {
"type": "Transitive",
"resolved": "1.22.0",
"contentHash": "1llC85TrCC69e18WSBF5rAHnbvwLY9wI+wX8PUpMfQhtSehZlJImMfXoCEdPYTtvLR/5ad/wHG43LwRLSxqp+g==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.22.0"
}
},
"Microsoft.ML.OnnxRuntime.Gpu.Windows": {
"type": "Transitive",
"resolved": "1.22.0",
"contentHash": "vscA3rOmdgyOXeXWMheBC4okYGvoHEK3bOC/RudikJyR3wY4mbiukfUqa94etShJ+YQYA9q35DOz0bxrAOUOKw==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.22.0"
}
},
"SQLite": {
"type": "Transitive",
"resolved": "3.53.4",
"contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw=="
},
"System.ServiceProcess.ServiceController": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ=="
}
}
}
}
@@ -53,5 +53,5 @@ public class CreateCameraCommandHandler : IRequestHandler<CreateCameraCommand, S
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
c.LastDiscoveredAt, c.LastStreamTestAt,
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt, c.RecordingEnabled, c.EventRecordingEnabled);
}
@@ -43,5 +43,5 @@ public class ToggleCameraStatusCommandHandler : IRequestHandler<ToggleCameraStat
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
c.LastDiscoveredAt, c.LastStreamTestAt,
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt, c.RecordingEnabled, c.EventRecordingEnabled);
}
@@ -15,7 +15,9 @@ public record UpdateCameraCommand(
string? Manufacturer = null,
string? Model = null,
DetectionProfileDto? DetectionProfile = null,
Guid? ActorId = null) : IRequest<ServiceResult<CameraResponse>>;
Guid? ActorId = null,
bool? RecordingEnabled = null,
bool? EventRecordingEnabled = null) : IRequest<ServiceResult<CameraResponse>>;
public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, ServiceResult<CameraResponse>>
{
@@ -48,11 +50,17 @@ public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, S
var oldName = camera.Name; var oldManufacturer = camera.Manufacturer; var oldModel = camera.Model;
var oldStatus = camera.Status;
var oldRecordingEnabled = camera.RecordingEnabled;
var oldEventRecordingEnabled = camera.EventRecordingEnabled;
var oldHasRtspUrl = camera.RtspUrl is not null;
camera.Update(request.Name, request.Manufacturer, request.Model, request.RtspUrl);
if (request.Status.HasValue)
camera.SetStatus(request.Status.Value);
if (request.RecordingEnabled.HasValue)
camera.SetRecordingEnabled(request.RecordingEnabled.Value);
if (request.EventRecordingEnabled.HasValue)
camera.SetEventRecordingEnabled(request.EventRecordingEnabled.Value);
_db.AuditLogs.Add(new AuditLog(request.ActorId, "Camera.Updated", "Camera", request.Id.ToString(),
oldValue: JsonSerializer.Serialize(new
@@ -62,6 +70,8 @@ public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, S
Model = oldModel,
Status = oldStatus,
HasRtspUrl = oldHasRtspUrl,
RecordingEnabled = oldRecordingEnabled,
EventRecordingEnabled = oldEventRecordingEnabled,
DetectionProfile = oldDetectionProfileJson
}),
newValue: JsonSerializer.Serialize(new
@@ -71,6 +81,8 @@ public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, S
camera.Model,
camera.Status,
HasRtspUrl = camera.RtspUrl is not null,
camera.RecordingEnabled,
camera.EventRecordingEnabled,
DetectionProfile = newDetectionProfileJson
})));
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
@@ -85,5 +97,5 @@ public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, S
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
c.LastDiscoveredAt, c.LastStreamTestAt,
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt, c.RecordingEnabled, c.EventRecordingEnabled);
}
@@ -43,5 +43,5 @@ public class GetCameraQueryHandler : IRequestHandler<GetCameraQuery, ServiceResu
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
c.LastDiscoveredAt, c.LastStreamTestAt,
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
}
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt, c.RecordingEnabled, c.EventRecordingEnabled);
}
@@ -57,5 +57,5 @@ public class GetCamerasBySiteQueryHandler : IRequestHandler<GetCamerasBySiteQuer
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
c.LastDiscoveredAt, c.LastStreamTestAt,
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt, c.RecordingEnabled, c.EventRecordingEnabled);
}
@@ -0,0 +1,14 @@
namespace Heimdall.Application.Common;
/// <summary>Serializes recording usage checks across cameras and exposes the validated Central quota.</summary>
public interface IRecordingQuotaGuard
{
long MaxStorageBytes { get; }
Task<IRecordingQuotaLease> AcquireAsync(CancellationToken ct = default);
}
/// <summary>A short-lived database transaction holding the global recording quota lock.</summary>
public interface IRecordingQuotaLease : IAsyncDisposable
{
Task CommitAsync(CancellationToken ct = default);
}
@@ -0,0 +1,13 @@
using Heimdall.Domain.Entities;
namespace Heimdall.Application.Common;
/// <summary>Storage operations for recording media, bound to the captured destination.</summary>
public interface IRecordingStorage
{
StorageLocation CaptureCurrentLocation();
Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, CancellationToken ct = default);
Task<Stream?> DownloadAsync(string key, StorageLocation location, CancellationToken ct = default);
Task<Stream?> DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive,
CancellationToken ct = default);
}
@@ -20,6 +20,9 @@ public interface IStorageProvider
/// <summary>Open a stream for reading a stored object. Null when missing.</summary>
Task<Stream?> DownloadAsync(string key, CancellationToken ct = default);
/// <summary>Open a single inclusive byte range without downloading the rest of the object.</summary>
Task<Stream?> DownloadRangeAsync(string key, long start, long endInclusive, CancellationToken ct = default);
/// <summary>Delete a single object. No-op when missing.</summary>
Task DeleteAsync(string key, CancellationToken ct = default);
+6 -2
View File
@@ -15,7 +15,9 @@ public record UpdateCameraRequest(
CameraStatus? Status,
string? Manufacturer = null,
string? Model = null,
DetectionProfileDto? DetectionProfile = null);
DetectionProfileDto? DetectionProfile = null,
bool? RecordingEnabled = null,
bool? EventRecordingEnabled = null);
/// <summary>Camera response including all discovery and stream test metadata.</summary>
public record CameraResponse(
@@ -45,4 +47,6 @@ public record CameraResponse(
bool HasPtz,
bool HasAudio,
bool HasMotionDetection,
DateTime CreatedAt);
DateTime CreatedAt,
bool RecordingEnabled = false,
bool EventRecordingEnabled = false);
+1 -1
View File
@@ -1,6 +1,6 @@
namespace Heimdall.Application.DTOs;
public record CreateSiteRequest(string Name, string? Address, string? Timezone);
public record CreateSiteRequest(string Name, string? Address, string? Timezone, string? NtfyTopic = null);
public record UpdateSiteRequest(string Name, string? Address, string? Timezone, string? NtfyTopic = null, bool? AutoUpdateEnabled = null);
@@ -62,6 +62,17 @@ public class CreateEventHandler : IRequestHandler<CreateEventCommand, ServiceRes
if (request.AgentId.HasValue)
ev.AssignAgent(request.AgentId.Value);
var matchingRecordingId = await _context.Recordings.AsNoTracking()
.Where(recording => recording.CameraId == request.CameraId &&
occurredAt >= recording.Timestamp &&
occurredAt < recording.Timestamp.AddSeconds(recording.DurationSeconds))
.OrderBy(recording => recording.Timestamp)
.Select(recording => (Guid?)recording.Id)
.FirstOrDefaultAsync(ct)
.ConfigureAwait(false);
if (matchingRecordingId.HasValue)
ev.AssignRecording(matchingRecordingId.Value);
_context.CameraEvents.Add(ev);
try
{
@@ -45,10 +45,10 @@ public class GetCamerasByGroupHandler : IRequestHandler<GetCamerasByGroupQuery,
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
c.LastDiscoveredAt, c.LastStreamTestAt,
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt))
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt, c.RecordingEnabled, c.EventRecordingEnabled))
.ToListAsync(ct);
return ServiceResult<PagedResult<CameraResponse>>.Success(
new PagedResult<CameraResponse>(items, total, request.Page, request.PageSize));
}
}
}
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff. Show more