From 923cc2e5cb67d6c8333a9f028a9d0680540cf4cf Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 24 Oct 2026 13:38:12 +0200 Subject: [PATCH] Complete durable agent analysis job flow --- .env.example | 2 + .gitea/workflows/build.yml | 25 ++- docker/docker-compose.prod.yml | 9 +- docker/server-image.json | 3 + docs/agent-release-signing.md | 2 + readme.md | 15 +- scripts/ci/cleanup-docker.sh | 18 +- scripts/ci/images.sh | 5 +- scripts/ci/publish.sh | 61 +++++-- scripts/ci/push-dockerhub.sh | 35 ---- scripts/ci/push-images.sh | 64 +++++++ src/Heimdall.Agent/Program.cs | 1 + .../Services/AnalysisJobPollingService.cs | 170 ++++++++++++++++++ .../Common/IApplicationDbContext.cs | 1 + .../Services/IAnalysisJobSchedulerService.cs | 17 +- src/Heimdall.Domain/Entities/AnalysisJob.cs | 15 +- .../BackgroundJobs/JobSetup.cs | 9 +- .../AnalysisJobConfiguration.cs | 2 + .../Jobs/AnalysisJobDispatcherJob.cs | 16 +- .../20261024010000_AddAnalysisJobAttempt.cs | 18 ++ .../Migrations/AppDbContextModelSnapshot.cs | 3 + .../Services/AnalysisJobSchedulerService.cs | 125 ++++++++++++- .../Controllers/AnalysisJobsController.cs | 130 ++++++++++++++ src/Heimdall.Web/appsettings.json | 3 - .../AnalysisJobDispatcherJobTests.cs | 6 +- .../AnalysisJobSchedulerServiceTests.cs | 54 ++++-- todo.md | 3 +- 27 files changed, 689 insertions(+), 123 deletions(-) create mode 100644 docker/server-image.json delete mode 100644 scripts/ci/push-dockerhub.sh create mode 100644 scripts/ci/push-images.sh create mode 100644 src/Heimdall.Agent/Services/AnalysisJobPollingService.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261024010000_AddAnalysisJobAttempt.cs create mode 100644 src/Heimdall.Web/Controllers/AnalysisJobsController.cs diff --git a/.env.example b/.env.example index 56d579d..b6dc7da 100644 --- a/.env.example +++ b/.env.example @@ -11,6 +11,8 @@ # Database POSTGRES_PASSWORD=heimdall DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall +SERVER_IMAGE_REFERENCE=eltruncho/heimdall:latest +UPDATES_RELEASE_API_URL=https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest # JWT (change in production!) # JWT__Key is used for access tokens, JWT__RefreshKey for refresh tokens. diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 8783bdb..9f313db 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -21,6 +21,9 @@ on: tags: ['v*'] permissions: contents: read +env: + BUILD_SERVER_URL: ${{ gitea.server_url }} + BUILD_REPOSITORY: ${{ gitea.repository }} jobs: verify: name: Build and tests @@ -135,13 +138,14 @@ jobs: run: bash scripts/ci/images.sh server - name: Scan server image run: bash scripts/ci/security.sh server - - name: Push immutable server image to Docker Hub + - name: Push immutable server image to configured registry if: gitea.ref == 'refs/heads/main' env: DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} - DOCKERHUB_NAMESPACE: eltruncho - run: bash scripts/ci/push-dockerhub.sh server + IMAGE_REGISTRY_USER: ${{ secrets.IMAGE_REGISTRY_USER }} + IMAGE_REGISTRY_TOKEN: ${{ secrets.IMAGE_REGISTRY_TOKEN }} + run: bash scripts/ci/push-images.sh server - name: Reclaim build storage after job if: always() run: | @@ -178,13 +182,14 @@ jobs: run: bash scripts/ci/images.sh agent - name: Scan agent image run: bash scripts/ci/security.sh agent - - name: Push immutable agent image to Docker Hub + - name: Push immutable agent image to configured registry if: gitea.ref == 'refs/heads/main' env: DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} - DOCKERHUB_NAMESPACE: eltruncho - run: bash scripts/ci/push-dockerhub.sh agent + IMAGE_REGISTRY_USER: ${{ secrets.IMAGE_REGISTRY_USER }} + IMAGE_REGISTRY_TOKEN: ${{ secrets.IMAGE_REGISTRY_TOKEN }} + run: bash scripts/ci/push-images.sh agent - name: Reclaim build storage after job if: always() run: | @@ -219,8 +224,9 @@ jobs: env: DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} - DOCKERHUB_NAMESPACE: eltruncho - run: bash scripts/ci/push-dockerhub.sh latest + IMAGE_REGISTRY_USER: ${{ secrets.IMAGE_REGISTRY_USER }} + IMAGE_REGISTRY_TOKEN: ${{ secrets.IMAGE_REGISTRY_TOKEN }} + run: bash scripts/ci/push-images.sh latest - name: Reclaim build storage after job if: always() run: | @@ -273,6 +279,9 @@ jobs: AGENT_REGISTRY_TOKEN: ${{ secrets.AGENT_REGISTRY_TOKEN }} DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + IMAGE_REGISTRY_USER: ${{ secrets.IMAGE_REGISTRY_USER }} + IMAGE_REGISTRY_TOKEN: ${{ secrets.IMAGE_REGISTRY_TOKEN }} RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }} RELEASE_SIGNING_KEY_B64: ${{ secrets.RELEASE_SIGNING_KEY_B64 }} + EXPECTED_BUILD_SERVER_URL: ${{ vars.RELEASE_SERVER_URL }} run: bash scripts/ci/publish.sh diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index ebc0dc5..66b08ea 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -13,9 +13,8 @@ # openssl rand -base64 32 > docker/secrets/rustfs_secret_key # echo -n "your-smtp-password" > docker/secrets/smtp_password # -# Images are published by the CI pipeline on main branch pushes: -# eltruncho/heimdall:latest -# image reference from the current Central agent-image.json manifest +# Set SERVER_IMAGE_REFERENCE to the server image selected for this deployment. +# Its repository is configured in docker/server-image.json. # # The heimdall service serves the Blazor UI, REST API, SignalR hubs, # and Hangfire background jobs (heartbeat monitor, agent failover) @@ -74,7 +73,7 @@ services: - heimdall-net heimdall: - image: eltruncho/heimdall:latest + image: ${SERVER_IMAGE_REFERENCE:?Set SERVER_IMAGE_REFERENCE from docker/server-image.json} environment: # Database (password from secret, rest from env) DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required} @@ -90,7 +89,7 @@ services: # container's own listener, NOT the host-mapped origin the browser sees. API_BASE_URL: ${API_BASE_URL:-http://localhost:8080} # Central selects the release source; agents obtain the image and digest from Central. - Updates__ReleaseApiUrl: ${UPDATES_RELEASE_API_URL:-https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest} + Updates__ReleaseApiUrl: ${UPDATES_RELEASE_API_URL:?Set the Central release API URL} # Ollama (optional — daily summaries) Ollama__Endpoint: http://ollama:11434 # Coturn (WebRTC relay) diff --git a/docker/server-image.json b/docker/server-image.json new file mode 100644 index 0000000..d42beef --- /dev/null +++ b/docker/server-image.json @@ -0,0 +1,3 @@ +{ + "image": "eltruncho/heimdall" +} diff --git a/docs/agent-release-signing.md b/docs/agent-release-signing.md index 7342367..13df8db 100644 --- a/docs/agent-release-signing.md +++ b/docs/agent-release-signing.md @@ -14,6 +14,8 @@ base64 -w0 agent-release-private.pem La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B64`. Ne pas ajouter la clé privée au dépôt ni aux images. Distribuer `agent-release-public.pem` par un canal d’administration indépendant de Central. La publication d’une release échoue si le secret de signature manque. +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 dépôts d’image serveur et Agent viennent de `docker/server-image.json` et `docker/agent-image.json`; fournir les secrets du registre correspondant. 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é. ## Installer un Agent natif diff --git a/readme.md b/readme.md index 90d6022..1dd9c31 100644 --- a/readme.md +++ b/readme.md @@ -104,10 +104,11 @@ Le dossier `docker/` contient tout nécessaire pour déployer Heimdall : | `docker-compose.local.yml` | Surcharges locales | Ajustements optionnels, par exemple l'exposition d'un GPU | | `Dockerfile` | Build | Image Central (UI + API + jobs) | | `Dockerfile.agent` | Build | Image agent avec FFmpeg | +| `docker/server-image.json` | Publication | Dépôt de l’image Central à publier | | `docker/agent-image.json` | Publication | Dépôt d’image agent à publier ; sa référence et son digest sont joints au manifeste de release | | `docker/secrets/` | Production | Clés secrètes (JWT, DB, Coturn, etc.) | -Pour une installation de production, définissez `AGENT_IMAGE_REFERENCE` sur la valeur `image@digest` du compose généré par le Central. Le dépôt et le digest proviennent du manifeste `agent-image.json` de la release ; le compose n’utilise pas de tag mutable. +Pour une installation de production, définissez `SERVER_IMAGE_REFERENCE` depuis `docker/server-image.json`. Définissez `AGENT_IMAGE_REFERENCE` sur la valeur `image@digest` du compose généré par le Central. Le dépôt et le digest agent proviennent du manifeste signé `agent-image.json` de la release ; le compose n’utilise pas de tag mutable. ### Services @@ -115,7 +116,7 @@ Pour une installation de production, définissez `AGENT_IMAGE_REFERENCE` sur la |---|---|---|---| | `postgresql` | `postgres:17-alpine` | 5432 | — | | `rustfs` | `rustfs/rustfs:latest` | 9000 (S3), 9001 (console) | — | -| `heimdall` | `heimdall:latest` (dev) / `eltruncho/heimdall:latest` (prod) | 5000 | postgresql (healthy) | +| `heimdall` | `heimdall:latest` (dev) / `SERVER_IMAGE_REFERENCE` (prod) | 5000 | postgresql (healthy) | | `heimdall-agent` | `heimdall-agent:latest` (dev) / `AGENT_IMAGE_REFERENCE` (prod) | — | heimdall | | `ntfy` | `binwiederhier/ntfy` | 8080 | — | | `coturn` | `coturn/coturn:4.6` | 3478 | — | @@ -215,11 +216,11 @@ Générer un token via `POST /api/sites/{id}/tokens` sur l'API. La source des mises à jour est configurée côté Central par `Updates:ReleaseApiUrl` (`UPDATES_RELEASE_API_URL` dans le Compose de production, ou -`Updates__ReleaseApiUrl` directement). Elle pointe par défaut vers les releases -du dépôt `sources.tordais.cc/arnaud.dartois/Heimdall` et peut être changée sans -recompiler le serveur. L'agent lit le nom et le digest de l'image dans le -manifeste authentifié de Central ; le dépôt d'image publié est défini dans -`docker/agent-image.json` lors de la release. +`Updates__ReleaseApiUrl` directement). Cette valeur est requise au déploiement +et peut être changée sans recompiler le serveur. L'agent lit le nom et le digest +de l'image dans le manifeste authentifié de Central ; le dépôt d'image Agent est +défini dans `docker/agent-image.json` et celui du serveur dans +`docker/server-image.json`. La [procédure de signature des releases agent](docs/agent-release-signing.md) décrit la clé publique locale requise pour les mises à jour natives et Docker. diff --git a/scripts/ci/cleanup-docker.sh b/scripts/ci/cleanup-docker.sh index 9c2f246..30a8844 100644 --- a/scripts/ci/cleanup-docker.sh +++ b/scripts/ci/cleanup-docker.sh @@ -12,18 +12,12 @@ df -i /workspace 2>/dev/null || true # Images are tagged with this source by scripts/ci/images.sh. Never delete an # image used by a running container; docker image rm without --force refuses it. -source_label='org.opencontainers.image.source=https://sources.tordais.cc/arnaud.dartois/Heimdall' -while IFS= read -r reference; do - case "$reference" in - heimdall-server:ci-*|heimdall-agent:ci-*|\ - eltruncho/heimdall:sha-*|eltruncho/heimdall:latest|\ - eltruncho/heimdall-agent:sha-*|eltruncho/heimdall-agent:latest|\ - sources.tordais.cc/arnaud.dartois/heimdall-server:*|\ - sources.tordais.cc/arnaud.dartois/heimdall-agent:*) - docker image rm "$reference" >/dev/null 2>&1 || true - ;; - esac -done < <(docker image ls --filter "label=$source_label" --format '{{.Repository}}:{{.Tag}}') +: "${BUILD_SERVER_URL:?Gitea server URL is required}" +: "${BUILD_REPOSITORY:?Gitea repository is required}" +source_label="org.opencontainers.image.source=${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}" +while IFS= read -r image_id; do + [[ -n "$image_id" ]] && docker image rm "$image_id" >/dev/null 2>&1 || true +done < <(docker image ls --filter "label=$source_label" --format '{{.ID}}' | sort -u) # A cancelled security step may leave its dedicated Trivy database volume. # Docker refuses removal while a scanner container still uses the volume. diff --git a/scripts/ci/images.sh b/scripts/ci/images.sh index 8d9075a..2aa6760 100644 --- a/scripts/ci/images.sh +++ b/scripts/ci/images.sh @@ -2,6 +2,9 @@ set -euo pipefail sha=$(git rev-parse HEAD) version=$(cat artifacts/version 2>/dev/null || printf '0.0.0-ci.%s' "${sha:0:12}") +: "${BUILD_SERVER_URL:?Gitea server URL is required}" +: "${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") ;; @@ -13,6 +16,6 @@ for component in "${components[@]}"; do docker build --pull --platform linux/amd64 -f "$file" --build-arg "VERSION=$version" \ --label "org.opencontainers.image.revision=$sha" \ --label "org.opencontainers.image.version=$version" \ - --label "org.opencontainers.image.source=https://sources.tordais.cc/arnaud.dartois/Heimdall" \ + --label "org.opencontainers.image.source=$source_url" \ -t "heimdall-$component:ci-$sha" . done diff --git a/scripts/ci/publish.sh b/scripts/ci/publish.sh index 9b5edf2..f858697 100644 --- a/scripts/ci/publish.sh +++ b/scripts/ci/publish.sh @@ -1,12 +1,27 @@ #!/usr/bin/env bash set -euo pipefail -: "${REGISTRY_USER:?Dedicated registry user is required}" -: "${REGISTRY_TOKEN:?Dedicated registry token is required}" : "${RELEASE_TOKEN:?Dedicated Gitea release token is required}" : "${RELEASE_SIGNING_KEY_B64:?Publisher ECDSA P-256 private key is required}" : "${BUILD_SERVER_URL:?Gitea URL is required}" +: "${EXPECTED_BUILD_SERVER_URL:?Expected Gitea URL is required}" : "${BUILD_REPOSITORY:?Repository is required}" -[[ "$BUILD_SERVER_URL" == https://sources.tordais.cc ]] || { echo 'Unexpected publication host' >&2; exit 1; } +registry_host=$(python3 - "$BUILD_SERVER_URL" "$EXPECTED_BUILD_SERVER_URL" <<'PY' +import sys +from urllib.parse import urlsplit + +actual, expected = (urlsplit(value) for value in sys.argv[1:]) +def valid_origin(value): + return (value.scheme == 'https' and bool(value.hostname) and + value.path in ('', '/') and not value.query and not value.fragment and + value.username is None and value.password is None) + +if (not valid_origin(actual) or not valid_origin(expected) or + actual.hostname.lower() != expected.hostname.lower() or + (actual.port or 443) != (expected.port or 443)): + raise SystemExit('Unexpected publication host') +print(actual.netloc) +PY +) [[ "$BUILD_REPOSITORY" == arnaud.dartois/Heimdall ]] || { echo 'Unexpected publication repository' >&2; exit 1; } sha=$(git rev-parse HEAD) umask 077 @@ -33,16 +48,40 @@ bash scripts/ci/images.sh export DOCKER_CONFIG DOCKER_CONFIG=$(mktemp -d) trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT -printf '%s' "$REGISTRY_TOKEN" | docker login sources.tordais.cc -u "$REGISTRY_USER" --password-stdin +server_image=$(python3 -c 'import json; print(json.load(open("docker/server-image.json"))["image"])') +[[ "$server_image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${server_image##*/}" != *:* ]] || { echo 'Invalid server image repository in docker/server-image.json' >&2; exit 1; } agent_image=$(python3 -c 'import json; print(json.load(open("docker/agent-image.json"))["image"])') [[ "$agent_image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${agent_image##*/}" != *:* ]] || { echo 'Invalid agent image repository in docker/agent-image.json' >&2; exit 1; } -agent_registry=${agent_image%%/*} -if [[ "$agent_registry" == "$agent_image" || ( "$agent_registry" != *.* && "$agent_registry" != *:* && "$agent_registry" != localhost* ) ]]; then - agent_registry=docker.io +image_registry() { + local image="$1" registry="${1%%/*}" + if [[ "$registry" == "$image" || ( "$registry" != *.* && "$registry" != *:* && "$registry" != localhost* ) ]]; then + printf 'docker.io' + else + printf '%s' "$registry" + fi +} +server_registry=$(image_registry "$server_image") +agent_registry=$(image_registry "$agent_image") +if [[ "$server_registry" == "$registry_host" ]]; then + : "${REGISTRY_USER:?Registry user is required for $server_registry}" + : "${REGISTRY_TOKEN:?Registry token is required for $server_registry}" + printf '%s' "$REGISTRY_TOKEN" | docker login "$server_registry" -u "$REGISTRY_USER" --password-stdin +elif [[ "$server_registry" == docker.io ]]; then + server_registry_user=${DOCKERHUB_USERNAME:-${REGISTRY_USER:-}} + server_registry_token=${DOCKERHUB_TOKEN:-${REGISTRY_TOKEN:-}} + : "${server_registry_user:?Docker Hub user is required for $server_image}" + : "${server_registry_token:?Docker Hub token is required for $server_image}" + printf '%s' "$server_registry_token" | docker login "$server_registry" -u "$server_registry_user" --password-stdin +else + server_registry_user=${SERVER_REGISTRY_USER:-${IMAGE_REGISTRY_USER:-}} + server_registry_token=${SERVER_REGISTRY_TOKEN:-${IMAGE_REGISTRY_TOKEN:-}} + : "${server_registry_user:?Server registry user is required for $server_registry}" + : "${server_registry_token:?Server registry token is required for $server_registry}" + printf '%s' "$server_registry_token" | docker login "$server_registry" -u "$server_registry_user" --password-stdin fi -if [[ "$agent_registry" != sources.tordais.cc ]]; then - agent_user=${AGENT_REGISTRY_USER:-${DOCKERHUB_USERNAME:-}} - agent_token=${AGENT_REGISTRY_TOKEN:-${DOCKERHUB_TOKEN:-}} +if [[ "$agent_registry" != "$server_registry" ]]; then + agent_user=${AGENT_REGISTRY_USER:-${DOCKERHUB_USERNAME:-${IMAGE_REGISTRY_USER:-}}} + agent_token=${AGENT_REGISTRY_TOKEN:-${DOCKERHUB_TOKEN:-${IMAGE_REGISTRY_TOKEN:-}}} : "${agent_user:?Agent registry user is required for $agent_registry}" : "${agent_token:?Agent registry token is required for $agent_registry}" printf '%s' "$agent_token" | docker login "$agent_registry" -u "$agent_user" --password-stdin @@ -52,7 +91,7 @@ for component in server agent; do if [[ "$component" == agent ]]; then image=$agent_image else - image="sources.tordais.cc/arnaud.dartois/heimdall-server" + image=$server_image fi for image_tag in "sha-$sha" "${tag#v}"; do if docker manifest inspect "$image:$image_tag" >/dev/null 2>&1; then diff --git a/scripts/ci/push-dockerhub.sh b/scripts/ci/push-dockerhub.sh deleted file mode 100644 index e5814c5..0000000 --- a/scripts/ci/push-dockerhub.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -: "${DOCKERHUB_USERNAME:?Docker Hub username is required}" -: "${DOCKERHUB_TOKEN:?Docker Hub access token is required}" -namespace=${DOCKERHUB_NAMESPACE:-eltruncho} -[[ "$namespace" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || { echo 'Invalid Docker Hub namespace' >&2; exit 1; } -mode=${1:?Expected server, agent or latest} -case "$mode" in server|agent|latest) ;; *) echo 'Usage: push-dockerhub.sh server|agent|latest' >&2; exit 2 ;; esac -sha=$(git rev-parse HEAD) -export DOCKER_CONFIG -DOCKER_CONFIG=$(mktemp -d) -trap 'rm -rf "$DOCKER_CONFIG"' EXIT -printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin -repository() { - case "$1" in - server) printf '%s/heimdall' "$namespace" ;; - agent) printf '%s/heimdall-agent' "$namespace" ;; - esac -} -if [[ "$mode" == latest ]]; then - # Move mutable tags only after both independently built images passed their scans. - for component in server agent; do - docker pull "$(repository "$component"):sha-$sha" - done - for component in server agent; do - repo=$(repository "$component") - docker tag "$repo:sha-$sha" "$repo:latest" - docker push "$repo:latest" - done -else - repo=$(repository "$mode") - docker image inspect "heimdall-$mode:ci-$sha" >/dev/null - docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha" - docker push "$repo:sha-$sha" -fi diff --git a/scripts/ci/push-images.sh b/scripts/ci/push-images.sh new file mode 100644 index 0000000..0ce849a --- /dev/null +++ b/scripts/ci/push-images.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +set -euo pipefail +mode=${1:?Expected server, agent or latest} +case "$mode" in server|agent|latest) ;; *) echo 'Usage: push-dockerhub.sh server|agent|latest' >&2; exit 2 ;; esac +sha=$(git rev-parse HEAD) +if [[ "$mode" == latest ]]; then components=(server agent); else components=("$mode"); fi +export DOCKER_CONFIG +DOCKER_CONFIG=$(mktemp -d) +trap 'rm -rf "$DOCKER_CONFIG"' EXIT +repository() { + case "$1" in + server) python3 -c 'import json; print(json.load(open("docker/server-image.json"))["image"])' ;; + agent) python3 -c 'import json; print(json.load(open("docker/agent-image.json"))["image"])' ;; + esac +} +registry_for() { + local image="$1" host="${1%%/*}" + if [[ "$host" == "$image" || ( "$host" != *.* && "$host" != *:* && "$host" != localhost* ) ]]; then + printf 'docker.io' + else + printf '%s' "$host" + fi +} +login_for() { + local registry="$1" user token + if [[ "$registry" == docker.io ]]; then + user=${DOCKERHUB_USERNAME:-} + token=${DOCKERHUB_TOKEN:-} + else + user=${IMAGE_REGISTRY_USER:-} + token=${IMAGE_REGISTRY_TOKEN:-} + fi + : "${user:?Image registry user is required for $registry}" + : "${token:?Image registry token is required for $registry}" + printf '%s' "$token" | docker login "$registry" -u "$user" --password-stdin +} +for component in "${components[@]}"; do + image=$(repository "$component") + [[ "$image" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$ && "${image##*/}" != *:* ]] || { + echo "Invalid $component image repository in docker/$component-image.json" >&2 + exit 1 + } + registry=$(registry_for "$image") + if [[ "$registry" != "${logged_registry:-}" ]]; then + login_for "$registry" + logged_registry=$registry + fi +done +if [[ "$mode" == latest ]]; then + # Move mutable tags only after both independently built images passed their scans. + for component in server agent; do + docker pull "$(repository "$component"):sha-$sha" + done + for component in server agent; do + repo=$(repository "$component") + docker tag "$repo:sha-$sha" "$repo:latest" + docker push "$repo:latest" + done +else + repo=$(repository "$mode") + docker image inspect "heimdall-$mode:ci-$sha" >/dev/null + docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha" + docker push "$repo:sha-$sha" +fi diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index a437b44..289e988 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -126,6 +126,7 @@ builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); +builder.Services.AddHostedService(); // Video capture pipeline (ticket #1): FFmpeg capture per assigned camera, // bounded snapshot channel, adaptive interval, frames → FrameAnalyzerService. diff --git a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs new file mode 100644 index 0000000..a2fe66b --- /dev/null +++ b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs @@ -0,0 +1,170 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Domain.Enums; + +namespace Heimdall.Agent.Services; + +/// +/// Claims one durable analysis job at a time over the agent's outbound Central connection. +/// Central owns the lease and attempt ID; a repeated result uses that same ID. +/// +public sealed class AnalysisJobPollingService : BackgroundService +{ + private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(5); + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + private readonly AgentState _state; + private readonly CameraConfigStore _cameras; + private readonly CameraStreamService _streams; + private readonly FrameAnalyzerService _analyzer; + private readonly IHttpClientFactory _clients; + private readonly ILogger _logger; + + public AnalysisJobPollingService(AgentState state, CameraConfigStore cameras, + CameraStreamService streams, FrameAnalyzerService analyzer, IHttpClientFactory clients, + ILogger logger) + { + _state = state; + _cameras = cameras; + _streams = streams; + _analyzer = analyzer; + _clients = clients; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + if (_state.AgentId != Guid.Empty && !string.IsNullOrWhiteSpace(_state.ApiKey)) + await PollOnceAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Analysis job polling failed; Central will retain or retry the leased job"); + } + + try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + } + } + + private async Task PollOnceAsync(CancellationToken ct) + { + var agentId = _state.AgentId; + using var client = _clients.CreateClient("Central"); + client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); + using var response = await client.GetAsync($"api/agents/{agentId:D}/analysis-jobs/next", ct) + .ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.NoContent) return; + if (!response.IsSuccessStatusCode) + { + _logger.LogWarning("Analysis job claim failed with HTTP {StatusCode}", (int)response.StatusCode); + return; + } + + var job = await response.Content.ReadFromJsonAsync(Json, ct).ConfigureAwait(false); + if (job is null || job.JobId == Guid.Empty || job.CameraId == Guid.Empty || job.AttemptId == Guid.Empty) + { + _logger.LogError("Central returned an invalid analysis job lease"); + return; + } + + var result = await ExecuteJobAsync(job, ct).ConfigureAwait(false); + await SendResultAsync(client, agentId, job.JobId, result, ct).ConfigureAwait(false); + } + + private async Task ExecuteJobAsync(LeasedJob job, CancellationToken ct) + { + if (!IsObjectDetection(job.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) + return Failure(job.AttemptId, "Object detection model is unavailable"); + + Snapshot? frame; + try + { + frame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + frame = null; + } + if (frame is null) + return Failure(job.AttemptId, "Camera frame capture failed or timed out"); + + var confidence = camera.DetectionProfile?.MinConfidence ?? FrameAnalyzerService.DefaultMinConfidence; + var analysis = await _analyzer.AnalyzeFrameAsync(frame.JpegData, confidence, ct).ConfigureAwait(false); + if (analysis is null) + return Failure(job.AttemptId, "Object detection was unavailable or saturated"); + + return new AnalysisResult(job.AttemptId, true, null, analysis.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, + AnalysisResult result, CancellationToken ct) + { + var retryDelay = TimeSpan.FromSeconds(2); + while (!ct.IsCancellationRequested) + { + try + { + using var response = await client.PutAsJsonAsync( + $"api/agents/{agentId:D}/analysis-jobs/{jobId:D}/result", result, Json, ct) + .ConfigureAwait(false); + if (response.IsSuccessStatusCode) return; + if (response.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.NotFound) + { + _logger.LogInformation("Analysis job {JobId} attempt {AttemptId} is no longer current", + jobId, result.AttemptId); + return; + } + _logger.LogWarning("Analysis result for job {JobId} was rejected with HTTP {StatusCode}; retrying", + jobId, (int)response.StatusCode); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + break; + } + catch (HttpRequestException ex) + { + _logger.LogWarning(ex, "Analysis result delivery failed for job {JobId}; retrying", jobId); + } + catch (TaskCanceledException ex) when (!ct.IsCancellationRequested) + { + _logger.LogWarning(ex, "Analysis result delivery timed out for job {JobId}; retrying", jobId); + } + + await Task.Delay(retryDelay, ct).ConfigureAwait(false); + retryDelay = TimeSpan.FromSeconds(Math.Min(retryDelay.TotalSeconds * 2, 30)); + } + } + + private static bool IsObjectDetection(JsonElement type) => type.ValueKind switch + { + JsonValueKind.String => string.Equals(type.GetString(), nameof(AnalysisJobType.ObjectDetection), + StringComparison.OrdinalIgnoreCase), + JsonValueKind.Number => type.TryGetInt32(out var value) && value == (int)AnalysisJobType.ObjectDetection, + _ => false, + }; + + private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []); + + private sealed record LeasedJob(Guid JobId, Guid CameraId, Guid AttemptId, JsonElement JobType); + private 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, + IReadOnlyList Detections); +} diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 0650128..86d91a3 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -8,6 +8,7 @@ public interface IApplicationDbContext DbSet Agents { get; } DbSet AgentLogEntries { get; } DbSet AgentSettings { get; } + DbSet AnalysisJobs { get; } DbSet ApiKeys { get; } DbSet AppSettings { get; } DbSet Users { get; } diff --git a/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs b/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs index d4a4ed3..e38fbf7 100644 --- a/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs +++ b/src/Heimdall.Application/Services/IAnalysisJobSchedulerService.cs @@ -21,12 +21,14 @@ public interface IAnalysisJobSchedulerService CancellationToken ct = default); /// - /// Select the best agent for a pending job and dispatch it. - /// Selection criteria: capabilities → site affinity → current load. - /// Returns null if no suitable agent is available. + /// Dispatches a pending job only to the agent currently assigned to its camera. + /// Returns a failure if that agent is unavailable or lacks the required resources. /// Task> DispatchJobAsync(Guid jobId, CancellationToken ct); + /// Atomically claim the next durable job assigned to an agent. + Task ClaimNextJobAsync(Guid agentId, CancellationToken ct); + /// /// Process the next batch of pending jobs (called by the Hangfire dispatcher). /// Selects agents and dispatches as many jobs as possible. @@ -43,11 +45,17 @@ public interface IAnalysisJobSchedulerService /// Task CompleteJobAsync(Guid jobId, CancellationToken ct, string? resultJson = null); + /// Complete only the current attempt owned by the authenticated agent. + Task CompleteJobAsync(Guid jobId, Guid agentId, Guid attemptId, CancellationToken ct, string? resultJson = null); + /// /// Report a job failure — triggers retry or dead-lettering. /// Task FailJobAsync(Guid jobId, string errorMessage, CancellationToken ct); + /// Fail only the current attempt owned by the authenticated agent. + Task FailJobAsync(Guid jobId, Guid agentId, Guid attemptId, string errorMessage, CancellationToken ct); + /// /// Cancel a pending or running job. /// @@ -60,8 +68,7 @@ public interface IAnalysisJobSchedulerService Task> GetTimedOutJobsAsync(CancellationToken ct); /// - /// Get the best agent for a given job based on capabilities, site affinity, and load. - /// Used internally and for testing/validation. + /// Scores an agent for legacy scheduling scenarios. Camera jobs dispatch to their assigned agent. /// Task SelectBestAgentAsync(AnalysisJob job, CancellationToken ct); diff --git a/src/Heimdall.Domain/Entities/AnalysisJob.cs b/src/Heimdall.Domain/Entities/AnalysisJob.cs index 0eb7384..a8807b3 100644 --- a/src/Heimdall.Domain/Entities/AnalysisJob.cs +++ b/src/Heimdall.Domain/Entities/AnalysisJob.cs @@ -12,6 +12,8 @@ public class AnalysisJob : Entity, IAuditableEntity { public Guid CameraId { get; private set; } public Guid? AssignedAgentId { get; private set; } + /// Changes on every dispatch so late replies cannot complete a retried job. + public Guid? AttemptId { get; private set; } public AnalysisJobType JobType { get; private set; } public AnalysisJobStatus Status { get; private set; } = AnalysisJobStatus.Pending; public AnalysisJobPriority Priority { get; private set; } = AnalysisJobPriority.Periodic; @@ -90,6 +92,7 @@ public class AnalysisJob : Entity, IAuditableEntity public void Dispatch(Guid agentId) { AssignedAgentId = agentId; + AttemptId = Guid.NewGuid(); Status = AnalysisJobStatus.Dispatched; DispatchedAt = DateTime.UtcNow; } @@ -111,6 +114,10 @@ public class AnalysisJob : Entity, IAuditableEntity { RetryCount++; ErrorMessage = errorMessage; + AssignedAgentId = null; + AttemptId = null; + DispatchedAt = null; + StartedAt = null; if (RetryCount >= MaxRetries) { @@ -120,8 +127,6 @@ public class AnalysisJob : Entity, IAuditableEntity { // Reset to pending for retry — agent will be re-selected Status = AnalysisJobStatus.Pending; - AssignedAgentId = null; - DispatchedAt = null; } } @@ -130,6 +135,10 @@ public class AnalysisJob : Entity, IAuditableEntity Status = AnalysisJobStatus.TimedOut; ErrorMessage = $"Job exceeded maximum execution time of {MaxExecutionTime.TotalSeconds}s"; RetryCount++; + AssignedAgentId = null; + AttemptId = null; + DispatchedAt = null; + StartedAt = null; if (RetryCount >= MaxRetries) { @@ -138,8 +147,6 @@ public class AnalysisJob : Entity, IAuditableEntity else { Status = AnalysisJobStatus.Pending; - AssignedAgentId = null; - DispatchedAt = null; } } diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index 7c03f73..880db28 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -68,8 +68,13 @@ public static class JobSetup job => job.ExecuteAsync(CancellationToken.None), "0 7 * * 0"); // Sunday at 7:00 - // Legacy analysis job timeout cleanup. Dispatch stays disabled until the - // Agent job path is implemented over the authenticated SignalR channel. + // PostgreSQL-backed analysis jobs are dispatched durably; agents claim + // assigned work over their authenticated outbound HTTP connection. + manager.AddOrUpdate( + "analysis-job-dispatch", + job => job.ExecuteAsync(CancellationToken.None), + "* * * * *"); + manager.AddOrUpdate( "analysis-job-timeout-sweep", job => job.ExecuteTimeoutSweepAsync(CancellationToken.None), diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs index b863506..67d34c2 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/AnalysisJobConfiguration.cs @@ -27,6 +27,8 @@ public class AnalysisJobConfiguration : IEntityTypeConfiguration .HasConversion() .IsRequired(); + builder.Property(j => j.AttemptId); + // Capability requirements builder.Property(j => j.RequiredCpuCores) .HasDefaultValue(0); diff --git a/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs b/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs index d1c2ad1..c9dba19 100644 --- a/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs @@ -70,11 +70,17 @@ public sealed class AnalysisJobDispatcherJob "Sweep: analysis job {JobId} stuck in {Status} since {DispatchedAt} (timeout={Timeout}s)", job.Id, job.Status, job.DispatchedAt, job.MaxExecutionTime.TotalSeconds); - await _schedulerService.FailJobAsync( - job.Id, - $"Sweep: execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s", - ct) - .ConfigureAwait(false); + var reason = $"Sweep: execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s"; + if (job.AssignedAgentId is Guid agentId && job.AttemptId is Guid attemptId) + { + await _schedulerService.FailJobAsync(job.Id, agentId, attemptId, reason, ct) + .ConfigureAwait(false); + } + else + { + // Upgrade path for jobs dispatched before attempt IDs were added. + await _schedulerService.FailJobAsync(job.Id, reason, ct).ConfigureAwait(false); + } } _logger.LogInformation("Timeout sweep: {Count} jobs cleaned up", timedOutJobs.Count); diff --git a/src/Heimdall.Infrastructure/Migrations/20261024010000_AddAnalysisJobAttempt.cs b/src/Heimdall.Infrastructure/Migrations/20261024010000_AddAnalysisJobAttempt.cs new file mode 100644 index 0000000..75fd335 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261024010000_AddAnalysisJobAttempt.cs @@ -0,0 +1,18 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261024010000_AddAnalysisJobAttempt")] +public partial class AddAnalysisJobAttempt : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + => migrationBuilder.AddColumn("AttemptId", "analysis_jobs", type: "uuid", nullable: true); + + protected override void Down(MigrationBuilder migrationBuilder) + => migrationBuilder.DropColumn("AttemptId", "analysis_jobs"); +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index cda546b..639438a 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -308,6 +308,9 @@ namespace Heimdall.Infrastructure.Migrations b.Property("AssignedAgentId") .HasColumnType("uuid"); + b.Property("AttemptId") + .HasColumnType("uuid"); + b.Property("CameraId") .HasColumnType("uuid"); diff --git a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs index a509a9d..acf85b9 100644 --- a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs +++ b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs @@ -9,10 +9,8 @@ using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.Services; /// -/// Schedules analysis jobs by selecting the best agent based on: -/// 1. Capabilities (GPU, CPU, RAM) — agent must meet job requirements -/// 2. Site affinity — prefer agents at the same site as the camera -/// 3. Current load — prefer agents with fewer active jobs +/// Schedules analysis jobs on the agent assigned to the camera, after checking +/// its reported capabilities. The source frame remains on that agent. /// /// Priority ordering: SecurityCritical > SecurityHigh > Periodic > Background. /// Timeout/retry logic: jobs that fail are retried up to MaxRetries, then dead-lettered. @@ -47,6 +45,9 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService if (camera is null) return ServiceResult.NotFound("Camera not found"); + if (jobType != AnalysisJobType.ObjectDetection) + return ServiceResult.Failure("Only ObjectDetection jobs are currently supported"); + var job = new AnalysisJob(cameraId, camera.SiteId, jobType, priority, parametersJson); // Set capability requirements based on job type @@ -68,13 +69,21 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService var job = await db.AnalysisJobs .AsTracking() + .Include(j => j.Camera) .FirstOrDefaultAsync(j => j.Id == jobId && j.Status == AnalysisJobStatus.Pending, ct) .ConfigureAwait(false); if (job is null) return ServiceResult.NotFound("No pending job found with this ID"); - var bestAgent = await SelectBestAgentInternalAsync(db, job, ct).ConfigureAwait(false); + // Frames are captured locally by the camera's assigned agent. Choosing + // another online agent would dispatch a job it cannot execute. + var bestAgent = await db.Agents.AsNoTracking() + .Where(a => a.Id == job.Camera.AgentId && a.SiteId == job.SiteId && + a.Status == AgentStatus.Online && !a.IsDeleted && + (!job.RequiresGpu || a.HasGpu) && + a.CpuCores >= job.RequiredCpuCores && a.MemoryMb >= job.RequiredMemoryMb) + .FirstOrDefaultAsync(ct).ConfigureAwait(false); if (bestAgent is null) { _logger.LogDebug( @@ -83,8 +92,21 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService return ServiceResult.Failure("No suitable agent available", 503); } - job.Dispatch(bestAgent.Id); - await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + var attemptId = Guid.NewGuid(); + var dispatchedAt = DateTime.UtcNow; + var updated = await db.AnalysisJobs + .Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Pending && + j.Camera.AgentId == bestAgent.Id) + .ExecuteUpdateAsync(setters => setters + .SetProperty(j => j.AssignedAgentId, bestAgent.Id) + .SetProperty(j => j.AttemptId, attemptId) + .SetProperty(j => j.Status, AnalysisJobStatus.Dispatched) + .SetProperty(j => j.DispatchedAt, dispatchedAt) + .SetProperty(j => j.StartedAt, (DateTime?)null), ct).ConfigureAwait(false); + if (updated == 0) + return ServiceResult.Conflict("Job was already dispatched or camera assignment changed"); + db.Entry(job).State = EntityState.Detached; + job = await db.AnalysisJobs.AsNoTracking().FirstAsync(j => j.Id == jobId, ct).ConfigureAwait(false); _logger.LogInformation( "Job {JobId} dispatched to agent {AgentId} ({AgentName}) — site affinity: {SameSite}", @@ -93,6 +115,33 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService return ServiceResult.Success(job); } + /// Atomically claims a dispatched job for the authenticated agent. + public async Task ClaimNextJobAsync(Guid agentId, CancellationToken ct) + { + if (agentId == Guid.Empty) return null; + await using var db = await _dbFactory.CreateDbContextAsync(ct); + var candidates = await db.AnalysisJobs.AsNoTracking() + .Where(j => j.Status == AnalysisJobStatus.Dispatched && j.AssignedAgentId == agentId && + j.AttemptId != null && j.Camera.AgentId == agentId && !j.Camera.IsDeleted) + .OrderBy(j => j.Priority).ThenBy(j => j.CreatedAt) + .Select(j => j.Id).Take(16).ToListAsync(ct).ConfigureAwait(false); + + foreach (var jobId in candidates) + { + var startedAt = DateTime.UtcNow; + var claimed = await db.AnalysisJobs + .Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Dispatched && + j.AssignedAgentId == agentId && j.Camera.AgentId == agentId) + .ExecuteUpdateAsync(setters => setters + .SetProperty(j => j.Status, AnalysisJobStatus.Running) + .SetProperty(j => j.StartedAt, startedAt), ct).ConfigureAwait(false); + if (claimed == 1) + return await db.AnalysisJobs.AsNoTracking().SingleAsync(j => j.Id == jobId, ct).ConfigureAwait(false); + } + + return null; + } + public async Task ProcessPendingJobsAsync(int maxJobs, CancellationToken ct) { var pendingJobs = await GetPendingJobsAsync(maxJobs, ct).ConfigureAwait(false); @@ -151,6 +200,31 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService return ServiceResult.Success(); } + /// Completes only the current attempt owned by this agent. + public async Task CompleteJobAsync( + Guid jobId, Guid agentId, Guid attemptId, CancellationToken ct, string? resultJson = null) + { + if (agentId == Guid.Empty || attemptId == Guid.Empty) + return ServiceResult.Conflict("Invalid analysis job attempt"); + await using var db = await _dbFactory.CreateDbContextAsync(ct); + var now = DateTime.UtcNow; + var updated = await db.AnalysisJobs + .Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Running && + j.AssignedAgentId == agentId && j.AttemptId == attemptId && + j.Camera.AgentId == agentId) + .ExecuteUpdateAsync(setters => setters + .SetProperty(j => j.Status, AnalysisJobStatus.Completed) + .SetProperty(j => j.ResultJson, resultJson) + .SetProperty(j => j.CompletedAt, now) + .SetProperty(j => j.ErrorMessage, (string?)null), ct).ConfigureAwait(false); + if (updated == 1) return ServiceResult.Success(); + + var alreadyCompleted = await db.AnalysisJobs.AsNoTracking() + .AnyAsync(j => j.Id == jobId && j.Status == AnalysisJobStatus.Completed && + j.AssignedAgentId == agentId && j.AttemptId == attemptId, ct).ConfigureAwait(false); + return alreadyCompleted ? ServiceResult.Success() : ServiceResult.Conflict("Analysis job attempt is no longer active"); + } + public async Task FailJobAsync(Guid jobId, string errorMessage, CancellationToken ct) { await using var db = await _dbFactory.CreateDbContextAsync(ct); @@ -184,6 +258,29 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService return ServiceResult.Success(); } + /// Fails only the current attempt owned by this agent. + public async Task FailJobAsync( + Guid jobId, Guid agentId, Guid attemptId, string errorMessage, CancellationToken ct) + { + if (agentId == Guid.Empty || attemptId == Guid.Empty) + return ServiceResult.Conflict("Invalid analysis job attempt"); + await using var db = await _dbFactory.CreateDbContextAsync(ct); + var safeError = string.IsNullOrWhiteSpace(errorMessage) ? "Agent analysis failed" : errorMessage[..Math.Min(errorMessage.Length, 2000)]; + var updated = await db.AnalysisJobs + .Where(j => j.Id == jobId && j.Status == AnalysisJobStatus.Running && + j.AssignedAgentId == agentId && j.AttemptId == attemptId) + .ExecuteUpdateAsync(setters => setters + .SetProperty(j => j.RetryCount, j => j.RetryCount + 1) + .SetProperty(j => j.Status, j => j.RetryCount + 1 >= j.MaxRetries + ? AnalysisJobStatus.DeadLettered : AnalysisJobStatus.Pending) + .SetProperty(j => j.ErrorMessage, safeError) + .SetProperty(j => j.AssignedAgentId, (Guid?)null) + .SetProperty(j => j.AttemptId, (Guid?)null) + .SetProperty(j => j.DispatchedAt, (DateTime?)null) + .SetProperty(j => j.StartedAt, (DateTime?)null), ct).ConfigureAwait(false); + return updated == 1 ? ServiceResult.Success() : ServiceResult.Conflict("Analysis job attempt is no longer active"); + } + public async Task CancelJobAsync(Guid jobId, CancellationToken ct) { await using var db = await _dbFactory.CreateDbContextAsync(ct); @@ -252,10 +349,16 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService private static async Task SelectBestAgentInternalAsync( AppDbContext db, AnalysisJob job, CancellationToken ct) { - // Load all online agents that are not soft-deleted + var assignedAgentId = await db.Cameras.AsNoTracking() + .Where(c => c.Id == job.CameraId && !c.IsDeleted) + .Select(c => c.AgentId).SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (assignedAgentId is null) return null; + + // Only the assigned agent can access the local camera stream. var agents = await db.Agents .AsNoTracking() - .Where(a => a.Status == AgentStatus.Online && !a.IsDeleted) + .Where(a => a.Id == assignedAgentId && a.SiteId == job.SiteId && + a.Status == AgentStatus.Online && !a.IsDeleted) .ToListAsync(ct) .ConfigureAwait(false); @@ -347,6 +450,10 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService switch (jobType) { case AnalysisJobType.ObjectDetection: + job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 2, requiredMemoryMb: 2048); + job.SetTimeout(TimeSpan.FromMinutes(10)); + break; + case AnalysisJobType.FullSceneAnalysis: job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048); job.SetTimeout(TimeSpan.FromMinutes(10)); diff --git a/src/Heimdall.Web/Controllers/AnalysisJobsController.cs b/src/Heimdall.Web/Controllers/AnalysisJobsController.cs new file mode 100644 index 0000000..dbfa9b6 --- /dev/null +++ b/src/Heimdall.Web/Controllers/AnalysisJobsController.cs @@ -0,0 +1,130 @@ +using System.Text.Json; +using Heimdall.Api.Security; +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api")] +public sealed class AnalysisJobsController( + IApplicationDbContext db, + IAnalysisJobSchedulerService scheduler, + ResourceAccess access) : ControllerBase +{ + private static readonly JsonSerializerOptions ResultJsonOptions = new(JsonSerializerDefaults.Web); + private const int MaxDetections = 500; + + public sealed record CreateAnalysisJobRequest(string JobType = "ObjectDetection", string? ParametersJson = null); + public sealed record AnalysisDetection(string Label, float Confidence, float X, float Y, + float Width, float Height, int? ClassIndex = null); + public sealed record SubmitAnalysisResult(Guid AttemptId, bool Success, string? Error, + IReadOnlyList? Detections = null); + + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] + [HttpPost("cameras/{cameraId:guid}/analysis-jobs")] + public async Task Create(Guid cameraId, [FromBody] CreateAnalysisJobRequest request, + CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + if (!Enum.TryParse(request.JobType, true, out var type) || + type != AnalysisJobType.ObjectDetection) + return BadRequest(new { error = "Only ObjectDetection jobs are currently supported" }); + if (request.ParametersJson is { Length: > 16_384 } || !IsJsonObjectOrNull(request.ParametersJson)) + return BadRequest(new { error = "ParametersJson must be a JSON object of at most 16 KiB" }); + + var created = await scheduler.CreateJobAsync(cameraId, type, AnalysisJobPriority.SecurityHigh, + request.ParametersJson, ct); + return created.IsSuccess + ? AcceptedAtAction(nameof(Get), new { cameraId, jobId = created.Data!.Id }, + new { jobId = created.Data!.Id, status = created.Data.Status.ToString() }) + : StatusCode(created.StatusCode ?? 400, new { error = created.Error }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("cameras/{cameraId:guid}/analysis-jobs/{jobId:guid}")] + public async Task Get(Guid cameraId, Guid jobId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + var job = await db.AnalysisJobs.AsNoTracking() + .Where(j => j.Id == jobId && j.CameraId == cameraId) + .Select(j => new { j.Id, j.JobType, j.Status, j.RetryCount, j.ErrorMessage, + j.ResultJson, j.CreatedAt, j.DispatchedAt, j.CompletedAt }) + .FirstOrDefaultAsync(ct); + return job is null ? NotFound() : Ok(job); + } + + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpGet("agents/{agentId:guid}/analysis-jobs/next")] + public async Task ClaimNext(Guid agentId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await access.AgentAsync(requester, agentId, ct)) return Forbid(); + var job = await scheduler.ClaimNextJobAsync(agentId, ct); + return job is null ? NoContent() : Ok(new + { + jobId = job.Id, + cameraId = job.CameraId, + attemptId = job.AttemptId, + jobType = job.JobType.ToString(), + parametersJson = job.ParametersJson + }); + } + + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPut("agents/{agentId:guid}/analysis-jobs/{jobId:guid}/result")] + public async Task SubmitResult(Guid agentId, Guid jobId, + [FromBody] SubmitAnalysisResult result, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await access.AgentAsync(requester, agentId, ct)) return Forbid(); + if (result.AttemptId == Guid.Empty) return BadRequest(new { error = "AttemptId is required" }); + if (result.Success && (result.Detections?.Count ?? 0) > MaxDetections) + return BadRequest(new { error = $"At most {MaxDetections} detections are accepted" }); + if (result.Success && result.Detections?.Any(d => string.IsNullOrWhiteSpace(d.Label) || + d.Label.Length > 120 || !float.IsFinite(d.Confidence) || d.Confidence is < 0 or > 1 || + !float.IsFinite(d.X) || !float.IsFinite(d.Y) || !float.IsFinite(d.Width) || + !float.IsFinite(d.Height) || d.X < 0 || d.Y < 0 || d.Width < 0 || d.Height < 0 || + d.X + d.Width > 1.001f || d.Y + d.Height > 1.001f) == true) + return BadRequest(new { error = "Detection values are invalid" }); + + ServiceResult updated; + if (result.Success) + { + var payload = JsonSerializer.Serialize(new { detections = result.Detections ?? [] }, ResultJsonOptions); + updated = await scheduler.CompleteJobAsync(jobId, agentId, result.AttemptId, ct, payload); + } + else + { + var error = string.IsNullOrWhiteSpace(result.Error) ? "Agent reported analysis failure" : result.Error; + updated = await scheduler.FailJobAsync(jobId, agentId, result.AttemptId, error[..Math.Min(error.Length, 2000)], ct); + } + if (updated.IsSuccess) return NoContent(); + if (updated.StatusCode == 404) return NotFound(); + if (updated.StatusCode == 409) return Conflict(new { error = updated.Error }); + return StatusCode(updated.StatusCode ?? 400, new { error = updated.Error }); + } + + private static bool IsJsonObjectOrNull(string? value) + { + if (value is null) return true; + try + { + using var document = JsonDocument.Parse(value); + return document.RootElement.ValueKind == JsonValueKind.Object; + } + catch (JsonException) { return false; } + } +} diff --git a/src/Heimdall.Web/appsettings.json b/src/Heimdall.Web/appsettings.json index cdf91ab..b2df244 100644 --- a/src/Heimdall.Web/appsettings.json +++ b/src/Heimdall.Web/appsettings.json @@ -8,9 +8,6 @@ } }, "AllowedHosts": "*", - "Updates": { - "ReleaseApiUrl": "https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest" - }, "Sentry": { "Dsn": "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6" } diff --git a/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs b/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs index 136b19b..a63771c 100644 --- a/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AnalysisJobDispatcherJobTests.cs @@ -172,11 +172,12 @@ public class AnalysisJobDispatcherJobTests : IAsyncLifetime await db.SaveChangesAsync(); var camera = new Camera(site.Id, "Main Camera", "rtsp://test"); - db.Cameras.Add(camera); var agent = new Agent(site.Id, "Test Agent", "test-host", "1.0.0"); agent.UpdateCapabilities(false, 4, 8192, GpuAcceleration.None); agent.UpdateHeartbeat("127.0.0.1"); + camera.AssignAgent(agent.Id); + db.Cameras.Add(camera); db.Agents.Add(agent); await db.SaveChangesAsync(); @@ -191,6 +192,9 @@ public class AnalysisJobDispatcherJobTests : IAsyncLifetime switch (jobType) { case AnalysisJobType.ObjectDetection: + job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 2, requiredMemoryMb: 2048); + job.SetTimeout(TimeSpan.FromMinutes(10)); + break; case AnalysisJobType.FullSceneAnalysis: job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048); job.SetTimeout(TimeSpan.FromMinutes(10)); diff --git a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs index 8540e04..4d04bb2 100644 --- a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs @@ -54,7 +54,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime } public static IEnumerable GpuScenarios => - from type in Enum.GetValues() + from type in new[] { AnalysisJobType.ObjectDetection } from sameSite in new[] { true, false } from loaded in new[] { true, false } select new object[] { type, sameSite, loaded }; @@ -71,6 +71,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime agent.Register("hash", "prefix"); agent.UpdateCapabilities(true, 8, 8192, GpuAcceleration.NvidiaCuda); db.Agents.Add(agent); + (await db.Cameras.SingleAsync(c => c.Id == cameraId)).AssignAgent(agent.Id); if (loaded) { var active = new AnalysisJob(cameraId, siteId, type, AnalysisJobPriority.Periodic); @@ -79,7 +80,9 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime } await db.SaveChangesAsync(); var created = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic); - (await _service.SelectBestAgentAsync(created.Data!, CancellationToken.None))!.Id.ShouldBe(agent.Id); + var selected = await _service.SelectBestAgentAsync(created.Data!, CancellationToken.None); + if (sameSite) selected!.Id.ShouldBe(agent.Id); + else selected.ShouldBeNull(); } // ── CreateJob ─────────────────────────────────────────────────── @@ -90,13 +93,13 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime var (siteId, cameraId) = await SeedSiteAndCameraAsync(); var result = await _service.CreateJobAsync( - cameraId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); + cameraId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic); result.IsSuccess.ShouldBeTrue(); result.Data.ShouldNotBeNull(); result.Data.CameraId.ShouldBe(cameraId); result.Data.SiteId.ShouldBe(siteId); - result.Data.JobType.ShouldBe(AnalysisJobType.MotionDetection); + result.Data.JobType.ShouldBe(AnalysisJobType.ObjectDetection); result.Data.Priority.ShouldBe(AnalysisJobPriority.Periodic); result.Data.Status.ShouldBe(AnalysisJobStatus.Pending); } @@ -120,7 +123,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime cameraId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical); result.IsSuccess.ShouldBeTrue(); - result.Data!.RequiresGpu.ShouldBeTrue(); + result.Data!.RequiresGpu.ShouldBeFalse(); result.Data.RequiredCpuCores.ShouldBe(2); result.Data.RequiredMemoryMb.ShouldBe(2048); } @@ -132,7 +135,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); var otherSiteId = await CreateSiteAsync("Other Site"); - await SeedAgentAsync(siteId, "Local Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + var localAgentId = await SeedAgentAsync(siteId, "Local Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, localAgentId); await SeedAgentAsync(otherSiteId, "Remote Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); @@ -148,9 +152,11 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); await SeedAgentAsync(siteId, "CPU Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); - await SeedAgentAsync(siteId, "GPU Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192); + var gpuAgentId = await SeedAgentAsync(siteId, "GPU Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, gpuAgentId); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.SecurityCritical); + job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048); var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None); @@ -162,9 +168,11 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task SelectBestAgentAsync_ExcludesInsufficientGpu() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "CPU Only", hasGpu: false, cpuCores: 4, memoryMb: 8192); + var cpuAgentId = await SeedAgentAsync(siteId, "CPU Only", hasGpu: false, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, cpuAgentId); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.ObjectDetection, AnalysisJobPriority.Periodic); + job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048); var bestAgent = await _service.SelectBestAgentAsync(job, CancellationToken.None); @@ -177,6 +185,7 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime var (siteId, cameraId) = await SeedSiteAndCameraAsync(); var idleAgentId = await SeedAgentAsync(siteId, "Idle Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); var busyAgentId = await SeedAgentAsync(siteId, "Busy Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, idleAgentId); // Give busy agent 3 active jobs for (var i = 0; i < 3; i++) @@ -202,7 +211,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task SelectBestAgentAsync_ExcludesOfflineAgents() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Offline Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192, status: AgentStatus.Offline); + var offlineAgentId = await SeedAgentAsync(siteId, "Offline Agent", hasGpu: true, cpuCores: 4, memoryMb: 8192, status: AgentStatus.Offline); + await AssignCameraAsync(cameraId, offlineAgentId); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); @@ -217,7 +227,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task DispatchJobAsync_PendingJob_DispatchesToAgent() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Test Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + var agentId = await SeedAgentAsync(siteId, "Test Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, agentId); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); var result = await _service.DispatchJobAsync(job.Id, CancellationToken.None); @@ -246,7 +257,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task StartJobAsync_DispatchedJob_SetsRunning() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, agentId); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); await _service.DispatchJobAsync(job.Id, CancellationToken.None); @@ -264,7 +276,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task CompleteJobAsync_RunningJob_SetsCompleted() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, agentId); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); await _service.DispatchJobAsync(job.Id, CancellationToken.None); await _service.StartJobAsync(job.Id, CancellationToken.None); @@ -284,7 +297,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task FailJobAsync_RunningJob_TriggersRetry() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, agentId); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); await _service.DispatchJobAsync(job.Id, CancellationToken.None); await _service.StartJobAsync(job.Id, CancellationToken.None); @@ -304,7 +318,8 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime public async Task FailJobAsync_ExceedsMaxRetries_DeadLetters() { var (siteId, cameraId) = await SeedSiteAndCameraAsync(); - await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + var agentId = await SeedAgentAsync(siteId, "Agent", hasGpu: false, cpuCores: 4, memoryMb: 8192); + await AssignCameraAsync(cameraId, agentId); var job = await CreateJobInDbAsync(cameraId, siteId, AnalysisJobType.MotionDetection, AnalysisJobPriority.Periodic); for (var i = 0; i < 3; i++) @@ -384,6 +399,14 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime return camera.Id; } + private async Task AssignCameraAsync(Guid cameraId, Guid agentId) + { + await using var db = await _dbFactory.CreateDbContextAsync(); + var camera = await db.Cameras.SingleAsync(c => c.Id == cameraId); + camera.AssignAgent(agentId); + await db.SaveChangesAsync(); + } + private async Task SeedAgentAsync( Guid siteId, string name, bool hasGpu, int cpuCores, long memoryMb, AgentStatus status = AgentStatus.Online) @@ -408,6 +431,9 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime switch (jobType) { case AnalysisJobType.ObjectDetection: + job.SetCapabilityRequirements(requiresGpu: false, requiredCpuCores: 2, requiredMemoryMb: 2048); + job.SetTimeout(TimeSpan.FromMinutes(10)); + break; case AnalysisJobType.FullSceneAnalysis: job.SetCapabilityRequirements(requiresGpu: true, requiredCpuCores: 2, requiredMemoryMb: 2048); job.SetTimeout(TimeSpan.FromMinutes(10)); diff --git a/todo.md b/todo.md index 2951006..51554ea 100644 --- a/todo.md +++ b/todo.md @@ -10,6 +10,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] Retirer `build-agent` de `runner-aaja` et le réserver aux runners de build autorisés. Le run PR #193 lui avait été affecté puis annulé ; le propriétaire a confirmé le retrait du label le 24 octobre 2026. Le run PR #194 s'exécute sur `runner-odin`. - [x] Valider le nettoyage Docker borné avant/après CI sur `runner-odin`. Les runs PR #189 et #191 avaient échoué pendant `dotnet build` avec `No space left on device`. Le run PR #194 a récupéré 95,89 Go avant build, ramené l'utilisation du disque de 97 % à 17 %, puis libéré 7,703 Go après job ; compilation, 1 965 tests, images et sécurité sont passés. Le script retire les anciennes images Heimdall, les volumes Trivy orphelins, les couches de build inutilisées de plus de 30 minutes et les images pendantes, sans purger les volumes ni les images nommées des autres projets. - [ ] Vérifier en exécution les secrets Docker Hub déclarés au niveau de l'organisation, puis un push des images serveur `eltruncho/heimdall` et agent `eltruncho/heimdall-agent` après merge sur `main`, avec tags `latest` et `sha-`. Namespace `eltruncho` confirmé par le propriétaire le 24 octobre 2026 ; la liste des secrets d'organisation n'est pas lisible avec le jeton actuel. +- [ ] Provisionner `RELEASE_SERVER_URL` comme variable Gitea, puis vérifier la publication signée et le registre sélectionné par `docker/server-image.json` et `docker/agent-image.json`. La PR #61 rend les noms d'images et l'origine des images configurables ; aucun push de release n'a été réalisé. - [ ] Réparer l'accès des conteneurs de job au serveur de cache/artefacts des runners (`cache.host`/réseau/port). Le run #442 a passé compilation, 1 965 tests, archives, images et sécurité, puis a échoué à `CreateArtifact: EHOSTUNREACH`. Restaurer les TRX et rapports comme artefacts lorsque l'endpoint est accessible. - [ ] Vérifier que le secret d'organisation `RENOVATE_TOKEN` est disponible au workflow, qu'il appartient à un compte bot Gitea et que la tâche planifiée crée des PR de dépendances avec lockfiles NuGet actualisés. - [ ] Vérifier la protection de `main` : contrôles obligatoires, merge d'une PR rouge refusé, aucun secret de publication exposé aux PR. @@ -19,7 +20,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant ## P1 — parcours caméra, agent et données - [ ] **PIPE-09** Valider sur caméra réelle capture automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. -- [ ] **PIPE-01/02** Décider si une analyse à la demande distribuée est requise. Si oui, construire une file PostgreSQL/outbox durable, bail atomique, routage ciblé via Agent, accusé, résultat idempotent et dead letter. Ne pas réintroduire RabbitMQ sans verticale complète démontrée. +- [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. CI et parcours avec deux agents, timeout/réessai et résultats tardifs restent à valider ; les autres types d'analyse ne sont pas pris en charge. - [ ] **PIPE-10 / FEAT-05** Vérifier une coupure réseau et reprise sans perte ni doublon ; ajouter outbox transactionnelle serveur, état de livraison et limitation par destinataire/canal. Tester SMTP/ntfy réels et échappement HTML. - [ ] **OPS-02** Généraliser la destination d'objet enregistrée aux médias futurs, traiter destinations perdues et lignes historiques sans inventer d'emplacement, supprimer les objets avant leurs références SQL. Vérifier réconciliation staging/finale et changement de provider. - [ ] **OPS-05 / AGENT-06** Installer clés de signature CI et clés publiques indépendantes de Central côté Agent ; tester release réelle, digest/signature, mise à jour native et Docker, arrêt propre et rollback.