Files
vigilcare-records/VigilCareRecordsAPI/BackgroundServices/AppBootstrapHostedService.cs
T
Trent a17bc2b734
CI / changes (push) Successful in 17s
dotnet8-ci / build-and-test (push) Successful in 8m23s
CI / backend (push) Successful in 8m24s
node-ci / build (push) Failing after 2m1s
CI / frontend (push) Failing after 2m2s
Harden API memory and CPU usage across Phases 19–22.
Bound list/PDF payloads, stream MinIO I/O with cancellation, paginate history and FHIR $everything, tighten OCR lifetimes/buffers, and add phase tracking docs.
2026-11-30 23:55:56 +08:00

56 lines
2.2 KiB
C#

using Microsoft.EntityFrameworkCore;
/// <summary>
/// Runs migrate / demo seed / MinIO bucket ensure after Kestrel is listening.
/// Keeping this off the Program.cs path before <c>app.Run()</c> lets Docker's
/// /health/live HEALTHCHECK succeed while dependencies warm up; /health/ready
/// stays gated by <see cref="StartupHealthCheck"/> until this finishes.
/// </summary>
public sealed class AppBootstrapHostedService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly StartupHealthCheck _startupHealthCheck;
private readonly IHostApplicationLifetime _lifetime;
private readonly ILogger<AppBootstrapHostedService> _logger;
public AppBootstrapHostedService(
IServiceScopeFactory scopeFactory,
StartupHealthCheck startupHealthCheck,
IHostApplicationLifetime lifetime,
ILogger<AppBootstrapHostedService> logger)
{
_scopeFactory = scopeFactory;
_startupHealthCheck = startupHealthCheck;
_lifetime = lifetime;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Yield so the generic host can finish starting Kestrel before we block on I/O.
await Task.Yield();
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync(stoppingToken);
await DataSeeder.SeedAsync(db, stoppingToken);
var storage = scope.ServiceProvider.GetRequiredService<IDocumentStorageService>();
await storage.EnsureBucketAsync(stoppingToken);
_logger.LogInformation("MinIO bucket ensure completed.");
await SeedDocumentStorage.EnsureAsync(db, storage, _logger, stoppingToken);
_startupHealthCheck.StartupCompleted = true;
_logger.LogInformation("Application bootstrap completed.");
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogCritical(ex, "Application bootstrap failed — stopping host.");
_lifetime.StopApplication();
}
}
}