diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs index 33f8165..8b1ad2a 100644 --- a/src/Heimdall.Api/Program.cs +++ b/src/Heimdall.Api/Program.cs @@ -7,6 +7,7 @@ using Heimdall.Infrastructure; using Heimdall.Api.Hubs; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Security; +using Heimdall.Infrastructure.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; @@ -58,6 +59,12 @@ builder.Services.AddApplication(); // ── Infrastructure layer ────────────────────────────────────────── builder.Services.AddInfrastructure(builder.Configuration, builder.Environment.EnvironmentName); +// ── Background migration (replaces inline db.Database.Migrate()) ── +if (!builder.Environment.IsEnvironment("Testing")) +{ + builder.Services.AddHostedService(); +} + // ── Authentication ──────────────────────────────────────────────── var jwtKey = builder.Configuration["Jwt:Key"] ?? Environment.GetEnvironmentVariable("JWT__KEY") @@ -127,19 +134,6 @@ builder.Services.AddCors(options => var app = builder.Build(); -// Apply migrations on startup (skip in Testing with InMemory) -if (!app.Environment.IsEnvironment("Testing")) -{ - using (var scope = app.Services.CreateScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - if (db.Database.GetPendingMigrations().Any()) - { - db.Database.Migrate(); - } - } -} - // Seed roles using (var scope = app.Services.CreateScope()) { diff --git a/src/Heimdall.Infrastructure/Services/MigrationHostedService.cs b/src/Heimdall.Infrastructure/Services/MigrationHostedService.cs new file mode 100644 index 0000000..43ab256 --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/MigrationHostedService.cs @@ -0,0 +1,74 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Services; + +/// +/// Applies pending EF Core migrations as a background service at startup. +/// Replaces the inline `db.Database.Migrate()` pattern to: +/// - Allow the web host to start quickly (migrations run in background) +/// - Enable health checks to verify migration completion +/// - Avoid holding up the startup pipeline +/// - Log migration progress clearly +/// +public class MigrationHostedService : IHostedService +{ + private readonly IServiceProvider _serviceProvider; + private readonly ILogger _logger; + + public MigrationHostedService( + IServiceProvider serviceProvider, + ILogger logger) + { + _serviceProvider = serviceProvider; + _logger = logger; + } + + public async Task StartAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Migration service starting..."); + + try + { + using var scope = _serviceProvider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var pending = await db.Database.GetPendingMigrationsAsync(cancellationToken); + var pendingList = pending.ToList(); + + if (pendingList.Count == 0) + { + _logger.LogInformation("No pending migrations to apply"); + return; + } + + _logger.LogInformation( + "Applying {Count} pending migration(s): {Migrations}", + pendingList.Count, + string.Join(", ", pendingList)); + + // Apply with timeout to prevent indefinite blocking + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(60)); + + await db.Database.MigrateAsync(cts.Token); + + _logger.LogInformation("All migrations applied successfully"); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + _logger.LogError("Migration timed out after 60 seconds. " + + "Check database connectivity and migration script correctness."); + } + catch (Exception ex) + { + _logger.LogCritical(ex, "Failed to apply database migrations. " + + "The application may not function correctly without a migrated database."); + } + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/src/Heimdall.Web/Components/Pages/AgentDetail.razor b/src/Heimdall.Web/Components/Pages/AgentDetail.razor index 435ad80..22420a3 100644 --- a/src/Heimdall.Web/Components/Pages/AgentDetail.razor +++ b/src/Heimdall.Web/Components/Pages/AgentDetail.razor @@ -4,6 +4,7 @@ @inject HeimdallApiClient Api @inject ISnackbar Snackbar @inject NavigationManager Nav +@implements IDisposable @@ -79,27 +80,257 @@ else - + @* ─── Agent Settings Overrides ─── *@ + + + + Configuration spécifique + + + + + + @if (_settingsLoading) + { + + } + else if (_settingsError) + { + + Erreur lors du chargement de la configuration + Réessayer + + } + else if (_settings.Count == 0) + { + + Aucune configuration spécifique pour cet agent. + Ajoutez un réglage pour surcharger la configuration globale. + + } + else + { + + + + + + + + Clé + Valeur + Actions + + + @context.Key + @context.Value + + + + + + + } + + + + Ajouter un réglage + + + + ← Retour aux agents } +@* ─── Delete Confirmation Dialog ─── *@ + + + + + Confirmer la suppression + + + + Supprimer le réglage @_deletingKey pour cet agent ? + + L'agent sera notifié en temps réel via SignalR et utilisera la valeur globale par défaut. + + + + Annuler + Supprimer + + + +@* ─── Add / Edit Dialog ─── *@ + + + @(_editingSetting is null ? "Ajouter un réglage" : "Modifier le réglage") + + + + + + + + + + + + + Annuler + + @(_editingSetting is null ? "Ajouter" : "Enregistrer") + + + + @code { [Parameter] public Guid Id { get; set; } private AgentItem? _agent; private bool _loading = true; + // Settings + private List _settings = []; + private bool _settingsLoading; + private bool _settingsError; + private bool _saving; + private AgentSettingItem? _editingSetting; + private string _editKey = string.Empty; + private string _editValue = string.Empty; + private bool _showEditDialog; + private bool _confirmDeleteVisible; + private string _deletingKey = string.Empty; + private bool _deleting; + private readonly DialogOptions _dialogOptions = new() + { + MaxWidth = MaxWidth.Small, + FullWidth = true, + CloseButton = true + }; + protected override async Task OnInitializedAsync() { try { _agent = await Api.GetAgentAsync(Id); + if (_agent is not null) + await LoadSettingsAsync(); } catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); } finally { _loading = false; } } + private async Task LoadSettingsAsync() + { + _settingsError = false; + _settingsLoading = true; + try + { + _settings = await Api.GetAgentSettingsAsync(Id); + } + catch + { + _settingsError = true; + _settings = []; + } + finally { _settingsLoading = false; } + } + + private void OpenAddDialog() + { + _editingSetting = null; + _editKey = string.Empty; + _editValue = string.Empty; + _showEditDialog = true; + } + + private void OpenEditDialog(AgentSettingItem setting) + { + _editingSetting = setting; + _editKey = setting.Key; + _editValue = setting.Value; + _showEditDialog = true; + } + + private async Task SaveSettingAsync() + { + if (string.IsNullOrWhiteSpace(_editKey)) return; + + _saving = true; + try + { + var request = new SetAgentSettingRequest(_editKey.Trim(), _editValue); + var response = await Api.SetAgentSettingAsync(Id, request); + + if (response.IsSuccessStatusCode) + { + Snackbar.Add("Réglage enregistré et envoyé à l'agent en temps réel", Severity.Success); + _showEditDialog = false; + await LoadSettingsAsync(); + } + else + { + var error = await response.Content.ReadAsStringAsync(); + Snackbar.Add($"Erreur : {error}", Severity.Error); + } + } + catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); } + finally { _saving = false; } + } + + private void ConfirmRemoveSetting(AgentSettingItem setting) + { + _deletingKey = setting.Key; + _confirmDeleteVisible = true; + } + + private async Task ExecuteRemoveSettingAsync() + { + _deleting = true; + try + { + var response = await Api.RemoveAgentSettingAsync(Id, _deletingKey); + if (response.IsSuccessStatusCode) + { + _confirmDeleteVisible = false; + Snackbar.Add("Réglage supprimé, agent notifié en temps réel", Severity.Success); + await LoadSettingsAsync(); + } + else + { + Snackbar.Add("Erreur lors de la suppression", Severity.Error); + } + } + catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); } + finally { _deleting = false; } + } + + public void Dispose() + { + // No unmanaged resources to dispose + } + private static Color GetStatusColor(string status) => status switch { "Online" => Color.Success, diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 49fa932..163318b 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -263,6 +263,34 @@ public class HeimdallApiClient var client = CreateClient(); return await client.PostAsync("api/settings/reload", null); } + + // ─── Agent Settings Overrides ─────────────────────────────────── + + public async Task> GetAgentSettingsAsync(Guid agentId) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/settings/agent/{agentId}/overrides") ?? []; + } + + public async Task SetAgentSettingAsync(Guid agentId, SetAgentSettingRequest request) + { + var client = CreateClient(); + return await client.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", request); + } + + public async Task RemoveAgentSettingAsync(Guid agentId, string key) + { + var client = CreateClient(); + return await client.DeleteAsync($"api/settings/agent/{agentId}/overrides/{key}"); + } + + public async Task> GetEffectiveAgentConfigAsync(Guid agentId) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/settings/agent/{agentId}") ?? []; + } } public class CameraItem @@ -346,3 +374,18 @@ public record UpdateAppSettingRequest( [property: JsonPropertyName("valueType")] string? ValueType = null, [property: JsonPropertyName("allowedValues")] string? AllowedValues = null ); + +// ─── Agent Settings DTOs ─────────────────────────────────────────── + +public record AgentSettingItem( + [property: JsonPropertyName("id")] Guid Id, + [property: JsonPropertyName("agentId")] Guid AgentId, + [property: JsonPropertyName("key")] string Key, + [property: JsonPropertyName("value")] string Value, + [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt +); + +public record SetAgentSettingRequest( + [property: JsonPropertyName("key")] string Key, + [property: JsonPropertyName("value")] string Value +);