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
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:
1 parent
7c4cff90d8
commit
f832d2fb62
36 files changed
+1174
-309
No files matched your search
@@ -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(); }
|
||||
|
||||
Reference in new issue
Block a user