diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 75bb1a2..d4ddebf 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -280,9 +280,9 @@ jobs: } >> "$GITHUB_OUTPUT" # ───────────────────────────────────────────────────────────────────────── - # TESTS DB — download artifacts + PostgreSQL local + # TESTS DB — Infrastructure (parallèle avec Integration) # ───────────────────────────────────────────────────────────────────────── - test-db: + test-db-infra: name: Tests DB (Infrastructure) needs: [build, changes] if: needs.changes.outputs.db_changed == 'true' @@ -318,14 +318,14 @@ jobs: sleep 1 done su - postgres -c "psql -c \"CREATE USER app WITH PASSWORD 'password';\"" 2>/dev/null || true - su - postgres -c "psql -c \"CREATE DATABASE app_test OWNER app;\"" 2>/dev/null || true - PGPASSWORD=password psql -U app -d app_test -h localhost -c "SELECT 1" > /dev/null - echo "PostgreSQL prêt" + su - postgres -c "psql -c \"CREATE DATABASE heimdall_infra_$\$ OWNER app;\"" 2>/dev/null || true + PGPASSWORD=password psql -U app -d heimdall_infra_$\$ -h localhost -c "SELECT 1" > /dev/null + echo "PostgreSQL prêt (infra)" - name: Run Infrastructure tests shell: bash env: - DATABASE_URL: Host=localhost;Port=5432;Database=app_test;Username=app;Password=password + DATABASE_URL: Host=localhost;Port=5432;Database=heimdall_infra_$\$;Username=app;Password=password run: | set -euo pipefail mkdir -p /tmp/coverage @@ -350,6 +350,78 @@ jobs: echo "EOF" } >> "$GITHUB_OUTPUT" + # ───────────────────────────────────────────────────────────────────────── + # TESTS DB — Integration (parallèle avec Infrastructure) + # ───────────────────────────────────────────────────────────────────────── + test-db-integration: + name: Tests DB (Integration) + needs: [build, changes] + if: needs.changes.outputs.db_changed == 'true' + runs-on: debian-12 + timeout-minutes: 20 + outputs: + summary: ${{ steps.gen-summary.outputs.summary }} + steps: + - uses: https://forgejo.tordais.cc/actions/checkout@v4 + + - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 + with: + dotnet-version: '10.0' + + - name: Download build artifacts + uses: https://forgejo.tordais.cc/actions/download-artifact@v3 + with: + name: build-output + + - name: Start PostgreSQL + shell: bash + run: | + set -euo pipefail + apt-get -qq update + apt-get install -y -qq --no-install-recommends postgresql-15 postgresql-client-15 + PGDATA=/tmp/pgdata + rm -rf "$PGDATA" + su - postgres -c "/usr/lib/postgresql/15/bin/initdb -D $PGDATA --auth=trust --no-locale --encoding=UTF8" + su - postgres -c "echo -e 'host all all 127.0.0.1/32 md5\nhost all all ::1/128 md5' >> $PGDATA/pg_hba.conf" + su - postgres -c "/usr/lib/postgresql/15/bin/pg_ctl -D $PGDATA -l /tmp/pgdata.log start" + for i in $(seq 1 15); do + su - postgres -c "/usr/lib/postgresql/15/bin/pg_isready -h localhost" > /dev/null 2>&1 && break + sleep 1 + done + su - postgres -c "psql -c \"CREATE USER app WITH PASSWORD 'password';\"" 2>/dev/null || true + su - postgres -c "psql -c \"CREATE DATABASE heimdall_integ_$\$ OWNER app;\"" 2>/dev/null || true + PGPASSWORD=password psql -U app -d heimdall_integ_$\$ -h localhost -c "SELECT 1" > /dev/null + echo "PostgreSQL prêt (integration)" + + - name: Run Integration tests + shell: bash + env: + DATABASE_URL: Host=localhost;Port=5432;Database=heimdall_integ_$\$;Username=app;Password=password + ASPNETCORE_ENVIRONMENT: Testing + run: | + set -euo pipefail + mkdir -p /tmp/coverage + LOG=/tmp/Heimdall.IntegrationTests.log + dotnet test tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj --no-build -c Release --nologo --blame-hang-timeout 180s \ + -p:CollectCoverage=true -p:CoverletOutputFormat=cobertura \ + -p:CoverletOutput=/tmp/coverage/Integration/ > "$LOG" 2>&1 || { + tail -40 "$LOG" | sed 's/^/ /' + exit 1 + } + grep -h -E "(Passed!|Failed!|Failed:|error CS)" "$LOG" 2>/dev/null || true + + - name: Générer le résumé + id: gen-summary + if: always() + shell: bash + run: | + SUMMARY=$(python3 scripts/ci/parse_test_log.py /tmp/*.log --coverage-dir /tmp/coverage 2>/dev/null || true) + { + echo "summary<> "$GITHUB_OUTPUT" + # ───────────────────────────────────────────────────────────────────────── # SONARQUBE — analyse (non bloquant, gate en warning) # ───────────────────────────────────────────────────────────────────────── @@ -690,7 +762,7 @@ jobs: post-summary: name: Résumé tests (PR) if: always() && github.event_name == 'pull_request' - needs: [changes, test-unit, test-web, test-db] + needs: [changes, test-unit, test-web, test-db-infra, test-db-integration] runs-on: debian-12 timeout-minutes: 10 steps: @@ -704,7 +776,7 @@ jobs: PR_NUMBER: ${{ github.event.pull_request.number }} S_UNIT: ${{ needs.test-unit.outputs.summary }} S_WEB: ${{ needs.test-web.outputs.summary }} - S_DB: ${{ needs.test-db.outputs.summary }} + S_DB: ${{ needs.test-db-infra.outputs.summary }} WEB_SKIPPED: ${{ needs.changes.outputs.web_changed }} DB_SKIPPED: ${{ needs.changes.outputs.db_changed }} run: | @@ -750,7 +822,7 @@ jobs: name: ci runs-on: debian-12 if: always() - needs: [build, test-unit, test-web, test-db, sonar, docker, dependency-check, post-summary] + needs: [build, test-unit, test-web, test-db-infra, test-db-integration, sonar, docker, dependency-check, post-summary] steps: - name: Vérifier les résultats shell: bash diff --git a/Makefile b/Makefile index 25f6d3a..6531c8e 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # ─── Heimdall — Development & Deployment ────────────────────────── .DEFAULT_GOAL := help -.PHONY: help build test docker-up docker-down docker-build clean dev +.PHONY: help build test docker-up docker-down docker-build clean dev backup backup-alarik restore backup-test help: ## Show this help @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | \ @@ -83,3 +83,41 @@ dev-web: ## Run combined API+Web+Jobs in development mode (single process) ASPNETCORE_ENVIRONMENT=Development \ Cors__AllowedOrigins="*" \ dotnet run --project src/Heimdall.Web + +# ─── Backup & Restore ────────────────────────────────────────── + +backup: ## Run PostgreSQL backup (daily — pg_dump + upload to Alarik/S3) + chmod +x docker/scripts/backup.sh + POSTGRES_HOST=localhost POSTGRES_PORT=5432 \ + POSTGRES_DB=heimdall POSTGRES_USER=heimdall POSTGRES_PASSWORD=heimdall \ + ./docker/scripts/backup.sh + +backup-alarik: ## Run Alarik/S3 mirror backup (weekly — snapshots + recordings) + chmod +x docker/scripts/backup-alarik.sh + ./docker/scripts/backup-alarik.sh + +restore: ## Restore PostgreSQL from latest backup (⚠️ drops current DB) + chmod +x docker/scripts/restore.sh + POSTGRES_HOST=localhost POSTGRES_PORT=5432 \ + POSTGRES_DB=heimdall POSTGRES_USER=heimdall POSTGRES_PASSWORD=heimdall \ + ./docker/scripts/restore.sh --latest --yes + +restore-file: ## Restore from a specific backup file (usage: make restore-file FILE=/path/to/dump.sql.gz) + @test -n "$(FILE)" || (echo "Usage: make restore-file FILE=/path/to/dump.sql.gz"; exit 1) + chmod +x docker/scripts/restore.sh + POSTGRES_HOST=localhost POSTGRES_PORT=5432 \ + POSTGRES_DB=heimdall POSTGRES_USER=heimdall POSTGRES_PASSWORD=heimdall \ + ./docker/scripts/restore.sh --file "$(FILE)" --yes + +backup-test: ## Run backup/restore E2E test (isolated PostgreSQL) + chmod +x docker/scripts/test-backup-restore.sh + ./docker/scripts/test-backup-restore.sh + +backup-up: ## Start backup cron service (daily PG + weekly Alarik mirror) + docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml up -d backup + +backup-down: ## Stop backup cron service + docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml down backup + +backup-logs: ## Tail backup service logs + docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml logs -f backup diff --git a/docker/docker-compose.backup.yml b/docker/docker-compose.backup.yml new file mode 100644 index 0000000..2b46899 --- /dev/null +++ b/docker/docker-compose.backup.yml @@ -0,0 +1,70 @@ +# ─── Heimdall — Backup Cron Service ────────────────────────────── +# Overlay for docker-compose.yml: adds a cron container that runs +# PostgreSQL backups daily and Alarik mirrors weekly. +# +# Usage: +# docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml up -d +# +# The cron service mounts the scripts directory and a backup volume. +# PostgreSQL dumps are uploaded to Alarik/S3 when configured. +# +# Requires: .env with DATABASE_URL, S3 credentials (optional for local-only backups) +# ────────────────────────────────────────────────────────────────── +services: + backup: + image: postgres:17-alpine + container_name: heimdall-backup + restart: unless-stopped + environment: + # Pass through all env vars needed by backup scripts + POSTGRES_HOST: postgresql + POSTGRES_PORT: "5432" + POSTGRES_DB: ${POSTGRES_DB:-heimdall} + POSTGRES_USER: ${POSTGRES_USER:-heimdall} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-heimdall} + # S3/Alarik config (optional — backup works local-only without these) + ALARIK_ENDPOINT: ${ALARIK_ENDPOINT:-} + ALARIK_ACCESS_KEY: ${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}} + ALARIK_SECRET_KEY: ${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}} + ALARIK_BUCKET: ${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}} + # Backup config + BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-30} + BACKUP_RETENTION_WEEKS: ${BACKUP_RETENTION_WEEKS:-12} + BACKUP_LOCAL_DIR: /backups + # Timezone + TZ: Europe/Paris + volumes: + - ./scripts:/scripts:ro + - backup_data:/backups + depends_on: + postgresql: + condition: service_healthy + networks: + - heimdall-net + entrypoint: ["/bin/sh", "-c"] + command: + - | + # Install mc (MinIO client) for S3 uploads + apk add --no-cache curl bash > /dev/null 2>&1 || true + curl -sSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc 2>/dev/null || true + chmod +x /usr/local/bin/mc 2>/dev/null || true + chmod +x /scripts/*.sh + + # Create crontab + echo "# Daily PostgreSQL backup at 02:00 UTC" > /tmp/crontab.txt + echo "0 2 * * * /scripts/backup.sh >> /var/log/backup.log 2>&1" >> /tmp/crontab.txt + echo "# Weekly Alarik mirror on Sundays at 03:00 UTC" >> /tmp/crontab.txt + echo "0 3 * * 0 /scripts/backup-alarik.sh >> /var/log/backup-alarik.log 2>&1" >> /tmp/crontab.txt + echo "# Log rotation weekly" >> /tmp/crontab.txt + echo "0 4 * * 0 if [ -f /var/log/backup.log ]; then mv /var/log/backup.log /var/log/backup.log.\$$(date +\%Y\%W); fi" >> /tmp/crontab.txt + + crontab /tmp/crontab.txt + echo "Crontab installed:" + crontab -l + + # Run crond in foreground + exec crond -f -l 2 + +volumes: + backup_data: + driver: local diff --git a/docker/scripts/backup-alarik.sh b/docker/scripts/backup-alarik.sh new file mode 100755 index 0000000..8158641 --- /dev/null +++ b/docker/scripts/backup-alarik.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# ─── Heimdall — Alarik/S3 Mirror Backup (weekly) ──────────────── +# Mirrors the heimdall bucket to a backup prefix with versioning. +# This captures snapshots, recordings, and other S3-stored data. +# +# Usage: +# ./backup-alarik.sh # defaults from env / .env +# ./backup-alarik.sh --dry-run # show what would be done +# BACKUP_RETENTION_WEEKS=8 ./backup-alarik.sh +# +# Required env vars: +# ALARIK_ENDPOINT (or S3_ENDPOINT), ALARIK_ACCESS_KEY (or S3_ACCESS_KEY), +# ALARIK_SECRET_KEY (or S3_SECRET_KEY), ALARIK_BUCKET (default: heimdall) +# +# Optional: +# BACKUP_RETENTION_WEEKS (default: 12) +# DRY_RUN (set to 1 for dry-run) +# ────────────────────────────────────────────────────────────────── +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)" + +# ── Load .env if present ──────────────────────────────────────── +ENV_FILE="${PROJECT_DIR}/docker/.env" +if [[ -f "$ENV_FILE" ]]; then + set -a + # shellcheck disable=SC1091 + source "$ENV_FILE" + set +a +fi + +# ── Configuration ─────────────────────────────────────────────── +S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}" +S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}" +S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}" +S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}" +BACKUP_PREFIX="backup/alarik" +RETENTION_WEEKS="${BACKUP_RETENTION_WEEKS:-12}" +TIMESTAMP="$(date -u +%Y-%m-%dT%H-%M-%SZ)" +WEEK_TAG="$(date -u +%Y-W%V)" +IS_DRY_RUN="${DRY_RUN:-0}" + +# ── Helpers ───────────────────────────────────────────────────── +log() { echo "[alarik-backup] $(date -u +%H:%M:%S) $*"; } +warn() { log "WARN: $*"; } +die() { log "FATAL: $*"; exit 1; } + +# ── Preflight ─────────────────────────────────────────────────── +[[ -z "$S3_ENDPOINT" ]] && die "S3_ENDPOINT not set — cannot mirror Alarik" + +if command -v mc >/dev/null 2>&1; then + CLIENT="mc" + mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null +elif command -v aws >/dev/null 2>&1; then + CLIENT="aws" +else + die "Neither 'mc' (MinIO client) nor 'aws' CLI found" +fi + +# ── Step 1: Mirror bucket to backup prefix ────────────────────── +log "Mirroring s3://${S3_BUCKET} → s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/" + +if [[ "$IS_DRY_RUN" == "1" ]]; then + log "[DRY-RUN] Would mirror all objects from ${S3_BUCKET} to ${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/" +else + if [[ "$CLIENT" == "mc" ]]; then + # mc mirror: copies new/changed objects, skips unchanged + # --overwrite: always copy (we want a point-in-time snapshot) + # --exclude "backup/*": don't mirror our own backups (avoid recursion) + mc mirror \ + "heimdall-backup/${S3_BUCKET}" \ + "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}" \ + --overwrite \ + --exclude "backup/*" \ + 2>&1 | tail -10 + else + # AWS CLI: sync with exclusion + aws --endpoint-url "$S3_ENDPOINT" s3 sync \ + "s3://${S3_BUCKET}" \ + "s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}" \ + --exclude "backup/*" \ + 2>&1 | tail -10 + fi + log "Mirror complete" +fi + +# ── Step 2: Prune old weekly backups ──────────────────────────── +CUTOFF_WEEK=$(date -u -d "${RETENTION_WEEKS} weeks ago" +%Y-W%V 2>/dev/null || \ + date -u -v-"${RETENTION_WEEKS}"w +%Y-W%V 2>/dev/null || echo "") + +if [[ -n "$CUTOFF_WEEK" ]]; then + log "Pruning weekly backups older than ${RETENTION_WEEKS} weeks (cutoff: ${CUTOFF_WEEK})..." + if [[ "$IS_DRY_RUN" != "1" ]]; then + if [[ "$CLIENT" == "mc" ]]; then + mc ls "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/" 2>/dev/null | \ + awk '{print $NF}' | \ + tr -d '/' | \ + while read -r week; do + if [[ -n "$week" && "$week" < "$CUTOFF_WEEK" ]]; then + log " Deleting: ${BACKUP_PREFIX}/${week}/" + mc rm --recursive --force "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" 2>/dev/null || true + fi + done + fi + fi +fi + +# ── Step 3: Create manifest ──────────────────────────────────── +MANIFEST_KEY="${BACKUP_PREFIX}/${WEEK_TAG}/MANIFEST.txt" +if [[ "$IS_DRY_RUN" != "1" ]]; then + log "Creating manifest..." + OBJECT_COUNT=0 + TOTAL_SIZE=0 + + if [[ "$CLIENT" == "mc" ]]; then + STATS=$(mc ls "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/" --recursive --summarize 2>/dev/null | tail -2) + OBJECT_COUNT=$(echo "$STATATS" | grep -oP 'Objects: \K\d+' || echo "0") + TOTAL_SIZE=$(echo "$STATATS" | grep -oP 'Size: \K\d+' || echo "0") + fi + + MANIFEST="Heimdall Alarik Backup Manifest +================================ +Week: ${WEEK_TAG} +Created: ${TIMESTAMP} +Bucket: ${S3_BUCKET} +Objects: ${OBJECT_COUNT} +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 + fi + log "Manifest written: ${MANIFEST_KEY}" +fi + +log "Alarik backup complete ✓" +log " Location: s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/" diff --git a/docker/scripts/backup.sh b/docker/scripts/backup.sh new file mode 100755 index 0000000..84c4c46 --- /dev/null +++ b/docker/scripts/backup.sh @@ -0,0 +1,142 @@ +#!/usr/bin/env bash +# ─── Heimdall — PostgreSQL Daily Backup ────────────────────────── +# Runs pg_dump inside the PostgreSQL container, compresses, uploads +# to Alarik/S3 under backup/postgresql/YYYY-MM-DD/, and prunes +# backups older than RETENTION_DAYS. +# +# Usage: +# ./backup.sh # defaults from env / .env +# ./backup.sh --dry-run # show what would be done +# BACKUP_RETENTION_DAYS=14 ./backup.sh +# +# Required env vars (set in .env or export): +# POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD +# ALARIK_ENDPOINT (or S3_ENDPOINT), ALARIK_ACCESS_KEY (or S3_ACCESS_KEY), +# ALARIK_SECRET_KEY (or S3_SECRET_KEY), ALARIK_BUCKET (default: heimdall) +# +# Optional: +# BACKUP_RETENTION_DAYS (default: 30) +# BACKUP_LOCAL_DIR (default: /var/lib/heimdall/backups) +# DRY_RUN (set to 1 for dry-run) +# ────────────────────────────────────────────────────────────────── +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)" + +# ── Load .env if present ──────────────────────────────────────── +ENV_FILE="${PROJECT_DIR}/docker/.env" +if [[ -f "$ENV_FILE" ]]; then + set -a + # shellcheck disable=SC1091 + source "$ENV_FILE" + set +a +fi + +# ── Configuration ─────────────────────────────────────────────── +PG_HOST="${POSTGRES_HOST:-localhost}" +PG_PORT="${POSTGRES_PORT:-5432}" +PG_DB="${POSTGRES_DB:-heimdall}" +PG_USER="${POSTGRES_USER:-heimdall}" +PG_PASSWORD="${POSTGRES_PASSWORD:-heimdall}" + +S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}" +S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}" +S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}" +S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}" +S3_PREFIX="backup/postgresql" + +RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-30}" +LOCAL_DIR="${BACKUP_LOCAL_DIR:-/var/lib/heimdall/backups}" +TIMESTAMP="$(date -u +%Y-%m-%dT%H-%M-%SZ)" +DATE_TAG="$(date -u +%Y-%m-%d)" +DUMP_FILE="${LOCAL_DIR}/postgresql/heimdall-${TIMESTAMP}.sql.gz" +IS_DRY_RUN="${DRY_RUN:-0}" + +# ── Helpers ───────────────────────────────────────────────────── +log() { echo "[backup] $(date -u +%H:%M:%S) $*"; } +warn() { log "WARN: $*"; } +die() { log "FATAL: $*"; exit 1; } + +# ── Preflight ─────────────────────────────────────────────────── +command -v pg_dump >/dev/null 2>&1 || die "pg_dump not found — install postgresql-client" +command -v mc >/dev/null 2>&1 || command -v aws >/dev/null 2>&1 || die "Neither 'mc' (MinIO client) nor 'aws' CLI found" + +if [[ -z "$S3_ENDPOINT" ]]; then + warn "S3_ENDPOINT not set — backup will be local only (no upload)" +fi + +mkdir -p "${LOCAL_DIR}/postgresql" + +# ── Step 1: pg_dump ───────────────────────────────────────────── +log "Starting PostgreSQL backup: ${PG_DB}@${PG_HOST}:${PG_PORT}" +if [[ "$IS_DRY_RUN" == "1" ]]; then + log "[DRY-RUN] Would run: pg_dump -h $PG_HOST -p $PG_PORT -U $PG_USER -d $PG_DB | gzip > $DUMP_FILE" +else + PGPASSWORD="$PG_PASSWORD" pg_dump \ + -h "$PG_HOST" \ + -p "$PG_PORT" \ + -U "$PG_USER" \ + -d "$PG_DB" \ + --format=custom \ + --compress=9 \ + --verbose \ + -f "$DUMP_FILE" \ + 2>&1 | tail -5 + log "Dump created: $(du -h "$DUMP_FILE" | cut -f1) → $DUMP_FILE" +fi + +# ── Step 2: Upload to Alarik/S3 ──────────────────────────────── +S3_KEY="${S3_PREFIX}/${DATE_TAG}/heimdall-${TIMESTAMP}.sql.gz" +S3_LATEST_KEY="${S3_PREFIX}/latest.sql.gz" + +if [[ -n "$S3_ENDPOINT" ]]; then + log "Uploading to S3: s3://${S3_BUCKET}/${S3_KEY}" + if [[ "$IS_DRY_RUN" == "1" ]]; then + log "[DRY-RUN] Would upload to s3://${S3_BUCKET}/${S3_KEY}" + else + # Try mc first, fallback to aws + if command -v mc >/dev/null 2>&1; then + mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null + 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 + fi + log "Upload complete" + fi +else + warn "Skipping S3 upload (no endpoint configured)" +fi + +# ── Step 3: Prune old local backups ───────────────────────────── +log "Pruning local backups older than ${RETENTION_DAYS} days..." +PRUNED=$(find "${LOCAL_DIR}/postgresql" -name "*.sql.gz" -mtime +"$RETENTION_DAYS" -print -delete 2>/dev/null | wc -l) +log "Pruned ${PRUNED} local backup(s)" + +# ── Step 4: Prune old S3 backups ──────────────────────────────── +if [[ -n "$S3_ENDPOINT" && "$IS_DRY_RUN" != "1" ]]; then + log "Pruning S3 backups older than ${RETENTION_DAYS} days..." + CUTOFF_DATE=$(date -u -d "${RETENTION_DAYS} days ago" +%Y-%m-%d 2>/dev/null || date -u -v-"${RETENTION_DAYS}"d +%Y-%m-%d 2>/dev/null || echo "") + if [[ -n "$CUTOFF_DATE" ]]; then + if command -v mc >/dev/null 2>&1; then + # List and delete old daily backups + mc ls "heimdall-backup/${S3_BUCKET}/${S3_PREFIX}/" --recursive 2>/dev/null | \ + awk '{print $NF}' | \ + grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}/' | \ + while read -r key; do + # Extract date from key: backup/postgresql/YYYY-MM-DD/... + key_date=$(echo "$key" | grep -oP '\d{4}-\d{2}-\d{2}' | head -1) + if [[ -n "$key_date" && "$key_date" < "$CUTOFF_DATE" ]]; then + log " Deleting: $key" + mc rm "heimdall-backup/${S3_BUCKET}/${key}" 2>/dev/null || true + fi + done + fi + fi +fi + +log "Backup complete ✓" +log " Local: ${DUMP_FILE}" +[[ -n "$S3_ENDPOINT" ]] && log " S3: s3://${S3_BUCKET}/${S3_KEY}" diff --git a/docker/scripts/restore.sh b/docker/scripts/restore.sh new file mode 100755 index 0000000..830793d --- /dev/null +++ b/docker/scripts/restore.sh @@ -0,0 +1,193 @@ +#!/usr/bin/env bash +# ─── Heimdall — PostgreSQL Restore from Backup ─────────────────── +# Downloads a backup from Alarik/S3 (or uses a local file) and +# restores it to the PostgreSQL database. +# +# Usage: +# ./restore.sh --file /path/to/backup.sql.gz # local file +# ./restore.sh --s3-key backup/postgresql/latest.sql.gz # from S3 +# ./restore.sh --latest # most recent from S3 +# +# ⚠️ This DROPS and RECREATES the target database. +# A confirmation prompt is shown unless --yes is passed. +# +# Required env vars (set in .env or export): +# POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD +# (S3 vars only needed for --s3-key or --latest) +# ────────────────────────────────────────────────────────────────── +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)" + +# ── Load .env if present ──────────────────────────────────────── +ENV_FILE="${PROJECT_DIR}/docker/.env" +if [[ -f "$ENV_FILE" ]]; then + set -a + # shellcheck disable=SC1091 + source "$ENV_FILE" + set +a +fi + +# ── Configuration ─────────────────────────────────────────────── +PG_HOST="${POSTGRES_HOST:-localhost}" +PG_PORT="${POSTGRES_PORT:-5432}" +PG_DB="${POSTGRES_DB:-heimdall}" +PG_USER="${POSTGRES_USER:-heimdall}" +PG_PASSWORD="${POSTGRES_PASSWORD:-heimdall}" + +S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}" +S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}" +S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}" +S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}" + +LOCAL_DIR="${BACKUP_LOCAL_DIR:-/var/lib/heimdall/backups}" +RESTORE_TMP="${LOCAL_DIR}/.restore-tmp" +AUTO_YES=0 + +# ── Helpers ───────────────────────────────────────────────────── +log() { echo "[restore] $(date -u +%H:%M:%S) $*"; } +warn() { log "WARN: $*"; } +die() { log "FATAL: $*"; exit 1; } + +usage() { + cat </dev/null 2>&1 || command -v psql >/dev/null 2>&1 || \ + die "pg_restore or psql not found — install postgresql-client" + +if [[ "$USE_LATEST" == "1" || -n "$S3_KEY" ]]; then + [[ -z "$S3_ENDPOINT" ]] && die "S3_ENDPOINT not set — required for S3 restore" + command -v mc >/dev/null 2>&1 || command -v aws >/dev/null 2>&1 || \ + die "Neither 'mc' (MinIO client) nor 'aws' CLI found" +fi + +mkdir -p "$RESTORE_TMP" + +# ── Step 1: Get the backup file ───────────────────────────────── +if [[ "$USE_LATEST" == "1" ]]; then + S3_KEY="backup/postgresql/latest.sql.gz" +fi + +if [[ -n "$S3_KEY" ]]; then + log "Downloading from S3: s3://${S3_BUCKET}/${S3_KEY}" + FILE="${RESTORE_TMP}/restore-$(date -u +%Y%m%d%H%M%S).sql.gz" + + if [[ "$IS_DRY_RUN" == "1" ]]; then + log "[DRY-RUN] Would download s3://${S3_BUCKET}/${S3_KEY} → $FILE" + log "[DRY-RUN] Would restore to ${PG_DB}@${PG_HOST}:${PG_PORT}" + exit 0 + fi + + if command -v mc >/dev/null 2>&1; 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 + fi + log "Downloaded: $(du -h "$FILE" | cut -f1)" +fi + +[[ ! -f "$FILE" ]] && die "Backup file not found: $FILE" + +# ── Step 2: Confirm ───────────────────────────────────────────── +if [[ "$AUTO_YES" != "1" && "$IS_DRY_RUN" != "1" ]]; then + echo "" + echo "⚠️ WARNING: This will DROP and RESTORE the database '${PG_DB}'." + echo " Backup file: ${FILE}" + echo " Target: ${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB}" + echo "" + read -rp "Type 'RESTORE' to confirm: " CONFIRM + [[ "$CONFIRM" != "RESTORE" ]] && { log "Aborted."; exit 1; } +fi + +# ── Step 3: Terminate existing connections ─────────────────────── +log "Terminating existing connections to ${PG_DB}..." +PGPASSWORD="$PG_PASSWORD" psql \ + -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres \ + -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${PG_DB}' AND pid <> pg_backend_pid();" \ + 2>/dev/null || warn "Could not terminate connections (may be first restore)" + +# ── Step 4: Drop and recreate database ────────────────────────── +log "Dropping and recreating database ${PG_DB}..." +if [[ "$IS_DRY_RUN" != "1" ]]; then + PGPASSWORD="$PG_PASSWORD" psql \ + -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres \ + -c "DROP DATABASE IF EXISTS ${PG_DB};" \ + -c "CREATE DATABASE ${PG_DB} OWNER ${PG_USER};" \ + 2>&1 | tail -5 +fi + +# ── Step 5: Restore ───────────────────────────────────────────── +log "Restoring from backup..." +if [[ "$IS_DRY_RUN" != "1" ]]; then + # Try pg_restore first (for custom format dumps) + if pg_restore --version 2>/dev/null | grep -q "."; then + PGPASSWORD="$PG_PASSWORD" pg_restore \ + -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" \ + -d "$PG_DB" \ + --no-owner \ + --no-privileges \ + --verbose \ + "$FILE" 2>&1 | tail -10 || true + else + # Fallback: psql for plain SQL dumps + gunzip -c "$FILE" | PGPASSWORD="$PG_PASSWORD" psql \ + -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$PG_DB" \ + --quiet 2>&1 | tail -10 + fi +fi + +# ── Step 6: Verify ────────────────────────────────────────────── +log "Verifying restore..." +if [[ "$IS_DRY_RUN" != "1" ]]; then + TABLE_COUNT=$(PGPASSWORD="$PG_PASSWORD" psql \ + -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$PG_DB" \ + -t -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';" \ + 2>/dev/null | tr -d ' ') + ROW_COUNT=$(PGPASSWORD="$PG_PASSWORD" psql \ + -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$PG_DB" \ + -t -c "SELECT SUM(n_live_tup) FROM pg_stat_user_tables;" \ + 2>/dev/null | tr -d ' ' || echo "0") + log " Tables: ${TABLE_COUNT:-0}" + log " Rows: ${ROW_COUNT:-0}" +fi + +# ── Cleanup ───────────────────────────────────────────────────── +rm -f "${RESTORE_TMP}"/*.sql.gz 2>/dev/null +rmdir "$RESTORE_TMP" 2>/dev/null || true + +log "Restore complete ✓" diff --git a/docker/scripts/test-backup-restore.sh b/docker/scripts/test-backup-restore.sh new file mode 100755 index 0000000..29870f1 --- /dev/null +++ b/docker/scripts/test-backup-restore.sh @@ -0,0 +1,235 @@ +#!/usr/bin/env bash +# ─── Heimdall — Backup/Restore E2E Test ───────────────────────── +# Creates a test backup, restores it into a temporary database, +# and verifies data integrity. Uses Docker to run PostgreSQL +# independently from the main stack. All DB operations go through +# docker exec (no host psql required). +# +# Usage: +# ./test-backup-restore.sh # runs the full test +# ./test-backup-restore.sh --no-cleanup # leave test containers running +# +# Requirements: +# - Docker +# - gzip, tar (standard on Linux) +# ────────────────────────────────────────────────────────────────── +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +TEST_DB="heimdall_backup_test" +TEST_PORT=15432 +TEST_USER="testbackup" +TEST_PASS="testbackup123" +CONTAINER_NAME="heimdall-pg-backup-test" +CLEANUP=1 + +# ── Helpers ───────────────────────────────────────────────────── +log() { echo "[backup-test] $(date -u +%H:%M:%S) $*"; } +pass() { log "✅ PASS: $*"; } +fail() { log "❌ FAIL: $*"; FAILURES=$((FAILURES + 1)); } +die() { log "FATAL: $*"; exit 1; } + +# Run psql inside the test container — connect to target DB. +# After DROP/CREATE the DB name is reused so psql -d $TEST_DB reconnects. +run_sql() { + docker exec "$CONTAINER_NAME" psql -U "$TEST_USER" -d "$TEST_DB" -t -A -c "$1" 2>/dev/null +} + +run_sql_raw() { + local sql_file + sql_file=$(mktemp /tmp/heimdall-test-XXXXXX.sql) + echo "$1" > "$sql_file" + docker cp "$sql_file" "${CONTAINER_NAME}:/tmp/test-query.sql" + docker exec "$CONTAINER_NAME" psql -U "$TEST_USER" -d "$TEST_DB" -f /tmp/test-query.sql 2>/dev/null + rm -f "$sql_file" +} + +# Drop DB helper — connects to 'postgres' to avoid dangling session +drop_and_recreate_db() { + local sql_file + sql_file=$(mktemp /tmp/heimdall-test-XXXXXX.sql) + cat > "$sql_file" < pg_backend_pid(); +DROP DATABASE IF EXISTS ${TEST_DB}; +CREATE DATABASE ${TEST_DB} OWNER ${TEST_USER}; +SQLEOF + docker cp "$sql_file" "${CONTAINER_NAME}:/tmp/drop-recreate.sql" + docker exec "$CONTAINER_NAME" psql -U "$TEST_USER" -d postgres -f /tmp/drop-recreate.sql >/dev/null 2>&1 + rm -f "$sql_file" +} + +FAILURES=0 +TESTS=0 + +run_test() { + local name="$1" + shift + TESTS=$((TESTS + 1)) + log "TEST ${TESTS}: ${name}" + if "$@"; then + pass "$name" + else + fail "$name" + fi +} + +# ── Parse arguments ───────────────────────────────────────────── +for arg in "$@"; do + case "$arg" in + --no-cleanup) CLEANUP=0 ;; + esac +done + +# ── Cleanup on exit ───────────────────────────────────────────── +cleanup() { + if [[ "$CLEANUP" == "1" ]]; then + log "Cleaning up test environment..." + docker rm -f "$CONTAINER_NAME" 2>/dev/null || true + docker network rm heimdall-backup-test-net 2>/dev/null || true + rm -rf "${SCRIPT_DIR}/.test-backup-tmp" 2>/dev/null + fi +} +trap cleanup EXIT + +# ── Setup: Start isolated PostgreSQL ───────────────────────────── +log "Setting up isolated PostgreSQL for backup test..." + +docker network create heimdall-backup-test-net 2>/dev/null || true +docker rm -f "$CONTAINER_NAME" 2>/dev/null || true + +docker run -d \ + --name "$CONTAINER_NAME" \ + --network heimdall-backup-test-net \ + -e POSTGRES_DB="$TEST_DB" \ + -e POSTGRES_USER="$TEST_USER" \ + -e POSTGRES_PASSWORD="$TEST_PASS" \ + -p "${TEST_PORT}:5432" \ + postgres:17-alpine + +log "Waiting for PostgreSQL to be ready..." +for i in $(seq 1 30); do + if docker exec "$CONTAINER_NAME" pg_isready -U "$TEST_USER" >/dev/null 2>&1; then + log "PostgreSQL ready after ${i}s" + break + fi + [[ $i -eq 30 ]] && die "PostgreSQL did not start in time" + sleep 1 +done + +# ── Step 1: Seed test data ────────────────────────────────────── +log "Seeding test data..." +run_sql_raw " +CREATE TABLE IF NOT EXISTS sites ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name TEXT NOT NULL, + created_at TIMESTAMPTZ DEFAULT now() +); +CREATE TABLE IF NOT EXISTS cameras ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + site_id UUID REFERENCES sites(id), + name TEXT NOT NULL, + rtsp_url TEXT, + created_at TIMESTAMPTZ DEFAULT now() +); +CREATE TABLE IF NOT EXISTS camera_events ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + camera_id UUID REFERENCES cameras(id), + event_type TEXT NOT NULL, + snapshot_url TEXT, + created_at TIMESTAMPTZ DEFAULT now() +); +INSERT INTO sites (id, name) VALUES + ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'Maison Principale'), + ('b0eebc99-9c0b-4ef8-bb6d-6bb9bd380a22', 'Garage'); +INSERT INTO cameras (id, site_id, name, rtsp_url) VALUES + ('c0eebc99-9c0b-4ef8-bb6d-6bb9bd380a33', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'Entrée', 'rtsp://192.168.1.100:554/stream1'), + ('d0eebc99-9c0b-4ef8-bb6d-6bb9bd380a44', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'Jardin', 'rtsp://192.168.1.100:554/stream2'), + ('e0eebc99-9c0b-4ef8-bb6d-6bb9bd380a55', 'b0eebc99-9c0b-4ef8-bb6d-6bb9bd380a22', 'Garage Intérieur', 'rtsp://192.168.1.101:554/stream1'); +INSERT INTO camera_events (camera_id, event_type, snapshot_url) VALUES + ('c0eebc99-9c0b-4ef8-bb6d-6bb9bd380a33', 'motion', 'https://alarik.local/snapshots/s1.jpg'), + ('c0eebc99-9c0b-4ef8-bb6d-6bb9bd380a33', 'person', 'https://alarik.local/snapshots/s2.jpg'), + ('d0eebc99-9c0b-4ef8-bb6d-6bb9bd380a44', 'vehicle', 'https://alarik.local/snapshots/s3.jpg'), + ('e0eebc99-9c0b-4ef8-bb6d-6bb9bd380a55', 'motion', 'https://alarik.local/snapshots/s4.jpg'); +" +log "Test data seeded" + +# ── Capture pre-backup counts ─────────────────────────────────── +PRE_SITES=$(run_sql "SELECT COUNT(*) FROM sites;") +PRE_CAMERAS=$(run_sql "SELECT COUNT(*) FROM cameras;") +PRE_EVENTS=$(run_sql "SELECT COUNT(*) FROM camera_events;") +log "Pre-backup: ${PRE_SITES} sites, ${PRE_CAMERAS} cameras, ${PRE_EVENTS} events" + +# ── Step 2: Create backup using pg_dump ───────────────────────── +TEST_BACKUP_DIR="${SCRIPT_DIR}/.test-backup-tmp" +mkdir -p "$TEST_BACKUP_DIR" +DUMP_FILE="${TEST_BACKUP_DIR}/test-backup.sql.gz" + +log "Creating backup with pg_dump..." +docker exec "$CONTAINER_NAME" pg_dump \ + -U "$TEST_USER" -d "$TEST_DB" \ + --format=custom --compress=9 \ + -f "/tmp/test-backup.sql.gz" + +docker cp "${CONTAINER_NAME}:/tmp/test-backup.sql.gz" "$DUMP_FILE" +docker exec "$CONTAINER_NAME" rm -f /tmp/test-backup.sql.gz + +[[ -f "$DUMP_FILE" ]] || die "Backup file not created" +DUMP_SIZE=$(du -h "$DUMP_FILE" | cut -f1) +log "Backup created: ${DUMP_SIZE}" + +run_test "Backup file exists and is non-empty" test -s "$DUMP_FILE" + +# ── Step 3: Drop and recreate database ────────────────────────── +log "Dropping and recreating test database..." +drop_and_recreate_db + +# Verify empty +EMPTY_TABLES=$(run_sql "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';") +run_test "Database is empty after drop" test "$EMPTY_TABLES" -eq 0 + +# ── Step 4: Restore from backup ───────────────────────────────── +log "Restoring from backup..." +docker cp "$DUMP_FILE" "${CONTAINER_NAME}:/tmp/restore-dump.sql.gz" +docker exec "$CONTAINER_NAME" pg_restore \ + -U "$TEST_USER" -d "$TEST_DB" \ + --no-owner --no-privileges \ + /tmp/restore-dump.sql.gz 2>&1 | tail -5 || true +docker exec "$CONTAINER_NAME" rm -f /tmp/restore-dump.sql.gz + +# ── Step 5: Verify restored data ──────────────────────────────── +POST_SITES=$(run_sql "SELECT COUNT(*) FROM sites;") +POST_CAMERAS=$(run_sql "SELECT COUNT(*) FROM cameras;") +POST_EVENTS=$(run_sql "SELECT COUNT(*) FROM camera_events;") + +log "Post-restore: ${POST_SITES} sites, ${POST_CAMERAS} cameras, ${POST_EVENTS} events" + +run_test "Site count matches" test "$POST_SITES" -eq "$PRE_SITES" +run_test "Camera count matches" test "$POST_CAMERAS" -eq "$PRE_CAMERAS" +run_test "Event count matches" test "$POST_EVENTS" -eq "$PRE_EVENTS" + +# ── Step 6: Verify specific data integrity ────────────────────── +SITE_NAME=$(run_sql "SELECT name FROM sites WHERE id = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11';") +run_test "Site name preserved" test "$SITE_NAME" = "Maison Principale" + +CAMERA_RTSP=$(run_sql "SELECT rtsp_url FROM cameras WHERE name = 'Entrée';") +run_test "Camera RTSP URL preserved" test "$CAMERA_RTSP" = "rtsp://192.168.1.100:554/stream1" + +FK_VIOLATIONS=$(run_sql " + SELECT COUNT(*) FROM camera_events e + WHERE NOT EXISTS (SELECT 1 FROM cameras c WHERE c.id = e.camera_id); +") +run_test "No FK violations in restored data" test "$FK_VIOLATIONS" -eq 0 + +# ── Summary ───────────────────────────────────────────────────── +echo "" +log "═══════════════════════════════════════════" +log " Test Results: $((TESTS - FAILURES))/${TESTS} passed" +log "═══════════════════════════════════════════" + +if [[ $FAILURES -gt 0 ]]; then + log "Some tests FAILED ❌" + exit 1 +else + log "All tests PASSED ✅" + exit 0 +fi diff --git a/src/Heimdall.Application/Vehicles/Commands/CreateVehicle/CreateVehicleCommand.cs b/src/Heimdall.Application/Vehicles/Commands/CreateVehicle/CreateVehicleCommand.cs index cbb2c98..7afc020 100644 --- a/src/Heimdall.Application/Vehicles/Commands/CreateVehicle/CreateVehicleCommand.cs +++ b/src/Heimdall.Application/Vehicles/Commands/CreateVehicle/CreateVehicleCommand.cs @@ -18,12 +18,12 @@ public class CreateVehicleCommandHandler : IRequestHandler _db = db; - public async Task> Handle(CreateVehicleCommand request, CancellationToken cancellationToken) + public async Task> Handle(CreateVehicleCommand request, CancellationToken ct) { var vehicle = new Vehicle(request.LicensePlate, request.PersonId, request.Make, request.Model, request.Color); _db.Vehicles.Add(vehicle); - await _db.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false); + await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); return ServiceResult.Success(Map(vehicle, 0)); } diff --git a/src/Heimdall.Application/Vehicles/Commands/DeleteVehicle/DeleteVehicleCommand.cs b/src/Heimdall.Application/Vehicles/Commands/DeleteVehicle/DeleteVehicleCommand.cs index d3f3ad7..ef3ebf5 100644 --- a/src/Heimdall.Application/Vehicles/Commands/DeleteVehicle/DeleteVehicleCommand.cs +++ b/src/Heimdall.Application/Vehicles/Commands/DeleteVehicle/DeleteVehicleCommand.cs @@ -12,14 +12,14 @@ public class DeleteVehicleCommandHandler : IRequestHandler _db = db; - public async Task Handle(DeleteVehicleCommand request, CancellationToken cancellationToken) + public async Task Handle(DeleteVehicleCommand request, CancellationToken ct) { - var vehicle = await _db.Vehicles.FindAsync([request.Id], cancellationToken).ConfigureAwait(false); + var vehicle = await _db.Vehicles.FindAsync([request.Id], ct).ConfigureAwait(false); if (vehicle is null) return ServiceResult.NotFound("Vehicle not found"); _db.Vehicles.Remove(vehicle); - await _db.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false); + await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); return ServiceResult.Success(); } diff --git a/src/Heimdall.Application/Vehicles/Commands/UpdateVehicle/UpdateVehicleCommand.cs b/src/Heimdall.Application/Vehicles/Commands/UpdateVehicle/UpdateVehicleCommand.cs index a403dde..7d0e9a1 100644 --- a/src/Heimdall.Application/Vehicles/Commands/UpdateVehicle/UpdateVehicleCommand.cs +++ b/src/Heimdall.Application/Vehicles/Commands/UpdateVehicle/UpdateVehicleCommand.cs @@ -20,11 +20,11 @@ public class UpdateVehicleCommandHandler : IRequestHandler _db = db; - public async Task> Handle(UpdateVehicleCommand request, CancellationToken cancellationToken) + public async Task> Handle(UpdateVehicleCommand request, CancellationToken ct) { var vehicle = await _db.Vehicles .Include(v => v.Person) - .FirstOrDefaultAsync(v => v.Id == request.Id, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(v => v.Id == request.Id, ct).ConfigureAwait(false); if (vehicle is null) return ServiceResult.NotFound("Vehicle not found"); @@ -36,9 +36,9 @@ public class UpdateVehicleCommandHandler : IRequestHandler e.VehicleId == request.Id, cancellationToken).ConfigureAwait(false); + var eventCount = await _db.CameraEvents.CountAsync(e => e.VehicleId == request.Id, ct).ConfigureAwait(false); return ServiceResult.Success(Map(vehicle, eventCount)); } diff --git a/src/Heimdall.Application/Vehicles/Queries/GetVehicle/GetVehicleQuery.cs b/src/Heimdall.Application/Vehicles/Queries/GetVehicle/GetVehicleQuery.cs index 48eefe3..6fefc1b 100644 --- a/src/Heimdall.Application/Vehicles/Queries/GetVehicle/GetVehicleQuery.cs +++ b/src/Heimdall.Application/Vehicles/Queries/GetVehicle/GetVehicleQuery.cs @@ -25,11 +25,11 @@ public class GetVehicleQueryHandler : IRequestHandler _db = db; - public async Task> Handle(GetVehicleQuery request, CancellationToken cancellationToken) + public async Task> Handle(GetVehicleQuery request, CancellationToken ct) { var vehicle = await _db.Vehicles .Include(v => v.Person) - .FirstOrDefaultAsync(v => v.Id == request.Id, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(v => v.Id == request.Id, ct).ConfigureAwait(false); if (vehicle is null) return ServiceResult.NotFound("Vehicle not found"); @@ -40,7 +40,7 @@ public class GetVehicleQueryHandler : IRequestHandler e.OccurredAt) .Take(50) .AsNoTracking() - .ToListAsync(cancellationToken).ConfigureAwait(false); + .ToListAsync(ct).ConfigureAwait(false); var eventSummaries = events.Select(e => new VehicleEventSummary( e.Id, @@ -50,7 +50,7 @@ public class GetVehicleQueryHandler : IRequestHandler e.VehicleId == request.Id, cancellationToken).ConfigureAwait(false); + .CountAsync(e => e.VehicleId == request.Id, ct).ConfigureAwait(false); return ServiceResult.Success(new VehicleDetailResponse( vehicle.Id, diff --git a/src/Heimdall.Application/Vehicles/Queries/GetVehicles/GetVehiclesQuery.cs b/src/Heimdall.Application/Vehicles/Queries/GetVehicles/GetVehiclesQuery.cs index 98c2cef..2912366 100644 --- a/src/Heimdall.Application/Vehicles/Queries/GetVehicles/GetVehiclesQuery.cs +++ b/src/Heimdall.Application/Vehicles/Queries/GetVehicles/GetVehiclesQuery.cs @@ -15,7 +15,7 @@ public class GetVehiclesQueryHandler : IRequestHandler _db = db; - public async Task>> Handle(GetVehiclesQuery request, CancellationToken cancellationToken) + public async Task>> Handle(GetVehiclesQuery request, CancellationToken ct) { var query = _db.Vehicles .Include(v => v.Person) @@ -31,14 +31,14 @@ public class GetVehiclesQueryHandler : IRequestHandler v.LicensePlate) .Skip((request.Page - 1) * request.PageSize) .Take(request.PageSize) - .ToListAsync(cancellationToken).ConfigureAwait(false); + .ToListAsync(ct).ConfigureAwait(false); var vehicleIds = vehicles.Select(v => v.Id).ToList(); var eventCounts = await _db.CameraEvents .Where(e => vehicleIds.Contains(e.VehicleId!.Value)) .GroupBy(e => e.VehicleId) .Select(g => new { VehicleId = g.Key, Count = g.Count() }) - .ToListAsync(cancellationToken).ConfigureAwait(false); + .ToListAsync(ct).ConfigureAwait(false); var countMap = eventCounts.ToDictionary(x => x.VehicleId!.Value, x => x.Count);