refactor: use EF Core for SQLite persistence
Heimdall Gitea / Detect CI scope (pull_request) Successful in 4s
Heimdall Gitea / Build and tests (pull_request) Successful in 14m48s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 4m24s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 9m12s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 4s

This commit is contained in:
Arnaud Dartois committed 2026-10-26 08:19:44 +01:00
1 parent 7c4cff90d8
commit f832d2fb62
36 files changed
+1174 -309

No files matched your search

+3 -1
View File
@@ -162,7 +162,9 @@ jobs:
- name: Reclaim old Heimdall build storage
run: bash scripts/ci/cleanup-docker.sh before
- name: CI script contracts
run: python3 -m unittest discover -s scripts/ci -p 'test_*.py'
run: |
python3 -m unittest discover -s scripts/ci -p 'test_*.py'
python3 scripts/ci/check-efcore-usage.py
- name: Validate Compose and build .NET solution
run: |
mkdir -p artifacts/tests artifacts/security
+2 -1
View File
@@ -3,9 +3,10 @@
- Read `todo.md` before changing code. Update its status and acceptance notes in the same PR as each correction or feature. Remove a completed item only after the behavior is verified; keep a short completion entry for traceability.
- Keep `Domain` independent of infrastructure. Put use cases and interfaces in `Application`, adapters and EF Core persistence in `Infrastructure`, HTTP/UI composition in `Web`, and camera/runtime behavior in `Agent`.
- Target the SDK pinned by `global.json` and .NET 10 or newer. Use nullable reference types, cancellation tokens for I/O, and explicit options validation. Do not weaken locked restore or suppress a new warning without a reason.
- For EF Core changes, preserve PostgreSQL behavior, add a migration for schema changes, and verify queries with an integration test when translation, concurrency, or deletion semantics matter. Never reuse a `DbContext` across concurrent operations.
- Use EF Core for production database reads and writes. Do not use direct ADO.NET or provider commands in production code; provider-specific EF SQL is allowed only for capabilities LINQ cannot express, with a nearby rationale and a test. The CI persistence policy enforces this boundary. Preserve PostgreSQL behavior, add migrations for schema changes, and verify translation, concurrency, and deletion semantics with relational tests. Never reuse a `DbContext` across concurrent operations.
- Keep tenant/site and camera authorization checks at API and application boundaries. Do not log credentials, RTSP URLs, embeddings, or raw tokens.
- CI jobs run only on `[ubuntu-latest, build-agent]`. Keep `runner-aaja` outside that label. Never use release credentials in pull request jobs.
- A PR touching deployment or publication must document required secrets and prove the relevant script locally. Do not claim a runner, registry, camera, or object store was validated without a real run.
See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance.
For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions.
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Reject direct database commands in production source outside documented EF exceptions."""
from pathlib import Path
import re
import sys
ROOT = Path(__file__).resolve().parents[2]
SOURCE_ROOT = ROOT / "src"
# These operations cannot be expressed portably through EF's LINQ/change tracker.
# Keep the exception narrow by path and explain it in the file next to the operation.
EF_CORE_EXCEPTIONS = {
"src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs": "PostgreSQL VACUUM/REINDEX and catalog inspection",
"src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs": "PostgreSQL partition DDL and catalog inspection",
"src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs": "transaction-scoped PostgreSQL advisory lock",
"src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs": "idempotent PostgreSQL bulk insert with ON CONFLICT DO NOTHING",
"src/Heimdall.Agent/Data/AgentOutboxDatabaseInitializer.cs": "baseline and migrate pre-EF local SQLite outbox schemas",
}
DATABASE_API = re.compile(
r"\b(?:Sqlite|Npgsql|Sql|MySql|Db)(?:Connection|Command|DataReader)\b"
r"|\.CreateCommand\s*\(|\.GetDbConnection\s*\(|\.CommandText\s*=|"
r"\.Execute(?:Reader|NonQuery|Scalar)(?:Async)?\s*\(|\b(?:ExecuteSqlRaw|ExecuteSqlInterpolated|"
r"SqlQueryRaw|SqlQuery|FromSqlRaw|FromSqlInterpolated|FromSql)\s*(?:Async)?\s*\(",
)
def inspect_source(path: str, content: str) -> list[str]:
"""Return policy violations for one repository-relative C# source file."""
if not path.startswith("src/") or "/Migrations/" in path or path.endswith(".Designer.cs"):
return []
if not DATABASE_API.search(content):
return []
rationale = EF_CORE_EXCEPTIONS.get(path)
if rationale and "EF Core exception:" in content:
return []
return [f"{path}: direct database API is not allowed; use EF Core or document an approved provider-specific exception"]
def check_tree(root: Path = ROOT) -> list[str]:
failures = []
for path in sorted((root / "src").rglob("*.cs")):
relative = path.relative_to(root).as_posix()
try:
content = path.read_text(encoding="utf-8-sig")
except UnicodeDecodeError:
failures.append(f"{relative}: source is not valid UTF-8")
continue
failures.extend(inspect_source(relative, content))
return failures
def main() -> int:
failures = check_tree()
if failures:
print("EF Core persistence policy violations:", file=sys.stderr)
print("\n".join(f"- {failure}" for failure in failures), file=sys.stderr)
return 1
print("EF Core persistence policy passed")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+23
View File
@@ -43,6 +43,29 @@ def load_test_plan():
spec.loader.exec_module(module)
return module
def load_efcore_policy():
spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class EfCorePolicyTests(unittest.TestCase):
def test_current_production_sources_follow_policy(self):
self.assertEqual(load_efcore_policy().check_tree(REPO_ROOT), [])
def test_agent_ado_net_is_rejected(self):
failures = load_efcore_policy().inspect_source(
'src/Heimdall.Agent/Services/Example.cs',
'using Microsoft.Data.Sqlite; var connection = new SqliteConnection();')
self.assertEqual(len(failures), 1)
def test_provider_specific_sql_requires_explicit_exception_marker(self):
policy = load_efcore_policy()
path = 'src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs'
self.assertEqual(policy.inspect_source(path, 'db.Database.ExecuteSqlRaw("VACUUM");'), [
f'{path}: direct database API is not allowed; use EF Core or document an approved provider-specific exception'])
self.assertEqual(policy.inspect_source(path, '// EF Core exception: PostgreSQL maintenance\ndb.Database.ExecuteSqlRaw("VACUUM");'), [])
class TestPlanTests(unittest.TestCase):
def test_domain_change_reaches_dependent_suites(self):
suites = load_test_plan().plan(['src/Heimdall.Domain/Camera.cs'])['suites']
+1
View File
@@ -9,6 +9,7 @@ else
docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet
fi
bash docker/scripts/test-backup-restore.sh
python3 scripts/ci/check-efcore-usage.py
dotnet restore Heimdall.slnx --locked-mode
dotnet build Heimdall.slnx -c Release --no-restore -m:2
# NuGet advisory report is kept separate from compiler warning suppressions.
+26
View File
@@ -0,0 +1,26 @@
---
name: ef-core-persistence
description: Implement or review database persistence in Heimdall with Entity Framework Core, including SQLite Agent stores and PostgreSQL behavior.
---
# Heimdall EF Core persistence
Use this skill whenever changing how application or Agent data is read or written.
- Use EF Core LINQ and entity configurations for CRUD. Prefer projections, bounded result sets, asynchronous APIs, and `CancellationToken`; use `AsNoTracking` for read-only entity queries.
- Create a short-lived `DbContext` per operation. Hosted services and concurrent workers should use `IDbContextFactory<TContext>` and dispose each context; never share a context across parallel work.
- Evolve schemas through reviewed EF Core migrations. Preserve deployed data and test upgrades from every supported on-disk schema, including Agent-local SQLite outboxes.
- Verify PostgreSQL translation, transaction boundaries, concurrency and deletion semantics against PostgreSQL integration tests when those behaviors matter. Do not use EF InMemory as proof of relational behavior.
- Do not issue CRUD through ADO.NET or hand-written SQL. Raw SQL through EF is an exception for database-specific capabilities that LINQ cannot express or for measured performance needs. Keep it parameterized, add an adjacent `EF Core exception:` comment with the reason, and add a test for its behavior.
- Migrations, test database setup, PostgreSQL maintenance/partition DDL, and locks with no portable EF equivalent are valid exceptions. Keep provider-specific code in Infrastructure or a dedicated adapter; do not spread it into use cases.
- Never enable sensitive-data logging in production. Do not log connection strings or persisted secret values.
Before editing, inspect this repository's `AGENTS.md`, `todo.md`, model configuration, latest migration, and callers. After editing, run the relevant suite and CI persistence policy check, then update the corresponding TODO item with evidence and remaining deployment checks.
## Microsoft references
- [EF Core efficient querying](https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying)
- [EF Core tracking and no-tracking](https://learn.microsoft.com/en-us/ef/core/querying/tracking)
- [EF Core raw SQL queries](https://learn.microsoft.com/en-us/ef/core/querying/sql-queries)
- [EF Core migrations](https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/)
- [SQLite provider for EF Core](https://learn.microsoft.com/en-us/ef/core/providers/sqlite/)
+2
View File
@@ -9,6 +9,8 @@ Read `AGENTS.md` and the relevant item in `todo.md` first. Trace a feature throu
For persistence changes, inspect the entity configuration and latest migration, then verify PostgreSQL translation and transactions with focused integration tests. Keep migrations compatible with existing rows, record the data backfill or rollback requirement, and avoid client-side filtering on access-controlled queries.
For detailed database access rules and the allowlist for unavoidable provider-specific SQL, follow [the EF Core persistence skill](../ef-core-persistence/SKILL.md).
For application commands, validate at the boundary, enforce site/camera scope in the use case, and make external side effects retry-safe. For agent work, account for disconnected operation, bounded queues, cancellation, and resource disposal.
After the change, run the smallest meaningful test suite plus the build when public contracts change. Update the matching `todo.md` entry with what passed and what still requires a deployed runner, camera, network, or object store.
@@ -0,0 +1,114 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Agent.Data;
internal static class AgentOutboxDatabaseInitializer
{
private const string EfProductVersion = "10.0.13";
private const string EventsMigration = "202610260001_InitialAgentEventsOutbox";
private const string StatusMigration = "202610260002_InitialAgentStatusOutbox";
public static string CreateConnectionString(string path) => new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = SqliteOpenMode.ReadWriteCreate,
DefaultTimeout = 5
}.ToString();
public static async Task InitializeEventsAsync(
IDbContextFactory<AgentEventsDbContext> factory,
string path,
CancellationToken ct)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await AdoptLegacyDatabaseAsync(factory, path, EventsMigration,
["pending_detection_events", "dead_letter_detection_events"],
"pending_detection_events", addSnapshotColumn: true, ct).ConfigureAwait(false);
await using var db = await factory.CreateDbContextAsync(ct).ConfigureAwait(false);
await db.Database.MigrateAsync(ct).ConfigureAwait(false);
await ConfigureSqliteAsync(db, version: 2, ct).ConfigureAwait(false);
RestrictDatabaseFile(path);
}
public static async Task InitializeStatusesAsync(
IDbContextFactory<AgentStatusDbContext> factory,
string path,
CancellationToken ct)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await AdoptLegacyDatabaseAsync(factory, path, StatusMigration,
["pending_camera_status", "acknowledged_camera_status"],
null, addSnapshotColumn: false, ct).ConfigureAwait(false);
await using var db = await factory.CreateDbContextAsync(ct).ConfigureAwait(false);
await db.Database.MigrateAsync(ct).ConfigureAwait(false);
await ConfigureSqliteAsync(db, version: 1, ct).ConfigureAwait(false);
RestrictDatabaseFile(path);
}
private static async Task AdoptLegacyDatabaseAsync<TContext>(
IDbContextFactory<TContext> factory,
string path,
string migrationId,
string[] expectedTables,
string? tableToInspect,
bool addSnapshotColumn,
CancellationToken ct)
where TContext : DbContext
{
if (!File.Exists(path))
return;
await using var db = await factory.CreateDbContextAsync(ct).ConfigureAwait(false);
var tables = await db.Database.SqlQueryRaw<string>("""
SELECT name AS Value FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
""").ToListAsync(ct).ConfigureAwait(false);
if (tables.Count == 0)
return;
if (expectedTables.Any(table => !tables.Contains(table, StringComparer.Ordinal)))
throw new InvalidDataException("Agent outbox database has an incomplete legacy schema; refusing to migrate it automatically.");
if (tableToInspect is not null)
{
var columns = await db.Database.SqlQueryRaw<string>(
"SELECT name AS Value FROM pragma_table_info('pending_detection_events')")
.ToListAsync(ct).ConfigureAwait(false);
if (addSnapshotColumn && !columns.Contains("snapshot_jpeg", StringComparer.Ordinal))
{
// EF Core exception: upgrade the deployed v1 SQLite schema before baselining it.
await db.Database.ExecuteSqlRawAsync(
"ALTER TABLE pending_detection_events ADD COLUMN snapshot_jpeg BLOB NULL", ct).ConfigureAwait(false);
}
}
// EF Core exception: adopt the pre-EF local database into EF's migration history,
// preserving its queued rows and then let EF apply future migrations normally.
await db.Database.ExecuteSqlRawAsync("""
CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
"MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,
"ProductVersion" TEXT NOT NULL)
""", ct).ConfigureAwait(false);
await db.Database.ExecuteSqlInterpolatedAsync($"""
INSERT OR IGNORE INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ({migrationId}, {EfProductVersion})
""", ct).ConfigureAwait(false);
}
private static async Task ConfigureSqliteAsync(DbContext db, int version, CancellationToken ct)
{
await db.Database.ExecuteSqlRawAsync("PRAGMA journal_mode=WAL", ct).ConfigureAwait(false);
await db.Database.ExecuteSqlRawAsync("PRAGMA synchronous=FULL", ct).ConfigureAwait(false);
var versionStatement = version == 2 ? "PRAGMA user_version=2" : "PRAGMA user_version=1";
await db.Database.ExecuteSqlRawAsync(versionStatement, ct).ConfigureAwait(false);
}
private static void RestrictDatabaseFile(string path)
{
if (!OperatingSystem.IsLinux())
return;
try { File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
}
@@ -0,0 +1,96 @@
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Agent.Data;
internal sealed class AgentEventsDbContext(DbContextOptions<AgentEventsDbContext> options) : DbContext(options)
{
public DbSet<PendingDetectionEvent> PendingEvents => Set<PendingDetectionEvent>();
public DbSet<DeadLetterDetectionEvent> DeadLetters => Set<DeadLetterDetectionEvent>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PendingDetectionEvent>(entity =>
{
entity.ToTable("pending_detection_events");
entity.HasKey(row => row.EventId);
entity.Property(row => row.EventId).HasColumnName("event_id").HasMaxLength(36);
entity.Property(row => row.EventType).HasColumnName("event_type");
entity.Property(row => row.Priority).HasColumnName("priority");
entity.Property(row => row.PayloadJson).HasColumnName("payload_json");
entity.Property(row => row.CreatedAt).HasColumnName("created_at");
entity.Property(row => row.Attempts).HasColumnName("attempts");
entity.Property(row => row.SnapshotJpeg).HasColumnName("snapshot_jpeg");
entity.HasIndex(row => new { row.Priority, row.CreatedAt })
.HasDatabaseName("ix_pending_detection_events_priority_created");
});
modelBuilder.Entity<DeadLetterDetectionEvent>(entity =>
{
entity.ToTable("dead_letter_detection_events");
entity.HasKey(row => row.EventId);
entity.Property(row => row.EventId).HasColumnName("event_id").HasMaxLength(36);
entity.Property(row => row.PayloadJson).HasColumnName("payload_json");
entity.Property(row => row.CreatedAt).HasColumnName("created_at");
entity.Property(row => row.LastError).HasColumnName("last_error");
entity.Property(row => row.Attempts).HasColumnName("attempts");
entity.HasIndex(row => row.CreatedAt).HasDatabaseName("ix_dead_letter_detection_events_created");
});
}
}
internal sealed class AgentStatusDbContext(DbContextOptions<AgentStatusDbContext> options) : DbContext(options)
{
public DbSet<PendingCameraStatus> PendingStatuses => Set<PendingCameraStatus>();
public DbSet<AcknowledgedCameraStatus> AcknowledgedStatuses => Set<AcknowledgedCameraStatus>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PendingCameraStatus>(entity =>
{
entity.ToTable("pending_camera_status");
entity.HasKey(row => row.CameraId);
entity.Property(row => row.CameraId).HasColumnName("camera_id").HasMaxLength(36);
entity.Property(row => row.Status).HasColumnName("status");
entity.Property(row => row.UpdatedAt).HasColumnName("updated_at");
});
modelBuilder.Entity<AcknowledgedCameraStatus>(entity =>
{
entity.ToTable("acknowledged_camera_status");
entity.HasKey(row => row.CameraId);
entity.Property(row => row.CameraId).HasColumnName("camera_id").HasMaxLength(36);
entity.Property(row => row.Status).HasColumnName("status");
});
}
}
internal sealed class PendingDetectionEvent
{
public string EventId { get; set; } = string.Empty;
public int EventType { get; set; }
public int Priority { get; set; }
public string PayloadJson { get; set; } = string.Empty;
public string CreatedAt { get; set; } = string.Empty;
public int Attempts { get; set; }
public byte[]? SnapshotJpeg { get; set; }
}
internal sealed class DeadLetterDetectionEvent
{
public string EventId { get; set; } = string.Empty;
public string PayloadJson { get; set; } = string.Empty;
public string CreatedAt { get; set; } = string.Empty;
public string LastError { get; set; } = string.Empty;
public int Attempts { get; set; }
}
internal sealed class PendingCameraStatus
{
public string CameraId { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
public string UpdatedAt { get; set; } = string.Empty;
}
internal sealed class AcknowledgedCameraStatus
{
public string CameraId { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
}
@@ -0,0 +1,86 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Heimdall.Agent.Data;
[DbContext(typeof(AgentEventsDbContext))]
[Migration("202610260001_InitialAgentEventsOutbox")]
internal sealed class InitialAgentEventsOutbox : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "pending_detection_events",
columns: table => new
{
event_id = table.Column<string>(type: "TEXT", maxLength: 36, nullable: false),
event_type = table.Column<int>(type: "INTEGER", nullable: false),
priority = table.Column<int>(type: "INTEGER", nullable: false),
payload_json = table.Column<string>(type: "TEXT", nullable: false),
created_at = table.Column<string>(type: "TEXT", nullable: false),
attempts = table.Column<int>(type: "INTEGER", nullable: false),
snapshot_jpeg = table.Column<byte[]>(type: "BLOB", nullable: true)
},
constraints: table => table.PrimaryKey("PK_pending_detection_events", row => row.event_id));
migrationBuilder.CreateTable(
name: "dead_letter_detection_events",
columns: table => new
{
event_id = table.Column<string>(type: "TEXT", maxLength: 36, nullable: false),
payload_json = table.Column<string>(type: "TEXT", nullable: false),
created_at = table.Column<string>(type: "TEXT", nullable: false),
last_error = table.Column<string>(type: "TEXT", nullable: false),
attempts = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table => table.PrimaryKey("PK_dead_letter_detection_events", row => row.event_id));
migrationBuilder.CreateIndex(
name: "ix_pending_detection_events_priority_created",
table: "pending_detection_events",
columns: new[] { "priority", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_dead_letter_detection_events_created",
table: "dead_letter_detection_events",
column: "created_at");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable("dead_letter_detection_events");
migrationBuilder.DropTable("pending_detection_events");
}
}
[DbContext(typeof(AgentStatusDbContext))]
[Migration("202610260002_InitialAgentStatusOutbox")]
internal sealed class InitialAgentStatusOutbox : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "pending_camera_status",
columns: table => new
{
camera_id = table.Column<string>(type: "TEXT", maxLength: 36, nullable: false),
status = table.Column<string>(type: "TEXT", nullable: false),
updated_at = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table => table.PrimaryKey("PK_pending_camera_status", row => row.camera_id));
migrationBuilder.CreateTable(
name: "acknowledged_camera_status",
columns: table => new
{
camera_id = table.Column<string>(type: "TEXT", maxLength: 36, nullable: false),
status = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table => table.PrimaryKey("PK_acknowledged_camera_status", row => row.camera_id));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable("acknowledged_camera_status");
migrationBuilder.DropTable("pending_camera_status");
}
}
@@ -0,0 +1,61 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Heimdall.Agent.Data;
[DbContext(typeof(AgentEventsDbContext))]
internal sealed class AgentEventsDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "10.0.13");
modelBuilder.Entity("Heimdall.Agent.Data.DeadLetterDetectionEvent", entity =>
{
entity.Property<string>("EventId").HasMaxLength(36).HasColumnType("TEXT").HasColumnName("event_id");
entity.Property<int>("Attempts").HasColumnType("INTEGER").HasColumnName("attempts");
entity.Property<string>("CreatedAt").IsRequired().HasColumnType("TEXT").HasColumnName("created_at");
entity.Property<string>("LastError").IsRequired().HasColumnType("TEXT").HasColumnName("last_error");
entity.Property<string>("PayloadJson").IsRequired().HasColumnType("TEXT").HasColumnName("payload_json");
entity.HasKey("EventId").HasName("PK_dead_letter_detection_events");
entity.HasIndex("CreatedAt").HasDatabaseName("ix_dead_letter_detection_events_created");
entity.ToTable("dead_letter_detection_events");
});
modelBuilder.Entity("Heimdall.Agent.Data.PendingDetectionEvent", entity =>
{
entity.Property<string>("EventId").HasMaxLength(36).HasColumnType("TEXT").HasColumnName("event_id");
entity.Property<int>("Attempts").HasColumnType("INTEGER").HasColumnName("attempts");
entity.Property<string>("CreatedAt").IsRequired().HasColumnType("TEXT").HasColumnName("created_at");
entity.Property<int>("EventType").HasColumnType("INTEGER").HasColumnName("event_type");
entity.Property<byte[]>("SnapshotJpeg").HasColumnType("BLOB").HasColumnName("snapshot_jpeg");
entity.Property<int>("Priority").HasColumnType("INTEGER").HasColumnName("priority");
entity.Property<string>("PayloadJson").IsRequired().HasColumnType("TEXT").HasColumnName("payload_json");
entity.HasKey("EventId").HasName("PK_pending_detection_events");
entity.HasIndex("Priority", "CreatedAt").HasDatabaseName("ix_pending_detection_events_priority_created");
entity.ToTable("pending_detection_events");
});
}
}
[DbContext(typeof(AgentStatusDbContext))]
internal sealed class AgentStatusDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "10.0.13");
modelBuilder.Entity("Heimdall.Agent.Data.AcknowledgedCameraStatus", entity =>
{
entity.Property<string>("CameraId").HasMaxLength(36).HasColumnType("TEXT").HasColumnName("camera_id");
entity.Property<string>("Status").IsRequired().HasColumnType("TEXT").HasColumnName("status");
entity.HasKey("CameraId").HasName("PK_acknowledged_camera_status");
entity.ToTable("acknowledged_camera_status");
});
modelBuilder.Entity("Heimdall.Agent.Data.PendingCameraStatus", entity =>
{
entity.Property<string>("CameraId").HasMaxLength(36).HasColumnType("TEXT").HasColumnName("camera_id");
entity.Property<string>("Status").IsRequired().HasColumnType("TEXT").HasColumnName("status");
entity.Property<string>("UpdatedAt").IsRequired().HasColumnType("TEXT").HasColumnName("updated_at");
entity.HasKey("CameraId").HasName("PK_pending_camera_status");
entity.ToTable("pending_camera_status");
});
}
}
+1 -1
View File
@@ -22,7 +22,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.13" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.13" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.22.0" />
<PackageReference Include="OpenTelemetry" Version="1.17.0" />
+1
View File
@@ -79,6 +79,7 @@ builder.Services.AddHttpClient("Broker", (sp, client) =>
// TPM/HSM-backed store or mount it outside the backed-up volume.
var stateDir = builder.Configuration["Agent:StateDirectory"]
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
Directory.CreateDirectory(stateDir);
var keysDir = Path.Combine(stateDir, "dp-keys");
Directory.CreateDirectory(keysDir);
if (OperatingSystem.IsLinux())
@@ -1,7 +1,9 @@
using System.Net.Http.Json;
using Heimdall.Agent;
using Heimdall.Agent.Data;
using Heimdall.Application.DTOs;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -21,6 +23,7 @@ public sealed class CameraStatusReporterService : BackgroundService, ICameraStat
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<CameraStatusReporterService> _logger;
private readonly string _databasePath;
private readonly PooledDbContextFactory<AgentStatusDbContext> _contextFactory;
private readonly SemaphoreSlim _wake = new(0, 1);
private readonly SemaphoreSlim _databaseWriteGate = new(1, 1);
private readonly SemaphoreSlim _databaseInitializationGate = new(1, 1);
@@ -41,6 +44,9 @@ public sealed class CameraStatusReporterService : BackgroundService, ICameraStat
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
Directory.CreateDirectory(stateDirectory);
_databasePath = Path.Combine(stateDirectory, "agent-outbox.db");
_contextFactory = new PooledDbContextFactory<AgentStatusDbContext>(
new DbContextOptionsBuilder<AgentStatusDbContext>()
.UseSqlite(AgentOutboxDatabaseInitializer.CreateConnectionString(_databasePath)).Options);
}
/// <summary>Number of failed status report attempts. Failed reports remain queued.</summary>
@@ -99,7 +105,7 @@ public sealed class CameraStatusReporterService : BackgroundService, ICameraStat
}
}
private async Task SendPendingStatusAsync(PendingCameraStatus pending, CancellationToken ct)
private async Task SendPendingStatusAsync(PendingStatusItem pending, CancellationToken ct)
{
try
{
@@ -127,42 +133,19 @@ public sealed class CameraStatusReporterService : BackgroundService, ICameraStat
}
}
private async Task<SqliteConnection> OpenDatabaseAsync(CancellationToken ct)
private async Task<AgentStatusDbContext> OpenDatabaseAsync(CancellationToken ct)
{
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = _databasePath,
Mode = SqliteOpenMode.ReadWriteCreate,
DefaultTimeout = 5
}.ToString());
await _databaseInitializationGate.WaitAsync(ct).ConfigureAwait(false);
try
{
await connection.OpenAsync(ct).ConfigureAwait(false);
await _databaseInitializationGate.WaitAsync(ct).ConfigureAwait(false);
try
if (!_databaseInitialized)
{
await using var command = connection.CreateCommand();
command.CommandText = _databaseInitialized
? "PRAGMA synchronous=FULL;"
: "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS pending_camera_status (camera_id TEXT PRIMARY KEY NOT NULL, status TEXT NOT NULL, updated_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS acknowledged_camera_status (camera_id TEXT PRIMARY KEY NOT NULL, status TEXT NOT NULL); PRAGMA user_version=1;";
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await AgentOutboxDatabaseInitializer.InitializeStatusesAsync(_contextFactory, _databasePath, ct).ConfigureAwait(false);
_databaseInitialized = true;
}
finally { _databaseInitializationGate.Release(); }
if (OperatingSystem.IsLinux())
{
try { File.SetUnixFileMode(_databasePath, UnixFileMode.UserRead | UnixFileMode.UserWrite); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
return connection;
}
catch
{
await connection.DisposeAsync().ConfigureAwait(false);
throw;
return await _contextFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
}
finally { _databaseInitializationGate.Release(); }
}
private async Task UpsertPendingStatusAsync(Guid cameraId, string status, CancellationToken ct)
@@ -170,72 +153,61 @@ public sealed class CameraStatusReporterService : BackgroundService, ICameraStat
await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false);
try
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using (var pendingCheck = connection.CreateCommand())
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
var key = cameraId.ToString("D");
var pending = await db.PendingStatuses.FindAsync([key], ct).ConfigureAwait(false);
if (pending is not null)
{
pendingCheck.CommandText = "SELECT status FROM pending_camera_status WHERE camera_id=$id;";
pendingCheck.Parameters.AddWithValue("$id", cameraId.ToString("D"));
var pendingStatus = await pendingCheck.ExecuteScalarAsync(ct).ConfigureAwait(false) as string;
if (pendingStatus is not null)
{
if (string.Equals(pendingStatus, status, StringComparison.Ordinal)) return;
}
else
{
await using var acknowledgedCheck = connection.CreateCommand();
acknowledgedCheck.CommandText = "SELECT status FROM acknowledged_camera_status WHERE camera_id=$id;";
acknowledgedCheck.Parameters.AddWithValue("$id", cameraId.ToString("D"));
if (string.Equals(await acknowledgedCheck.ExecuteScalarAsync(ct).ConfigureAwait(false) as string, status, StringComparison.Ordinal))
return;
}
if (string.Equals(pending.Status, status, StringComparison.Ordinal)) return;
pending.Status = status;
pending.UpdatedAt = DateTimeOffset.UtcNow.ToString("O");
}
await using var command = connection.CreateCommand();
command.CommandText = "INSERT INTO pending_camera_status(camera_id,status,updated_at) VALUES($id,$status,$updated) ON CONFLICT(camera_id) DO UPDATE SET status=excluded.status, updated_at=excluded.updated_at;";
command.Parameters.AddWithValue("$id", cameraId.ToString("D"));
command.Parameters.AddWithValue("$status", status);
command.Parameters.AddWithValue("$updated", DateTimeOffset.UtcNow.ToString("O"));
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
else
{
var acknowledged = await db.AcknowledgedStatuses.FindAsync([key], ct).ConfigureAwait(false);
if (string.Equals(acknowledged?.Status, status, StringComparison.Ordinal)) return;
db.PendingStatuses.Add(new PendingCameraStatus
{
CameraId = key,
Status = status,
UpdatedAt = DateTimeOffset.UtcNow.ToString("O")
});
}
await db.SaveChangesAsync(ct).ConfigureAwait(false);
}
finally { _databaseWriteGate.Release(); }
}
private async Task<List<PendingCameraStatus>> ReadPendingStatusesAsync(CancellationToken ct)
private async Task<List<PendingStatusItem>> ReadPendingStatusesAsync(CancellationToken ct)
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var command = connection.CreateCommand();
command.CommandText = "SELECT camera_id,status,updated_at FROM pending_camera_status ORDER BY updated_at;";
var results = new List<PendingCameraStatus>();
await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false))
if (Guid.TryParse(reader.GetString(0), out var id)) results.Add(new PendingCameraStatus(id, reader.GetString(1), reader.GetString(2)));
return results;
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
var rows = await db.PendingStatuses.AsNoTracking().OrderBy(item => item.UpdatedAt).ToListAsync(ct).ConfigureAwait(false);
return rows.Where(item => Guid.TryParse(item.CameraId, out _))
.Select(item => new PendingStatusItem(Guid.Parse(item.CameraId), item.Status, item.UpdatedAt)).ToList();
}
private async Task DeletePendingStatusAsync(PendingCameraStatus pending, CancellationToken ct)
private async Task DeletePendingStatusAsync(PendingStatusItem pending, CancellationToken ct)
{
await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false);
try
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var transaction = await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
await using var command = connection.CreateCommand();
command.CommandText = "DELETE FROM pending_camera_status WHERE camera_id=$id AND status=$status AND updated_at=$updated;";
command.Transaction = (SqliteTransaction)transaction;
command.Parameters.AddWithValue("$id", pending.CameraId.ToString("D"));
command.Parameters.AddWithValue("$status", pending.Status);
command.Parameters.AddWithValue("$updated", pending.UpdatedAt);
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await using var acknowledged = connection.CreateCommand();
acknowledged.Transaction = (SqliteTransaction)transaction;
acknowledged.CommandText = "INSERT INTO acknowledged_camera_status(camera_id,status) VALUES($id,$status) ON CONFLICT(camera_id) DO UPDATE SET status=excluded.status;";
acknowledged.Parameters.AddWithValue("$id", pending.CameraId.ToString("D"));
acknowledged.Parameters.AddWithValue("$status", pending.Status);
await acknowledged.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var transaction = await db.Database.BeginTransactionAsync(ct).ConfigureAwait(false);
var key = pending.CameraId.ToString("D");
var queued = await db.PendingStatuses.FirstOrDefaultAsync(item =>
item.CameraId == key && item.Status == pending.Status && item.UpdatedAt == pending.UpdatedAt, ct).ConfigureAwait(false);
if (queued is not null)
db.PendingStatuses.Remove(queued);
var acknowledged = await db.AcknowledgedStatuses.FindAsync([key], ct).ConfigureAwait(false);
if (acknowledged is null)
db.AcknowledgedStatuses.Add(new AcknowledgedCameraStatus { CameraId = key, Status = pending.Status });
else
acknowledged.Status = pending.Status;
await db.SaveChangesAsync(ct).ConfigureAwait(false);
await transaction.CommitAsync(ct).ConfigureAwait(false);
}
finally { _databaseWriteGate.Release(); }
}
private sealed record PendingCameraStatus(Guid CameraId, string Status, string UpdatedAt);
private sealed record PendingStatusItem(Guid CameraId, string Status, string UpdatedAt);
}
@@ -3,10 +3,12 @@ using System.Net.Http.Json;
using System.Text.Json;
using System.Text;
using Heimdall.Agent;
using Heimdall.Agent.Data;
using Heimdall.Application.DTOs;
using Heimdall.Application.Metrics;
using Heimdall.Domain.Enums;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -45,6 +47,7 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<DetectionReporterService> _logger;
private readonly string _databasePath;
private readonly PooledDbContextFactory<AgentEventsDbContext> _contextFactory;
private readonly ConcurrentDictionary<(Guid CameraId, EventType Type), DateTime> _lastQueued = new();
private readonly SemaphoreSlim _wake = new(0, 1);
private readonly SemaphoreSlim _databaseWriteGate = new(1, 1);
@@ -76,6 +79,9 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
var stateDirectory = options.Value.StateDirectory
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
_databasePath = Path.Combine(stateDirectory, "agent-events.db");
_contextFactory = new PooledDbContextFactory<AgentEventsDbContext>(
new DbContextOptionsBuilder<AgentEventsDbContext>()
.UseSqlite(AgentOutboxDatabaseInitializer.CreateConnectionString(_databasePath)).Options);
}
public long FailedReports => Interlocked.Read(ref _failedReports);
@@ -237,54 +243,19 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
}
}
private async Task<SqliteConnection> OpenDatabaseAsync(CancellationToken ct)
private async Task<AgentEventsDbContext> OpenDatabaseAsync(CancellationToken ct)
{
Directory.CreateDirectory(Path.GetDirectoryName(_databasePath)!);
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = _databasePath,
Mode = SqliteOpenMode.ReadWriteCreate,
DefaultTimeout = 5
}.ToString());
await _databaseInitializationGate.WaitAsync(ct).ConfigureAwait(false);
try
{
await connection.OpenAsync(ct).ConfigureAwait(false);
await _databaseInitializationGate.WaitAsync(ct).ConfigureAwait(false);
try
if (!_databaseInitialized)
{
await using var command = connection.CreateCommand();
command.CommandText = _databaseInitialized
? "PRAGMA synchronous=FULL;"
: "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS pending_detection_events (event_id TEXT PRIMARY KEY NOT NULL, event_type INTEGER NOT NULL, priority INTEGER NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS ix_pending_detection_events_priority_created ON pending_detection_events(priority DESC, created_at); CREATE TABLE IF NOT EXISTS dead_letter_detection_events (event_id TEXT PRIMARY KEY NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL, last_error TEXT NOT NULL, attempts INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS ix_dead_letter_detection_events_created ON dead_letter_detection_events(created_at);";
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
if (!_databaseInitialized)
{
await using var check = connection.CreateCommand();
check.CommandText = "SELECT COUNT(*) FROM pragma_table_info('pending_detection_events') WHERE name='snapshot_jpeg';";
if (Convert.ToInt32(await check.ExecuteScalarAsync(ct).ConfigureAwait(false), System.Globalization.CultureInfo.InvariantCulture) == 0)
{
await using var upgrade = connection.CreateCommand();
upgrade.CommandText = "ALTER TABLE pending_detection_events ADD COLUMN snapshot_jpeg BLOB NULL; PRAGMA user_version=2;";
await upgrade.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
}
await AgentOutboxDatabaseInitializer.InitializeEventsAsync(_contextFactory, _databasePath, ct).ConfigureAwait(false);
_databaseInitialized = true;
}
finally { _databaseInitializationGate.Release(); }
if (OperatingSystem.IsLinux())
{
try { File.SetUnixFileMode(_databasePath, UnixFileMode.UserRead | UnixFileMode.UserWrite); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
return connection;
}
catch
{
await connection.DisposeAsync().ConfigureAwait(false);
throw;
return await _contextFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
}
finally { _databaseInitializationGate.Release(); }
}
private async Task<bool> EnqueueAsync(CreateCameraEventRequest request, byte[]? snapshotJpeg, CancellationToken ct)
@@ -318,13 +289,20 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false);
try
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var transaction = await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(connection, (SqliteTransaction)transaction, ct).ConfigureAwait(false);
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var transaction = await db.Database.BeginTransactionAsync(ct).ConfigureAwait(false);
var queuedPayloads = await db.PendingEvents.AsNoTracking()
.Select(item => new { item.PayloadJson, item.SnapshotJpeg })
.ToListAsync(ct).ConfigureAwait(false);
var count = (long)queuedPayloads.Count;
var bytes = queuedPayloads.Sum(item => (long)Encoding.UTF8.GetByteCount(item.PayloadJson) + (item.SnapshotJpeg?.LongLength ?? 0));
while (count >= MaxPendingEvents || bytes + itemBytes > MaxOutboxBytes)
{
var evictedBytes = await EvictOldestMotionEventAsync(connection, transaction, ct).ConfigureAwait(false);
if (evictedBytes is null)
var oldestMotion = await db.PendingEvents
.Where(item => item.Priority == 0)
.OrderBy(item => item.CreatedAt)
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
if (oldestMotion is null)
{
Interlocked.Increment(ref _rejectedByCapacity);
HeimdallMetrics.RecordEventOutboxRejected("spool-full", request.Type.ToString());
@@ -332,23 +310,26 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
count, bytes, eventId, request.Type);
return false;
}
var evictedBytes = Encoding.UTF8.GetByteCount(oldestMotion.PayloadJson) + (oldestMotion.SnapshotJpeg?.LongLength ?? 0);
db.PendingEvents.Remove(oldestMotion);
await db.SaveChangesAsync(ct).ConfigureAwait(false);
count--;
bytes -= evictedBytes.Value;
bytes -= evictedBytes;
Interlocked.Increment(ref _rejectedByCapacity);
HeimdallMetrics.RecordEventOutboxRejected("evicted-motion", EventType.MotionDetected.ToString());
_logger.LogError("Detection outbox reached capacity; evicted the oldest motion event to retain event {EventId}", eventId);
}
await using var insert = connection.CreateCommand();
insert.Transaction = (SqliteTransaction)transaction;
insert.CommandText = "INSERT INTO pending_detection_events(event_id,event_type,priority,payload_json,created_at,snapshot_jpeg) VALUES($id,$type,$priority,$payload,$created,$snapshot);";
insert.Parameters.AddWithValue("$id", eventId.ToString("D"));
insert.Parameters.AddWithValue("$type", (int)request.Type);
insert.Parameters.AddWithValue("$priority", priority);
insert.Parameters.AddWithValue("$payload", payload);
insert.Parameters.AddWithValue("$created", DateTimeOffset.UtcNow.ToString("O"));
insert.Parameters.AddWithValue("$snapshot", (object?)snapshotJpeg ?? DBNull.Value);
await insert.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
db.PendingEvents.Add(new PendingDetectionEvent
{
EventId = eventId.ToString("D"),
EventType = (int)request.Type,
Priority = priority,
PayloadJson = payload,
CreatedAt = DateTimeOffset.UtcNow.ToString("O"),
SnapshotJpeg = snapshotJpeg
});
await db.SaveChangesAsync(ct).ConfigureAwait(false);
await transaction.CommitAsync(ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count + 1, bytes + itemBytes);
HeimdallMetrics.RecordEventCreated(request.Type.ToString(), request.CameraId);
@@ -358,65 +339,63 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
}
private static async Task<(long Count, long Bytes)> GetOutboxSizeAsync(
SqliteConnection connection, SqliteTransaction? transaction, CancellationToken ct)
AgentEventsDbContext db, CancellationToken ct)
{
await using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "SELECT COUNT(*), COALESCE(SUM(length(CAST(payload_json AS BLOB)) + COALESCE(length(snapshot_jpeg),0)),0) FROM pending_detection_events;";
await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
await reader.ReadAsync(ct).ConfigureAwait(false);
return (reader.GetInt64(0), reader.GetInt64(1));
}
private static async Task<long?> EvictOldestMotionEventAsync(
SqliteConnection connection, System.Data.Common.DbTransaction transaction, CancellationToken ct)
{
await using var command = connection.CreateCommand();
command.Transaction = (SqliteTransaction)transaction;
command.CommandText = "DELETE FROM pending_detection_events WHERE event_id=(SELECT event_id FROM pending_detection_events WHERE priority=0 ORDER BY created_at LIMIT 1) RETURNING length(CAST(payload_json AS BLOB)) + COALESCE(length(snapshot_jpeg),0);";
var result = await command.ExecuteScalarAsync(ct).ConfigureAwait(false);
return result is null or DBNull ? null : Convert.ToInt64(result, System.Globalization.CultureInfo.InvariantCulture);
var payloads = await db.PendingEvents.AsNoTracking()
.Select(item => new { item.PayloadJson, item.SnapshotJpeg })
.ToListAsync(ct).ConfigureAwait(false);
return (payloads.Count, payloads.Sum(item => (long)Encoding.UTF8.GetByteCount(item.PayloadJson) + (item.SnapshotJpeg?.LongLength ?? 0)));
}
private async Task<List<PendingDetection>> ReadPendingAsync(CancellationToken ct)
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(connection, null, ct).ConfigureAwait(false);
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(db, ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count, bytes);
await using var command = connection.CreateCommand();
command.CommandText = "SELECT event_id,payload_json,attempts,snapshot_jpeg FROM pending_detection_events ORDER BY priority DESC,created_at LIMIT $limit;";
command.Parameters.AddWithValue("$limit", ReadBatchSize);
var results = new List<PendingDetection>();
await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
var request = JsonSerializer.Deserialize<CreateCameraEventRequest>(reader.GetString(1), Json);
if (request is not null && Guid.TryParse(reader.GetString(0), out var id))
results.Add(new PendingDetection(id, request, reader.GetInt32(2), reader.IsDBNull(3) ? null : reader.GetFieldValue<byte[]>(3)));
}
return results;
var rows = await db.PendingEvents.AsNoTracking()
.OrderByDescending(item => item.Priority)
.ThenBy(item => item.CreatedAt)
.Take(ReadBatchSize)
.ToListAsync(ct).ConfigureAwait(false);
return rows.Select(item => new
{
Item = item,
Request = JsonSerializer.Deserialize<CreateCameraEventRequest>(item.PayloadJson, Json)
})
.Where(entry => entry.Request is not null && Guid.TryParse(entry.Item.EventId, out _))
.Select(entry => new PendingDetection(Guid.Parse(entry.Item.EventId), entry.Request!, entry.Item.Attempts, entry.Item.SnapshotJpeg))
.ToList();
}
private async Task DeletePendingAsync(Guid eventId, CancellationToken ct)
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var command = connection.CreateCommand();
command.CommandText = "DELETE FROM pending_detection_events WHERE event_id=$id;";
command.Parameters.AddWithValue("$id", eventId.ToString("D"));
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(connection, null, ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count, bytes);
await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false);
try
{
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
var item = await db.PendingEvents.FindAsync([eventId.ToString("D")], ct).ConfigureAwait(false);
if (item is not null)
{
db.PendingEvents.Remove(item);
await db.SaveChangesAsync(ct).ConfigureAwait(false);
}
var (count, bytes) = await GetOutboxSizeAsync(db, ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count, bytes);
}
finally { _databaseWriteGate.Release(); }
}
private async Task IncrementAttemptsAsync(Guid eventId, CancellationToken ct)
{
try
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var command = connection.CreateCommand();
command.CommandText = "UPDATE pending_detection_events SET attempts=attempts+1 WHERE event_id=$id;";
command.Parameters.AddWithValue("$id", eventId.ToString("D"));
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
var item = await db.PendingEvents.FindAsync([eventId.ToString("D")], ct).ConfigureAwait(false);
if (item is not null)
{
item.Attempts++;
await db.SaveChangesAsync(ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { }
catch (Exception ex) { _logger.LogWarning(ex, "Could not update retry count for event {EventId}", eventId); }
@@ -427,21 +406,26 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo
await _databaseWriteGate.WaitAsync(ct).ConfigureAwait(false);
try
{
await using var connection = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var transaction = await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
await using var trim = connection.CreateCommand();
trim.Transaction = (SqliteTransaction)transaction;
trim.CommandText = "DELETE FROM dead_letter_detection_events WHERE event_id IN (SELECT event_id FROM dead_letter_detection_events ORDER BY created_at DESC LIMIT -1 OFFSET $keep);";
trim.Parameters.AddWithValue("$keep", MaxDeadLetterEvents - 1);
await trim.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await using var insert = connection.CreateCommand();
insert.Transaction = (SqliteTransaction)transaction;
insert.CommandText = "INSERT OR REPLACE INTO dead_letter_detection_events(event_id,payload_json,created_at,last_error,attempts) SELECT event_id,payload_json,created_at,$error,attempts+1 FROM pending_detection_events WHERE event_id=$id; DELETE FROM pending_detection_events WHERE event_id=$id;";
insert.Parameters.AddWithValue("$error", error);
insert.Parameters.AddWithValue("$id", item.EventId.ToString("D"));
await insert.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await using var db = await OpenDatabaseAsync(ct).ConfigureAwait(false);
await using var transaction = await db.Database.BeginTransactionAsync(ct).ConfigureAwait(false);
var pending = await db.PendingEvents.FindAsync([item.EventId.ToString("D")], ct).ConfigureAwait(false);
if (pending is null)
return;
var excess = await db.DeadLetters.OrderByDescending(letter => letter.CreatedAt)
.Skip(MaxDeadLetterEvents - 1).ToListAsync(ct).ConfigureAwait(false);
db.DeadLetters.RemoveRange(excess);
db.DeadLetters.Add(new DeadLetterDetectionEvent
{
EventId = pending.EventId,
PayloadJson = pending.PayloadJson,
CreatedAt = pending.CreatedAt,
LastError = error,
Attempts = pending.Attempts + 1
});
db.PendingEvents.Remove(pending);
await db.SaveChangesAsync(ct).ConfigureAwait(false);
await transaction.CommitAsync(ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(connection, null, ct).ConfigureAwait(false);
var (count, bytes) = await GetOutboxSizeAsync(db, ct).ConfigureAwait(false);
HeimdallMetrics.SetEventOutboxState((int)count, bytes);
}
finally { _databaseWriteGate.Release(); }
+31 -3
View File
@@ -21,6 +21,18 @@
"Microsoft.AspNetCore.SignalR.Client.Core": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.ML.OnnxRuntime": {
"type": "Direct",
"requested": "[1.22.0, )",
@@ -124,8 +136,7 @@
"contentHash": "zfCQ0/J/rATKKcpwcpQYFz8sxhvrzgGyblsATcfxqSCibRkPFmDZcFmfD0UfLi38q+VDMpwEVuzOCO3TpRy99Q=="
},
"Microsoft.Data.Sqlite": {
"type": "Direct",
"requested": "[10.0.13, )",
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "w37nz3WFmDtRfXxWEwIXX2OgqDRiwhD1JGbFwfpFCF8GkCrV/yO6Y2JF5058J2RGoI2sCcdn02wrk0yEcekWcw==",
"dependencies": {
@@ -169,6 +180,22 @@
"Microsoft.EntityFrameworkCore": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.IdentityModel.Abstractions": {
"type": "Transitive",
"resolved": "8.14.0",
@@ -283,6 +310,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
@@ -304,4 +332,4 @@
}
}
}
}
}
@@ -3,6 +3,7 @@ using System.Text;
using System.Text.RegularExpressions;
using Heimdall.Application.DTOs;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
@@ -10,8 +11,7 @@ namespace Heimdall.Application.Discovery;
/// <summary>
/// SQLite reader over the embedded StrixCamDB (<c>cameras.db</c>, MIT © 2025
/// eduard256, transposed from Strix pkg/camdb). Pure managed
/// <see cref="Microsoft.Data.Sqlite"/> — no native dependency, Alpine-safe.
/// eduard256, transposed from Strix pkg/camdb). Read-only EF Core SQLite adapter.
/// The DB file is copied to the output directory by the Application csproj
/// (<c>Discovery\Data\cameras.db</c>), so it is available to the Central, the
/// Agent and the tests.
@@ -21,10 +21,10 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
private const int MaxResults = 50;
private static readonly TimeSpan OpenTimeout = TimeSpan.FromSeconds(2);
private readonly SqliteConnection? _connection;
private readonly CameraCatalogueContext? _context;
private readonly ILogger<SqliteCameraDatabase> _logger;
public bool IsAvailable => _connection is not null;
public bool IsAvailable => _context is not null;
public SqliteCameraDatabase(ILogger<SqliteCameraDatabase>? logger = null)
{
@@ -44,15 +44,15 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
Mode = SqliteOpenMode.ReadOnly,
Pooling = false,
};
var connection = new SqliteConnection(builder.ToString());
connection.Open();
_connection = connection;
_context = new CameraCatalogueContext(builder.ToString());
if (!_context.Database.CanConnect())
throw new InvalidOperationException("StrixCamDB is not readable");
_logger.LogInformation("StrixCamDB loaded: {Path}", path);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to open StrixCamDB");
_connection = null;
_context = null;
}
}
@@ -86,7 +86,7 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
public IReadOnlyList<CameraDbEntry> Search(string query)
{
if (_connection is null)
if (_context is null)
return [];
try
@@ -113,37 +113,25 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
return results;
// 3) Models — each word must match brand or model (Strix SearchQuery)
var where = new StringBuilder();
var args = new List<string>();
for (var i = 0; i < terms.Length; i++)
var models = _context.StreamModels.AsNoTracking();
foreach (var term in terms)
{
if (i > 0)
where.Append(" AND ");
where.Append(CultureInfo.InvariantCulture, $"(b.brand LIKE @w{i} OR b.brand_id LIKE @w{i} OR sm.model LIKE @w{i})");
args.Add($"%{terms[i]}%");
var pattern = $"%{term}%";
models = models.Where(model =>
EF.Functions.Like(model.Stream.Brand.Brand, pattern) ||
EF.Functions.Like(model.Stream.Brand.BrandId, pattern) ||
EF.Functions.Like(model.Model, pattern));
}
using var cmd = _connection.CreateCommand();
cmd.CommandText = $"""
SELECT DISTINCT b.brand_id, b.brand, sm.model
FROM stream_models sm
JOIN streams s ON s.id = sm.stream_id
JOIN brands b ON b.brand_id = s.brand_id
WHERE {where}
ORDER BY b.brand, sm.model
LIMIT {MaxResults - results.Count}
""";
for (var i = 0; i < args.Count; i++)
cmd.Parameters.AddWithValue($"@w{i}", args[i]);
using var reader = cmd.ExecuteReader();
while (reader.Read() && results.Count < MaxResults)
{
var brandId = reader.GetString(0);
var brand = reader.GetString(1);
var model = reader.GetString(2);
results.Add(new CameraDbEntry("model", $"m:{brandId}:{model}", $"{brand} {model}"));
}
results.AddRange(models
.OrderBy(model => model.Stream.Brand.Brand)
.ThenBy(model => model.Model)
.Select(model => new CameraDbEntry(
"model", $"m:{model.Stream.Brand.BrandId}:{model.Model}",
model.Stream.Brand.Brand + " " + model.Model))
.Distinct()
.Take(MaxResults - results.Count)
.ToList());
return results;
}
@@ -157,39 +145,33 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
private List<CameraDbEntry> QueryPresets(string like, int limit)
{
var results = new List<CameraDbEntry>();
if (limit <= 0 || _connection is null)
if (limit <= 0 || _context is null)
return results;
using var cmd = _connection.CreateCommand();
cmd.CommandText = "SELECT preset_id, name FROM presets WHERE (@like = '' OR preset_id LIKE @like OR name LIKE @like) ORDER BY preset_id LIMIT @limit";
cmd.Parameters.AddWithValue("@like", like);
cmd.Parameters.AddWithValue("@limit", limit);
using var reader = cmd.ExecuteReader();
while (reader.Read() && results.Count < limit)
results.Add(new CameraDbEntry("preset", $"p:{reader.GetString(0)}", reader.GetString(1)));
var query = _context.Presets.AsNoTracking();
if (like.Length > 0)
query = query.Where(preset => EF.Functions.Like(preset.PresetId, like) || EF.Functions.Like(preset.Name, like));
results.AddRange(query.OrderBy(preset => preset.PresetId).Take(limit)
.Select(preset => new CameraDbEntry("preset", "p:" + preset.PresetId, preset.Name)).ToList());
return results;
}
private List<CameraDbEntry> QueryBrands(string like, int limit)
{
var results = new List<CameraDbEntry>();
if (limit <= 0 || _connection is null)
if (limit <= 0 || _context is null)
return results;
using var cmd = _connection.CreateCommand();
cmd.CommandText = "SELECT brand_id, brand FROM brands WHERE (@like = '' OR brand_id LIKE @like OR brand LIKE @like) ORDER BY brand LIMIT @limit";
cmd.Parameters.AddWithValue("@like", like);
cmd.Parameters.AddWithValue("@limit", limit);
using var reader = cmd.ExecuteReader();
while (reader.Read() && results.Count < limit)
results.Add(new CameraDbEntry("brand", $"b:{reader.GetString(0)}", reader.GetString(1)));
var query = _context.Brands.AsNoTracking();
if (like.Length > 0)
query = query.Where(brand => EF.Functions.Like(brand.BrandId, like) || EF.Functions.Like(brand.Brand, like));
results.AddRange(query.OrderBy(brand => brand.Brand).Take(limit)
.Select(brand => new CameraDbEntry("brand", "b:" + brand.BrandId, brand.Brand)).ToList());
return results;
}
public IReadOnlyList<string> BuildStreams(
string[] ids, string ip, string? username, string? password, int channel = 0, int[]? portFilter = null)
{
if (_connection is null)
if (_context is null)
return [];
var filter = portFilter is { Length: > 0 } ? portFilter.Distinct().ToHashSet() : null;
@@ -238,10 +220,9 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
private List<(string Url, string Protocol, int Port)> QueryStreamsByBrand(string brandId)
{
using var cmd = _connection!.CreateCommand();
cmd.CommandText = "SELECT url, protocol, port FROM streams WHERE brand_id = @b";
cmd.Parameters.AddWithValue("@b", brandId);
return ReadStreamRows(cmd);
return _context!.Streams.AsNoTracking().Where(stream => stream.BrandId == brandId)
.Select(stream => new { stream.Url, stream.Protocol, stream.Port })
.ToList().Select(row => (row.Url, row.Protocol, row.Port)).ToList();
}
private List<(string Url, string Protocol, int Port)> QueryStreamsByModel(string modelId)
@@ -250,43 +231,22 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
if (parts.Length != 2)
return [];
using var cmd = _connection!.CreateCommand();
cmd.CommandText = """
SELECT s.url, s.protocol, s.port
FROM stream_models sm
JOIN streams s ON s.id = sm.stream_id
WHERE s.brand_id = @b AND sm.model = @m
""";
cmd.Parameters.AddWithValue("@b", parts[0]);
cmd.Parameters.AddWithValue("@m", parts[1]);
return ReadStreamRows(cmd);
return _context!.StreamModels.AsNoTracking()
.Where(model => model.Stream.BrandId == parts[0] && model.Model == parts[1])
.Select(model => new { model.Stream.Url, model.Stream.Protocol, model.Stream.Port })
.ToList().Select(row => (row.Url, row.Protocol, row.Port)).ToList();
}
private List<(string Url, string Protocol, int Port)> QueryPresetStreams(string presetId)
{
using var cmd = _connection!.CreateCommand();
cmd.CommandText = "SELECT url, protocol, port FROM preset_streams WHERE preset_id = @p";
cmd.Parameters.AddWithValue("@p", presetId);
return ReadStreamRows(cmd);
}
private static List<(string Url, string Protocol, int Port)> ReadStreamRows(SqliteCommand cmd)
{
var rows = new List<(string, string, int)>();
using var reader = cmd.ExecuteReader();
while (reader.Read())
{
rows.Add((
reader.GetString(0),
reader.GetString(1),
reader.IsDBNull(2) ? 0 : reader.GetInt32(2)));
}
return rows;
return _context!.PresetStreams.AsNoTracking().Where(stream => stream.PresetId == presetId)
.Select(stream => new { stream.Url, stream.Protocol, stream.Port })
.ToList().Select(row => (row.Url, row.Protocol, row.Port)).ToList();
}
public string? LookupOui(string mac)
{
if (_connection is null || string.IsNullOrWhiteSpace(mac))
if (_context is null || string.IsNullOrWhiteSpace(mac))
return null;
try
@@ -304,10 +264,10 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
prefix = string.Join(':', Enumerable.Range(0, 3).Select(i => prefix.Substring(i * 2, 2)));
}
using var cmd = _connection.CreateCommand();
cmd.CommandText = "SELECT brand FROM oui WHERE prefix = @p";
cmd.Parameters.AddWithValue("@p", prefix);
var result = cmd.ExecuteScalar() as string;
var result = _context.OuiEntries.AsNoTracking()
.Where(entry => entry.Prefix == prefix)
.Select(entry => entry.Brand)
.FirstOrDefault();
return string.IsNullOrWhiteSpace(result) ? null : result;
}
catch (Exception ex)
@@ -385,5 +345,34 @@ public sealed class SqliteCameraDatabase : ICameraDatabase, IDisposable
});
}
public void Dispose() => _connection?.Dispose();
public void Dispose() => _context?.Dispose();
private sealed class CameraCatalogueContext(string connectionString) : DbContext
{
public DbSet<PresetRow> Presets => Set<PresetRow>();
public DbSet<BrandRow> Brands => Set<BrandRow>();
public DbSet<StreamRow> Streams => Set<StreamRow>();
public DbSet<StreamModelRow> StreamModels => Set<StreamModelRow>();
public DbSet<PresetStreamRow> PresetStreams => Set<PresetStreamRow>();
public DbSet<OuiRow> OuiEntries => Set<OuiRow>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlite(connectionString);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PresetRow>(entity => { entity.ToTable("presets"); entity.HasKey(row => row.Id); entity.Property(row => row.Id).HasColumnName("id"); entity.Property(row => row.PresetId).HasColumnName("preset_id"); entity.Property(row => row.Name).HasColumnName("name"); });
modelBuilder.Entity<BrandRow>(entity => { entity.ToTable("brands"); entity.HasKey(row => row.Id); entity.Property(row => row.Id).HasColumnName("id"); entity.Property(row => row.BrandId).HasColumnName("brand_id"); entity.Property(row => row.Brand).HasColumnName("brand"); });
modelBuilder.Entity<StreamRow>(entity => { entity.ToTable("streams"); entity.HasKey(row => row.Id); entity.Property(row => row.Id).HasColumnName("id"); entity.Property(row => row.BrandId).HasColumnName("brand_id"); entity.Property(row => row.Url).HasColumnName("url"); entity.Property(row => row.Protocol).HasColumnName("protocol"); entity.Property(row => row.Port).HasColumnName("port"); entity.HasOne(row => row.Brand).WithMany().HasForeignKey(row => row.BrandId).HasPrincipalKey(row => row.BrandId); });
modelBuilder.Entity<StreamModelRow>(entity => { entity.ToTable("stream_models"); entity.HasKey(row => new { row.StreamId, row.Model }); entity.Property(row => row.StreamId).HasColumnName("stream_id"); entity.Property(row => row.Model).HasColumnName("model"); entity.HasOne(row => row.Stream).WithMany().HasForeignKey(row => row.StreamId); });
modelBuilder.Entity<PresetStreamRow>(entity => { entity.ToTable("preset_streams"); entity.HasKey(row => row.Id); entity.Property(row => row.Id).HasColumnName("id"); entity.Property(row => row.PresetId).HasColumnName("preset_id"); entity.Property(row => row.Url).HasColumnName("url"); entity.Property(row => row.Protocol).HasColumnName("protocol"); entity.Property(row => row.Port).HasColumnName("port"); });
modelBuilder.Entity<OuiRow>(entity => { entity.ToTable("oui"); entity.HasKey(row => row.Prefix); entity.Property(row => row.Prefix).HasColumnName("prefix"); entity.Property(row => row.Brand).HasColumnName("brand"); });
}
}
private sealed class PresetRow { public long Id { get; set; } public string PresetId { get; set; } = ""; public string Name { get; set; } = ""; }
private sealed class BrandRow { public long Id { get; set; } public string BrandId { get; set; } = ""; public string Brand { get; set; } = ""; }
private sealed class StreamRow { public long Id { get; set; } public string BrandId { get; set; } = ""; public string Url { get; set; } = ""; public string Protocol { get; set; } = ""; public int Port { get; set; } public BrandRow Brand { get; set; } = null!; }
private sealed class StreamModelRow { public long StreamId { get; set; } public string Model { get; set; } = ""; public StreamRow Stream { get; set; } = null!; }
private sealed class PresetStreamRow { public long Id { get; set; } public string PresetId { get; set; } = ""; public string Url { get; set; } = ""; public string Protocol { get; set; } = ""; public int Port { get; set; } }
private sealed class OuiRow { public string Prefix { get; set; } = ""; public string Brand { get; set; } = ""; }
}
@@ -14,6 +14,7 @@
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.13" />
</ItemGroup>
<ItemGroup>
@@ -72,6 +72,21 @@
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"SQLitePCLRaw.bundle_e_sqlite3": {
"type": "Direct",
"requested": "[3.0.5, )",
@@ -129,6 +144,20 @@
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -188,6 +217,11 @@
"resolved": "10.0.13",
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -56,6 +56,7 @@ public sealed class AgentMetricSampleJob
gpuTemperature, gpuUtilization, agent.TemperatureJson, agent.InventoryObservedAtUtc));
}
// EF Core exception: bulk JSON recordset insert uses PostgreSQL ON CONFLICT for idempotency.
// The unique (AgentId, CapturedAtUtc) index makes retries and duplicate
// executions safe. Only typed, server-serialized values reach PostgreSQL.
const int batchSize = 500;
@@ -34,6 +34,7 @@ public class DatabaseMaintenanceJob
{
try
{
// EF Core exception: VACUUM and REINDEX are PostgreSQL maintenance commands.
// VACUUM per partition (FULL on first Sunday of month)
var vacuumSql = isFirstSunday
? $"VACUUM FULL \"{partition}\";"
@@ -62,6 +63,7 @@ public class DatabaseMaintenanceJob
private static async Task<List<string>> GetPartitionsAsync(AppDbContext db, CancellationToken ct)
{
// EF Core exception: pg_tables is a PostgreSQL system catalog with no portable model.
var partitions = new List<string>();
await using var connection = db.Database.GetDbConnection();
@@ -62,6 +62,7 @@ public class PartitionManagerJob
var created = 0;
var dropped = 0;
// EF Core exception: PostgreSQL partition creation and pruning require provider-specific DDL.
// ── Create future partitions ────────────────────────────────────────
for (int i = 0; i <= PreCreateMonths; i++)
{
@@ -119,6 +119,7 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat
{
location.Provider.ToString(), localRoot, endpoint, bucket
});
// EF Core exception: PostgreSQL advisory locks have no portable LINQ equivalent.
// The advisory lock makes the read-then-insert idempotent across concurrent
// uploads. A hash collision only serializes unrelated destinations; equality
// is still checked against all stored fields below.
@@ -387,6 +387,34 @@
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -771,6 +799,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
+28
View File
@@ -325,6 +325,33 @@
"Microsoft.EntityFrameworkCore": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -472,6 +499,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
@@ -0,0 +1,100 @@
using System.Globalization;
using Heimdall.Agent;
using Heimdall.Agent.Services;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using Shouldly;
namespace Heimdall.Agent.Tests;
public sealed class CameraStatusReporterServiceTests
{
[Fact]
public async Task ReportAsync_PersistsPendingStatusWithEfCoreSchema()
{
var directory = CreateStateDirectory();
try
{
using var reporter = CreateReporter(directory);
var cameraId = Guid.NewGuid();
await reporter.ReportAsync(cameraId, "Online", CancellationToken.None);
reporter.FailedReports.ShouldBe(0);
await using var db = new SqliteConnection($"Data Source={Path.Combine(directory, "agent-outbox.db")};Mode=ReadOnly");
await db.OpenAsync();
await using var command = db.CreateCommand();
command.CommandText = "SELECT status FROM pending_camera_status WHERE camera_id=$id;";
command.Parameters.AddWithValue("$id", cameraId.ToString("D"));
(await command.ExecuteScalarAsync()).ShouldBe("Online");
}
finally
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
[Fact]
public async Task ReportAsync_AdoptsLegacyOutboxAndPreservesPendingAndAcknowledgedStatuses()
{
var directory = CreateStateDirectory();
var databasePath = Path.Combine(directory, "agent-outbox.db");
var pendingCamera = Guid.NewGuid();
var acknowledgedCamera = Guid.NewGuid();
try
{
await using (var database = new SqliteConnection($"Data Source={databasePath}"))
{
await database.OpenAsync();
await using var setup = database.CreateCommand();
setup.CommandText = """
CREATE TABLE pending_camera_status (camera_id TEXT PRIMARY KEY NOT NULL, status TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE acknowledged_camera_status (camera_id TEXT PRIMARY KEY NOT NULL, status TEXT NOT NULL);
INSERT INTO pending_camera_status VALUES ($pending, 'Offline', '2026-01-01T00:00:00Z');
INSERT INTO acknowledged_camera_status VALUES ($acknowledged, 'Online');
PRAGMA user_version=1;
""";
setup.Parameters.AddWithValue("$pending", pendingCamera.ToString("D"));
setup.Parameters.AddWithValue("$acknowledged", acknowledgedCamera.ToString("D"));
await setup.ExecuteNonQueryAsync();
}
using var reporter = CreateReporter(directory);
await reporter.ReportAsync(pendingCamera, "Online", CancellationToken.None);
await reporter.ReportAsync(acknowledgedCamera, "Online", CancellationToken.None);
reporter.FailedReports.ShouldBe(0);
await using var verify = new SqliteConnection($"Data Source={databasePath};Mode=ReadOnly");
await verify.OpenAsync();
await using var checkPending = verify.CreateCommand();
checkPending.CommandText = "SELECT status FROM pending_camera_status WHERE camera_id=$id;";
checkPending.Parameters.AddWithValue("$id", pendingCamera.ToString("D"));
(await checkPending.ExecuteScalarAsync()).ShouldBe("Online");
await using var checkAck = verify.CreateCommand();
checkAck.CommandText = "SELECT status FROM acknowledged_camera_status WHERE camera_id=$id;";
checkAck.Parameters.AddWithValue("$id", acknowledgedCamera.ToString("D"));
(await checkAck.ExecuteScalarAsync()).ShouldBe("Online");
await using var count = verify.CreateCommand();
count.CommandText = "SELECT COUNT(*) FROM pending_camera_status;";
Convert.ToInt32(await count.ExecuteScalarAsync(), CultureInfo.InvariantCulture).ShouldBe(1);
}
finally
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
private static string CreateStateDirectory()
{
var directory = Path.Combine(Path.GetTempPath(), $"heimdall-status-outbox-{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
return directory;
}
private static CameraStatusReporterService CreateReporter(string directory) => new(
new AgentState(), Substitute.For<IHttpClientFactory>(),
Substitute.For<ILogger<CameraStatusReporterService>>(),
Options.Create(new AgentOptions { StateDirectory = directory }));
}
@@ -1,3 +1,4 @@
using System.Globalization;
using Heimdall.Agent.Services;
using Heimdall.Domain.Enums;
using Microsoft.Data.Sqlite;
@@ -117,4 +118,53 @@ public class DetectionReporterServiceTests
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
[Fact]
public async Task ReportAsync_AdoptsLegacyOutboxAndPreservesQueuedEvents()
{
var directory = Path.Combine(Path.GetTempPath(), $"heimdall-legacy-outbox-{Guid.NewGuid():N}");
Directory.CreateDirectory(directory);
var databasePath = Path.Combine(directory, "agent-events.db");
try
{
await using (var database = new SqliteConnection($"Data Source={databasePath}"))
{
await database.OpenAsync();
await using var command = database.CreateCommand();
command.CommandText = """
CREATE TABLE pending_detection_events (
event_id TEXT PRIMARY KEY NOT NULL, event_type INTEGER NOT NULL,
priority INTEGER NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0);
CREATE INDEX ix_pending_detection_events_priority_created
ON pending_detection_events(priority DESC, created_at);
CREATE TABLE dead_letter_detection_events (
event_id TEXT PRIMARY KEY NOT NULL, payload_json TEXT NOT NULL,
created_at TEXT NOT NULL, last_error TEXT NOT NULL, attempts INTEGER NOT NULL);
INSERT INTO pending_detection_events
(event_id, event_type, priority, payload_json, created_at, attempts)
VALUES ('11111111-1111-4111-8111-111111111111', 0, 1, '{}', '2026-01-01T00:00:00Z', 0);
PRAGMA user_version=1;
""";
await command.ExecuteNonQueryAsync();
}
using var reporter = new DetectionReporterService(new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" },
Substitute.For<IHttpClientFactory>(), Substitute.For<ILogger<DetectionReporterService>>(),
Options.Create(new Heimdall.Agent.AgentOptions { StateDirectory = directory }));
(await reporter.ReportAsync(Guid.NewGuid(), EventType.PersonDetected, 0.9, "person")).ShouldBeTrue();
reporter.FailedReports.ShouldBe(0);
await using var verify = new SqliteConnection($"Data Source={databasePath};Mode=ReadOnly");
await verify.OpenAsync();
await using var check = verify.CreateCommand();
check.CommandText = "SELECT COUNT(*) FROM pending_detection_events WHERE event_id='11111111-1111-4111-8111-111111111111' AND snapshot_jpeg IS NULL;";
Convert.ToInt32(await check.ExecuteScalarAsync(), CultureInfo.InvariantCulture).ShouldBe(1);
}
finally
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
}
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="10.0.13" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.13" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="NSubstitute" Version="6.0.0" />
<PackageReference Include="Shouldly" Version="4.3.0" />
@@ -26,4 +27,4 @@
<ProjectReference Include="..\..\src\Heimdall.Agent\Heimdall.Agent.csproj" />
</ItemGroup>
</Project>
</Project>
+47 -12
View File
@@ -23,6 +23,17 @@
"System.Security.Cryptography.Xml": "10.0.13"
}
},
"Microsoft.Data.Sqlite": {
"type": "Direct",
"requested": "[10.0.13, )",
"resolved": "10.0.13",
"contentHash": "w37nz3WFmDtRfXxWEwIXX2OgqDRiwhD1JGbFwfpFCF8GkCrV/yO6Y2JF5058J2RGoI2sCcdn02wrk0yEcekWcw==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.NET.Test.Sdk": {
"type": "Direct",
"requested": "[17.14.1, )",
@@ -237,16 +248,6 @@
"resolved": "17.14.1",
"contentHash": "pmTrhfFIoplzFVbhVwUquT+77CbGH+h4/3mBpdmIlYtBi9nAB+kKI6dN3A/nV4DFi3wLLx/BlHIPK+MkbQ6Tpg=="
},
"Microsoft.Data.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "w37nz3WFmDtRfXxWEwIXX2OgqDRiwhD1JGbFwfpFCF8GkCrV/yO6Y2JF5058J2RGoI2sCcdn02wrk0yEcekWcw==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -287,6 +288,34 @@
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -355,6 +384,11 @@
"resolved": "10.0.13",
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -742,7 +776,7 @@
"Heimdall.Mdns": "[1.0.0, )",
"Magick.NET-Q16-AnyCPU": "[14.16.0, )",
"Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"Microsoft.ML.OnnxRuntime": "[1.22.0, )",
"OpenTelemetry": "[1.17.0, )",
"OpenTelemetry.Exporter.Prometheus.AspNetCore": "[1.17.0-beta.1, )",
@@ -761,6 +795,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
@@ -785,4 +820,4 @@
}
}
}
}
}
@@ -470,6 +470,34 @@
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -538,6 +566,11 @@
"resolved": "10.0.13",
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -1036,6 +1069,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
@@ -192,6 +192,34 @@
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -251,6 +279,11 @@
"resolved": "10.0.13",
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
},
"Microsoft.Extensions.Diagnostics": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -488,6 +521,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
@@ -564,6 +564,34 @@
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -1315,6 +1343,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
@@ -884,6 +884,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
@@ -552,6 +552,34 @@
"Microsoft.Extensions.Logging": "10.0.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.EntityFrameworkCore.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.13",
"contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.13",
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
"Microsoft.Extensions.Caching.Memory": "10.0.13",
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
"Microsoft.Extensions.DependencyModel": "10.0.13",
"Microsoft.Extensions.Logging": "10.0.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.Caching.Abstractions": {
"type": "Transitive",
"resolved": "10.0.13",
@@ -1290,6 +1318,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
@@ -1190,6 +1190,7 @@
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.Data.Sqlite": "[10.0.13, )",
"Microsoft.EntityFrameworkCore": "[10.0.13, )",
"Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )",
"SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )"
}
},
+4
View File
@@ -19,6 +19,8 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
## P1 — parcours caméra, agent et données
- [ ] **EF Core / règles de persistance** Remplacer l’ADO.NET des deux outboxes Agent et du catalogue caméra par EF Core SQLite, préserver les bases locales existantes avec une adoption de schéma testée, et bloquer en CI les commandes directes non autorisées. Cette branche ajoute la skill `skills/ef-core-persistence/`, relie les règles du dépôt au skill et documente les exceptions PostgreSQL qui n’ont pas d’équivalent portable. Restent les contrôles CI PR et la validation après merge.
- [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées.
- [ ] **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é. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse.
- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. Le run PR #276 a validé build/tests et les scans des images serveur et Agent; la validation sur plusieurs Agents reste à faire.
@@ -35,6 +37,8 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
## P2 — fonctionnalités et exploitation
- [ ] **Installateur Linux serveur** Fournir un script shell interactif qui génère le Compose serveur et son `.env`, demande les réglages applicatifs appropriés et propose d’installer ou de configurer les services externes nécessaires. À traiter dans une PR distincte après la PR EF Core.
- [ ] **PWA** PR #64 livre le manifeste, une icône SVG, l'enregistrement du service worker et une page hors connexion statique ; cache public limité à ces trois fichiers, sans mise en cache des données métier. Le fallback offline est exclu des navigations API/auth, hubs, Hangfire, métriques, santé et documentation technique. Le cycle de mise à jour propose un rechargement explicite après installation d'une nouvelle version (installation initiale silencieuse, sans actualisation automatique). Des icônes PNG 180/192/512 px sont maintenant déclarées pour Apple et les installateurs Android, avec tests de dimensions et de présence. Restent les validations appareils/HTTPS, reprise mobile, stratégie de rollback et Web Push par utilisateur/appareil. Ne jamais mettre les données privées en cache.
- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe.
- [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète.