feat(mvp): complete MVP hardening — API, Web, config system, SignalR, tests

This commit is contained in:
Arnaud Dartois committed 2026-07-18 18:58:20 +00:00
1 parent 3fc42be4b2
commit c2837af089
59 files changed
+4920 -81

No files matched your search

@@ -19,6 +19,8 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
public DbSet<UserSite> UserSites => Set<UserSite>();
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
public DbSet<AuditLog> AuditLogs => Set<AuditLog>();
public DbSet<AppSetting> AppSettings => Set<AppSetting>();
public DbSet<AgentSetting> AgentSettings => Set<AgentSetting>();
protected override void OnModelCreating(ModelBuilder builder)
{
@@ -0,0 +1,43 @@
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class AppSettingConfiguration : IEntityTypeConfiguration<AppSetting>
{
public void Configure(EntityTypeBuilder<AppSetting> builder)
{
builder.ToTable("app_settings");
builder.HasKey(x => x.Id);
builder.HasIndex(x => x.Key).IsUnique();
builder.Property(x => x.Key).IsRequired().HasMaxLength(200).HasColumnName("key");
builder.Property(x => x.Value).IsRequired().HasColumnName("value");
builder.Property(x => x.Description).HasMaxLength(500).HasColumnName("description");
builder.Property(x => x.Category).IsRequired().HasMaxLength(100).HasColumnName("category");
builder.Property(x => x.ValueType).IsRequired().HasMaxLength(50).HasColumnName("value_type");
builder.Property(x => x.AllowedValues).HasMaxLength(2000).HasColumnName("allowed_values");
builder.Property(x => x.CreatedAt).HasColumnName("created_at");
builder.Property(x => x.UpdatedAt).HasColumnName("updated_at");
}
}
public class AgentSettingConfiguration : IEntityTypeConfiguration<AgentSetting>
{
public void Configure(EntityTypeBuilder<AgentSetting> builder)
{
builder.ToTable("agent_settings");
builder.HasKey(x => x.Id);
builder.HasIndex(x => new { x.AgentId, x.Key }).IsUnique();
builder.Property(x => x.AgentId).IsRequired().HasColumnName("agent_id");
builder.Property(x => x.Key).IsRequired().HasMaxLength(200).HasColumnName("key");
builder.Property(x => x.Value).IsRequired().HasColumnName("value");
builder.Property(x => x.CreatedAt).HasColumnName("created_at");
builder.Property(x => x.UpdatedAt).HasColumnName("updated_at");
builder.HasOne(x => x.Agent)
.WithMany()
.HasForeignKey(x => x.AgentId)
.OnDelete(DeleteBehavior.Cascade);
}
}
@@ -68,6 +68,7 @@ public static class DependencyInjection
services.AddScoped<ICameraService, CameraService>();
services.AddScoped<IStatsService, StatsService>();
services.AddScoped<IAuditLogService, AuditLogService>();
services.AddScoped<ISettingService, SettingService>();
return services;
}
@@ -0,0 +1,985 @@
// <auto-generated />
using System;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260718143003_AddAppSettings")]
partial class AddAppSettings
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ApiKeyHash")
.HasMaxLength(128)
.IsUnicode(false)
.HasColumnType("character varying(128)");
b.Property<string>("ApiKeyPrefix")
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnType("character varying(8)");
b.Property<int>("CpuCores")
.HasColumnType("integer");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("GpuType")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<bool>("HasGpu")
.HasColumnType("boolean");
b.Property<string>("Hostname")
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false)
.HasColumnType("character varying(255)");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<DateTime?>("LastHeartbeat")
.HasColumnType("timestamp with time zone");
b.Property<long>("MemoryMb")
.HasColumnType("bigint");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.IsUnicode(false)
.HasColumnType("character varying(200)");
b.Property<string>("PublicIp")
.HasMaxLength(45)
.IsUnicode(false)
.HasColumnType("character varying(45)");
b.Property<Guid>("SiteId")
.HasColumnType("uuid");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("Version")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("character varying(50)");
b.HasKey("Id");
b.HasIndex("LastHeartbeat")
.HasFilter("\"status\" = 'Online'");
b.HasIndex("SiteId");
b.ToTable("agents", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AgentId")
.HasColumnType("uuid")
.HasColumnName("agent_id");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("key");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("text")
.HasColumnName("value");
b.HasKey("Id");
b.HasIndex("AgentId", "Key")
.IsUnique();
b.ToTable("agent_settings", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<Guid?>("CreatedByUserId")
.HasColumnType("uuid");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<DateTime?>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("KeyHash")
.IsRequired()
.HasMaxLength(128)
.IsUnicode(false)
.HasColumnType("character varying(128)");
b.Property<string>("KeyPrefix")
.IsRequired()
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnType("character varying(8)");
b.Property<DateTime?>("LastUsedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("SiteId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("KeyHash");
b.HasIndex("KeyPrefix");
b.HasIndex("SiteId");
b.ToTable("api_keys", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("roles", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AllowedValues")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)")
.HasColumnName("allowed_values");
b.Property<string>("Category")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("category");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("character varying(500)")
.HasColumnName("description");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("key");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("text")
.HasColumnName("value");
b.Property<string>("ValueType")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("value_type");
b.HasKey("Id");
b.HasIndex("Key")
.IsUnique();
b.ToTable("app_settings", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<string>("Language")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("character varying(10)")
.HasDefaultValue("fr");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<bool>("MustChangePassword")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false);
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<string>("Theme")
.ValueGeneratedOnAdd()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)")
.HasDefaultValue("Auto");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("users", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Action")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<string>("IpAddress")
.HasMaxLength(45)
.IsUnicode(false)
.HasColumnType("character varying(45)");
b.Property<string>("NewValue")
.HasColumnType("text");
b.Property<string>("OldValue")
.HasColumnType("text");
b.Property<string>("ResourceId")
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<string>("ResourceType")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<DateTime>("Timestamp")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("Timestamp")
.IsDescending();
b.HasIndex("UserId");
b.HasIndex("ResourceType", "ResourceId", "Timestamp")
.IsDescending(false, false, true);
b.ToTable("audit_logs", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid?>("AgentId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("HasAudio")
.HasColumnType("boolean");
b.Property<bool>("HasMotionDetection")
.HasColumnType("boolean");
b.Property<bool>("HasPtz")
.HasColumnType("boolean");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Manufacturer")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Model")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.IsUnicode(false)
.HasColumnType("character varying(200)");
b.Property<string>("RtspUrl")
.HasMaxLength(1000)
.IsUnicode(false)
.HasColumnType("character varying(1000)");
b.Property<Guid>("SiteId")
.HasColumnType("uuid");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.HasKey("Id");
b.HasIndex("AgentId");
b.HasIndex("SiteId");
b.ToTable("cameras", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b =>
{
b.Property<Guid>("CameraId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("OnvifPassword")
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnType("character varying(500)");
b.Property<string>("OnvifUsername")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)")
.HasDefaultValue("admin");
b.Property<string>("RtspPassword")
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnType("character varying(500)");
b.Property<string>("RtspUsername")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.HasKey("CameraId");
b.ToTable("camera_credentials", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b =>
{
b.Property<Guid>("CameraId")
.HasColumnType("uuid");
b.Property<int>("ActiveIntervalMs")
.HasColumnType("integer");
b.Property<int>("AnimalCooldownSec")
.HasColumnType("integer");
b.Property<bool>("DetectAnimal")
.HasColumnType("boolean");
b.Property<bool>("DetectMotion")
.HasColumnType("boolean");
b.Property<bool>("DetectPackage")
.HasColumnType("boolean");
b.Property<bool>("DetectPerson")
.HasColumnType("boolean");
b.Property<bool>("DetectVehicle")
.HasColumnType("boolean");
b.Property<bool>("FaceRecognition")
.HasColumnType("boolean");
b.Property<int>("IdleIntervalMs")
.HasColumnType("integer");
b.Property<double>("IoUThreshold")
.HasColumnType("double precision");
b.Property<bool>("LicensePlateRecognition")
.HasColumnType("boolean");
b.Property<int>("MaxEventsPerMinute")
.HasColumnType("integer");
b.Property<double>("MinConfidence")
.ValueGeneratedOnAdd()
.HasColumnType("double precision")
.HasDefaultValue(0.40000000000000002);
b.Property<int>("MotionIntervalMs")
.HasColumnType("integer");
b.Property<double>("MotionThreshold")
.HasColumnType("double precision");
b.Property<int>("PersonCooldownSec")
.HasColumnType("integer");
b.Property<bool>("RequireMotionForAI")
.HasColumnType("boolean");
b.Property<int>("VehicleCooldownSec")
.HasColumnType("integer");
b.Property<string>("YoloModel")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("character varying(50)")
.HasDefaultValue("yolov8n");
b.HasKey("CameraId");
b.ToTable("camera_detection_profiles", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.Site", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Address")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Enabled")
.HasColumnType("boolean");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("RegistrationTokenHash")
.HasMaxLength(128)
.IsUnicode(false)
.HasColumnType("character varying(128)");
b.Property<string>("Timezone")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)")
.HasDefaultValue("UTC");
b.Property<DateTime?>("TokenExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.HasKey("Id");
b.HasIndex("IsDeleted")
.HasFilter("\"is_deleted\" = false");
b.HasIndex("Name");
b.ToTable("sites", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("SiteId")
.HasColumnType("uuid");
b.HasKey("UserId", "SiteId");
b.HasIndex("SiteId");
b.ToTable("user_sites", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("role_claims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("user_claims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("user_logins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("user_roles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("user_tokens", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b =>
{
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
.WithMany("Agents")
.HasForeignKey("SiteId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Site");
});
modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
{
b.HasOne("Heimdall.Domain.Entities.Agent", "Agent")
.WithMany()
.HasForeignKey("AgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Agent");
});
modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
{
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
.WithMany()
.HasForeignKey("SiteId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Site");
});
modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("User");
});
modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
{
b.HasOne("Heimdall.Domain.Entities.Agent", "Agent")
.WithMany("Cameras")
.HasForeignKey("AgentId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
.WithMany("Cameras")
.HasForeignKey("SiteId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Agent");
b.Navigation("Site");
});
modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b =>
{
b.HasOne("Heimdall.Domain.Entities.Camera", "Camera")
.WithOne("Credentials")
.HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Camera");
});
modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b =>
{
b.HasOne("Heimdall.Domain.Entities.Camera", "Camera")
.WithOne("DetectionProfile")
.HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Camera");
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b =>
{
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
.WithMany()
.HasForeignKey("SiteId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
.WithMany("UserSites")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Site");
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b =>
{
b.Navigation("Cameras");
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
{
b.Navigation("UserSites");
});
modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
{
b.Navigation("Credentials");
b.Navigation("DetectionProfile");
});
modelBuilder.Entity("Heimdall.Domain.Entities.Site", b =>
{
b.Navigation("Agents");
b.Navigation("Cameras");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,78 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddAppSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "agent_settings",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
agent_id = table.Column<Guid>(type: "uuid", nullable: false),
key = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
value = table.Column<string>(type: "text", nullable: false),
created_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
updated_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_agent_settings", x => x.Id);
table.ForeignKey(
name: "FK_agent_settings_agents_agent_id",
column: x => x.agent_id,
principalTable: "agents",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "app_settings",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
key = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
value = table.Column<string>(type: "text", nullable: false),
description = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
category = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
value_type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
allowed_values = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: true),
created_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
updated_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_app_settings", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_agent_settings_agent_id_key",
table: "agent_settings",
columns: new[] { "agent_id", "key" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_app_settings_key",
table: "app_settings",
column: "key",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "agent_settings");
migrationBuilder.DropTable(
name: "app_settings");
}
}
}
@@ -30,10 +30,12 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("ApiKeyHash")
.HasMaxLength(128)
.IsUnicode(false)
.HasColumnType("character varying(128)");
b.Property<string>("ApiKeyPrefix")
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnType("character varying(8)");
b.Property<int>("CpuCores")
@@ -50,6 +52,7 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("GpuType")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<bool>("HasGpu")
@@ -58,6 +61,7 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("Hostname")
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false)
.HasColumnType("character varying(255)");
b.Property<bool>("IsDeleted")
@@ -72,10 +76,12 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.IsUnicode(false)
.HasColumnType("character varying(200)");
b.Property<string>("PublicIp")
.HasMaxLength(45)
.IsUnicode(false)
.HasColumnType("character varying(45)");
b.Property<Guid>("SiteId")
@@ -84,6 +90,7 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<DateTime>("UpdatedAt")
@@ -94,6 +101,7 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("Version")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("character varying(50)");
b.HasKey("Id");
@@ -106,6 +114,43 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("agents", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AgentId")
.HasColumnType("uuid")
.HasColumnName("agent_id");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("key");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("text")
.HasColumnName("value");
b.HasKey("Id");
b.HasIndex("AgentId", "Key")
.IsUnique();
b.ToTable("agent_settings", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
{
b.Property<Guid>("Id")
@@ -129,11 +174,13 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("KeyHash")
.IsRequired()
.HasMaxLength(128)
.IsUnicode(false)
.HasColumnType("character varying(128)");
b.Property<string>("KeyPrefix")
.IsRequired()
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnType("character varying(8)");
b.Property<DateTime?>("LastUsedAt")
@@ -180,6 +227,61 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("roles", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AllowedValues")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)")
.HasColumnName("allowed_values");
b.Property<string>("Category")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("category");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("character varying(500)")
.HasColumnName("description");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("key");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("text")
.HasColumnName("value");
b.Property<string>("ValueType")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("value_type");
b.HasKey("Id");
b.HasIndex("Key")
.IsUnique();
b.ToTable("app_settings", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
{
b.Property<Guid>("Id")
@@ -214,6 +316,7 @@ namespace Heimdall.Infrastructure.Migrations
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("character varying(10)")
.HasDefaultValue("fr");
@@ -251,6 +354,7 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("Theme")
.ValueGeneratedOnAdd()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)")
.HasDefaultValue("Auto");
@@ -282,10 +386,12 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("Action")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<string>("IpAddress")
.HasMaxLength(45)
.IsUnicode(false)
.HasColumnType("character varying(45)");
b.Property<string>("NewValue")
@@ -296,11 +402,13 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("ResourceId")
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<string>("ResourceType")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<DateTime>("Timestamp")
@@ -364,10 +472,12 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.IsUnicode(false)
.HasColumnType("character varying(200)");
b.Property<string>("RtspUrl")
.HasMaxLength(1000)
.IsUnicode(false)
.HasColumnType("character varying(1000)");
b.Property<Guid>("SiteId")
@@ -376,6 +486,7 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<DateTime>("UpdatedAt")
@@ -405,23 +516,27 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("OnvifPassword")
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnType("character varying(500)");
b.Property<string>("OnvifUsername")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)")
.HasDefaultValue("admin");
b.Property<string>("RtspPassword")
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnType("character varying(500)");
b.Property<string>("RtspUsername")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)");
b.Property<DateTime>("UpdatedAt")
@@ -499,6 +614,7 @@ namespace Heimdall.Infrastructure.Migrations
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("character varying(50)")
.HasDefaultValue("yolov8n");
@@ -538,12 +654,14 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<string>("RegistrationTokenHash")
.HasMaxLength(128)
.IsUnicode(false)
.HasColumnType("character varying(128)");
b.Property<string>("Timezone")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("character varying(100)")
.HasDefaultValue("UTC");
@@ -694,6 +812,17 @@ namespace Heimdall.Infrastructure.Migrations
b.Navigation("Site");
});
modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
{
b.HasOne("Heimdall.Domain.Entities.Agent", "Agent")
.WithMany()
.HasForeignKey("AgentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Agent");
});
modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
{
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
@@ -0,0 +1,328 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
/// <summary>
/// Manages global application settings and per-agent setting overrides.
/// </summary>
public class SettingService : ISettingService
{
private readonly AppDbContext _db;
private readonly ILogger<SettingService> _logger;
public SettingService(AppDbContext db, ILogger<SettingService> logger)
{
_db = db;
_logger = logger;
}
// ────────────────────────────── Global Settings ──────────────────────────────
/// <inheritdoc />
public async Task<ServiceResult<List<AppSettingDto>>> GetAllSettingsAsync(CancellationToken ct = default)
{
try
{
var settings = await _db.AppSettings
.OrderBy(s => s.Category)
.ThenBy(s => s.Key)
.ToListAsync(ct);
return ServiceResult<List<AppSettingDto>>.Success(
settings.Select(MapToDto).ToList());
}
catch (OperationCanceledException)
{
return ServiceResult<List<AppSettingDto>>.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve all app settings");
return ServiceResult<List<AppSettingDto>>.Failure("An error occurred while retrieving settings");
}
}
/// <inheritdoc />
public async Task<ServiceResult<AppSettingDto>> GetSettingByKeyAsync(string key, CancellationToken ct = default)
{
try
{
var setting = await _db.AppSettings
.FirstOrDefaultAsync(s => s.Key == key, ct);
if (setting is null)
{
_logger.LogWarning("Setting '{Key}' not found", key);
return ServiceResult<AppSettingDto>.NotFound($"Setting '{key}' not found");
}
return ServiceResult<AppSettingDto>.Success(MapToDto(setting));
}
catch (OperationCanceledException)
{
return ServiceResult<AppSettingDto>.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve setting '{Key}'", key);
return ServiceResult<AppSettingDto>.Failure("An error occurred while retrieving the setting");
}
}
/// <inheritdoc />
public async Task<ServiceResult<AppSettingDto>> CreateSettingAsync(CreateAppSettingRequest request, CancellationToken ct = default)
{
try
{
var key = request.Key.Trim().ToLowerInvariant();
var exists = await _db.AppSettings.AnyAsync(s => s.Key == key, ct);
if (exists)
{
_logger.LogWarning("Attempted to create duplicate setting '{Key}'", key);
return ServiceResult<AppSettingDto>.Conflict($"Setting '{key}' already exists");
}
var setting = new AppSetting(key, request.Value, request.Category, request.Description);
// Apply optional metadata not covered by the constructor
setting.UpdateMetadata(null, null, request.ValueType, request.AllowedValues);
_db.AppSettings.Add(setting);
await _db.SaveChangesAsync(ct);
_logger.LogInformation("Created setting '{Key}' in category '{Category}'", key, request.Category);
return ServiceResult<AppSettingDto>.Success(MapToDto(setting));
}
catch (OperationCanceledException)
{
return ServiceResult<AppSettingDto>.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create setting '{Key}'", request.Key);
return ServiceResult<AppSettingDto>.Failure("An error occurred while creating the setting");
}
}
/// <inheritdoc />
public async Task<ServiceResult<AppSettingDto>> UpdateSettingAsync(string key, UpdateAppSettingRequest request, CancellationToken ct = default)
{
try
{
var setting = await _db.AppSettings
.FirstOrDefaultAsync(s => s.Key == key, ct);
if (setting is null)
{
_logger.LogWarning("Attempted to update non-existent setting '{Key}'", key);
return ServiceResult<AppSettingDto>.NotFound($"Setting '{key}' not found");
}
setting.UpdateValue(request.Value);
setting.UpdateMetadata(request.Description, request.Category, request.ValueType, request.AllowedValues);
await _db.SaveChangesAsync(ct);
_logger.LogInformation("Updated setting '{Key}'", key);
return ServiceResult<AppSettingDto>.Success(MapToDto(setting));
}
catch (OperationCanceledException)
{
return ServiceResult<AppSettingDto>.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to update setting '{Key}'", key);
return ServiceResult<AppSettingDto>.Failure("An error occurred while updating the setting");
}
}
/// <inheritdoc />
public async Task<ServiceResult> DeleteSettingAsync(string key, CancellationToken ct = default)
{
try
{
var setting = await _db.AppSettings
.FirstOrDefaultAsync(s => s.Key == key, ct);
if (setting is null)
{
_logger.LogWarning("Attempted to delete non-existent setting '{Key}'", key);
return ServiceResult.NotFound($"Setting '{key}' not found");
}
_db.AppSettings.Remove(setting);
await _db.SaveChangesAsync(ct);
_logger.LogInformation("Deleted setting '{Key}'", key);
return ServiceResult.Success();
}
catch (OperationCanceledException)
{
return ServiceResult.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete setting '{Key}'", key);
return ServiceResult.Failure("An error occurred while deleting the setting");
}
}
// ──────────────────────────── Agent-Specific Overrides ────────────────────────────
/// <inheritdoc />
public async Task<ServiceResult<List<AgentSettingDto>>> GetAgentSettingsAsync(Guid agentId, CancellationToken ct = default)
{
try
{
var settings = await _db.AgentSettings
.Where(s => s.AgentId == agentId)
.OrderBy(s => s.Key)
.ToListAsync(ct);
return ServiceResult<List<AgentSettingDto>>.Success(
settings.Select(MapToAgentDto).ToList());
}
catch (OperationCanceledException)
{
return ServiceResult<List<AgentSettingDto>>.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve settings for agent {AgentId}", agentId);
return ServiceResult<List<AgentSettingDto>>.Failure("An error occurred while retrieving agent settings");
}
}
/// <inheritdoc />
public async Task<ServiceResult<AgentSettingDto>> SetAgentSettingAsync(Guid agentId, SetAgentSettingRequest request, CancellationToken ct = default)
{
try
{
var key = request.Key.Trim().ToLowerInvariant();
var existing = await _db.AgentSettings
.FirstOrDefaultAsync(s => s.AgentId == agentId && s.Key == key, ct);
if (existing is not null)
{
existing.UpdateValue(request.Value);
_logger.LogInformation("Updated agent setting '{Key}' for agent {AgentId}", key, agentId);
}
else
{
existing = new AgentSetting(agentId, key, request.Value);
_db.AgentSettings.Add(existing);
_logger.LogInformation("Created agent setting '{Key}' for agent {AgentId}", key, agentId);
}
await _db.SaveChangesAsync(ct);
return ServiceResult<AgentSettingDto>.Success(MapToAgentDto(existing));
}
catch (OperationCanceledException)
{
return ServiceResult<AgentSettingDto>.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to set agent setting '{Key}' for agent {AgentId}", request.Key, agentId);
return ServiceResult<AgentSettingDto>.Failure("An error occurred while setting the agent setting");
}
}
/// <inheritdoc />
public async Task<ServiceResult> RemoveAgentSettingAsync(Guid agentId, string key, CancellationToken ct = default)
{
try
{
var setting = await _db.AgentSettings
.FirstOrDefaultAsync(s => s.AgentId == agentId && s.Key == key, ct);
if (setting is null)
{
_logger.LogWarning("Attempted to remove non-existent agent setting '{Key}' for agent {AgentId}", key, agentId);
return ServiceResult.NotFound($"Agent setting '{key}' not found for agent {agentId}");
}
_db.AgentSettings.Remove(setting);
await _db.SaveChangesAsync(ct);
_logger.LogInformation("Removed agent setting '{Key}' for agent {AgentId}", key, agentId);
return ServiceResult.Success();
}
catch (OperationCanceledException)
{
return ServiceResult.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to remove agent setting '{Key}' for agent {AgentId}", key, agentId);
return ServiceResult.Failure("An error occurred while removing the agent setting");
}
}
// ──────────────────────────── Effective Config (Merge) ────────────────────────────
/// <inheritdoc />
public async Task<ServiceResult<Dictionary<string, string>>> GetEffectiveAgentConfigAsync(Guid agentId, CancellationToken ct = default)
{
try
{
// Load all global app settings as the base configuration
var appSettings = await _db.AppSettings.ToListAsync(ct);
var config = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var s in appSettings)
{
config[s.Key] = s.Value;
}
// Load agent-specific overrides and overlay them
var agentSettings = await _db.AgentSettings
.Where(s => s.AgentId == agentId)
.ToListAsync(ct);
foreach (var s in agentSettings)
{
config[s.Key] = s.Value;
}
return ServiceResult<Dictionary<string, string>>.Success(config);
}
catch (OperationCanceledException)
{
return ServiceResult<Dictionary<string, string>>.Failure("Operation was cancelled");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to compute effective config for agent {AgentId}", agentId);
return ServiceResult<Dictionary<string, string>>.Failure("An error occurred while computing the effective configuration");
}
}
// ──────────────────────────── Mapping Helpers ────────────────────────────
private static AppSettingDto MapToDto(AppSetting s) => new(
s.Id,
s.Key,
s.Value,
s.Description,
s.Category,
s.ValueType,
s.AllowedValues,
s.UpdatedAt);
private static AgentSettingDto MapToAgentDto(AgentSetting s) => new(
s.Id,
s.AgentId,
s.Key,
s.Value,
s.UpdatedAt);
}