feat(mvp): agent settings UI + migration orchestrator
Agent settings UI: - Add settings section to AgentDetail page showing per-agent overrides - Add/edit/delete agent settings with confirmation dialogs - Add settings API methods + DTOs to HeimdallApiClient - Real-time SignalR notification shown in UI feedback Migration orchestrator: - Replace inline db.Database.Migrate() with MigrationHostedService - Runs migrations in background at startup (non-blocking) - 60-second timeout with critical logging on failure - Preserves Testing environment exclusion - Clear migration progress logging
This commit is contained in:
1 parent
c2837af089
commit
cca6ab6f46
4 files changed
+356
-14
No files matched your search
@@ -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<MigrationHostedService>();
|
||||
}
|
||||
|
||||
// ── 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<AppDbContext>();
|
||||
if (db.Database.GetPendingMigrations().Any())
|
||||
{
|
||||
db.Database.Migrate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Seed roles
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// </summary>
|
||||
public class MigrationHostedService : IHostedService
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly ILogger<MigrationHostedService> _logger;
|
||||
|
||||
public MigrationHostedService(
|
||||
IServiceProvider serviceProvider,
|
||||
ILogger<MigrationHostedService> 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<AppDbContext>();
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
@inject HeimdallApiClient Api
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Nav
|
||||
@implements IDisposable
|
||||
|
||||
<MudText Typo="Typo.h4" Class="mb-6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Dns" Class="mr-2" />
|
||||
@@ -79,27 +80,257 @@ else
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Default" OnClick="@(() => Nav.NavigateTo($"/sites/{_agent.SiteId}/agents"))">
|
||||
@* ─── Agent Settings Overrides ─── *@
|
||||
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h6" Class="mb-4">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Tune" Class="mr-2" />
|
||||
Configuration spécifique
|
||||
<MudTooltip Text="Ces réglages prennent le pas sur la configuration globale pour cet agent uniquement. Envoyés en temps réel via SignalR.">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Info" Size="Size.Small" Class="ml-1" Color="Color.Primary" />
|
||||
</MudTooltip>
|
||||
</MudText>
|
||||
|
||||
@if (_settingsLoading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" Size="Size.Small" />
|
||||
}
|
||||
else if (_settingsError)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">
|
||||
Erreur lors du chargement de la configuration
|
||||
<MudButton OnClick="@LoadSettingsAsync" Size="Size.Small" Variant="Variant.Text" Class="ml-2">Réessayer</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else if (_settings.Count == 0)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mb-4">
|
||||
Aucune configuration spécifique pour cet agent.
|
||||
Ajoutez un réglage pour surcharger la configuration globale.
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_settings" Hover="true" Dense="true" Class="mb-4">
|
||||
<ColGroup>
|
||||
<col style="width: 40%;" />
|
||||
<col style="width: 40%;" />
|
||||
<col style="width: 20%;" />
|
||||
</ColGroup>
|
||||
<HeaderContent>
|
||||
<MudTh>Clé</MudTh>
|
||||
<MudTh>Valeur</MudTh>
|
||||
<MudTh>Actions</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd><MudText Typo="Typo.body2">@context.Key</MudText></MudTd>
|
||||
<MudTd><MudText Typo="Typo.body2">@context.Value</MudText></MudTd>
|
||||
<MudTd>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small"
|
||||
OnClick="@(() => OpenEditDialog(context))" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Error"
|
||||
OnClick="@(() => ConfirmRemoveSetting(context))" />
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
}
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary"
|
||||
OnClick="@OpenAddDialog" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" />
|
||||
Ajouter un réglage
|
||||
</MudButton>
|
||||
</MudPaper>
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Default"
|
||||
OnClick="@(() => Nav.NavigateTo($"/sites/{_agent.SiteId}/agents"))">
|
||||
← Retour aux agents
|
||||
</MudButton>
|
||||
}
|
||||
|
||||
@* ─── Delete Confirmation Dialog ─── *@
|
||||
<MudDialog @bind-Visible="_confirmDeleteVisible" Options="_dialogOptions">
|
||||
<TitleContent>
|
||||
<MudText Typo="Typo.h6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Warning" Color="Color.Warning" Class="mr-2" />
|
||||
Confirmer la suppression
|
||||
</MudText>
|
||||
</TitleContent>
|
||||
<DialogContent>
|
||||
<MudText>Supprimer le réglage <strong>@_deletingKey</strong> pour cet agent ?</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2">
|
||||
L'agent sera notifié en temps réel via SignalR et utilisera la valeur globale par défaut.
|
||||
</MudText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteVisible = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Error"
|
||||
OnClick="@ExecuteRemoveSettingAsync"
|
||||
Loading="@_deleting"
|
||||
Disabled="@_deleting">Supprimer</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@* ─── Add / Edit Dialog ─── *@
|
||||
<MudDialog @bind-Visible="_showEditDialog" Options="_dialogOptions">
|
||||
<TitleContent>
|
||||
<MudText Typo="Typo.h6">@(_editingSetting is null ? "Ajouter un réglage" : "Modifier le réglage")</MudText>
|
||||
</TitleContent>
|
||||
<DialogContent>
|
||||
<MudGrid>
|
||||
<MudItem xs="12">
|
||||
<MudTextField Label="Clé"
|
||||
@bind-Value="_editKey"
|
||||
Disabled="@(_editingSetting is not null)"
|
||||
For="@(() => _editKey)"
|
||||
Required="true"
|
||||
HelperText="Ex: heartbeat.interval.seconds" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudTextField Label="Valeur"
|
||||
@bind-Value="_editValue"
|
||||
For="@(() => _editValue)"
|
||||
Required="true" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _showEditDialog = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary"
|
||||
OnClick="@SaveSettingAsync"
|
||||
Disabled="@_saving"
|
||||
Loading="@_saving">
|
||||
@(_editingSetting is null ? "Ajouter" : "Enregistrer")
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@code {
|
||||
[Parameter] public Guid Id { get; set; }
|
||||
|
||||
private AgentItem? _agent;
|
||||
private bool _loading = true;
|
||||
|
||||
// Settings
|
||||
private List<AgentSettingItem> _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,
|
||||
|
||||
@@ -263,6 +263,34 @@ public class HeimdallApiClient
|
||||
var client = CreateClient();
|
||||
return await client.PostAsync("api/settings/reload", null);
|
||||
}
|
||||
|
||||
// ─── Agent Settings Overrides ───────────────────────────────────
|
||||
|
||||
public async Task<List<AgentSettingItem>> GetAgentSettingsAsync(Guid agentId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<List<AgentSettingItem>>(
|
||||
$"api/settings/agent/{agentId}/overrides") ?? [];
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> SetAgentSettingAsync(Guid agentId, SetAgentSettingRequest request)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", request);
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> RemoveAgentSettingAsync(Guid agentId, string key)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.DeleteAsync($"api/settings/agent/{agentId}/overrides/{key}");
|
||||
}
|
||||
|
||||
public async Task<Dictionary<string, string>> GetEffectiveAgentConfigAsync(Guid agentId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<Dictionary<string, string>>(
|
||||
$"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
|
||||
);
|
||||
Reference in new issue
Block a user