Fix API deploy healthcheck by starting Kestrel before migrate/seed.
Compose was marking the API unhealthy because bootstrap blocked app.Run(), so /health/live never answered within the HEALTHCHECK window.
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Minio;
|
||||
using Minio.DataModel.Args;
|
||||
|
||||
/// <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);
|
||||
|
||||
var minio = scope.ServiceProvider.GetRequiredService<IMinioClient>();
|
||||
var minioOpts = scope.ServiceProvider.GetRequiredService<IOptions<MinioOptions>>().Value;
|
||||
if (!await minio.BucketExistsAsync(
|
||||
new BucketExistsArgs().WithBucket(minioOpts.BucketName), stoppingToken))
|
||||
{
|
||||
await minio.MakeBucketAsync(
|
||||
new MakeBucketArgs().WithBucket(minioOpts.BucketName), stoppingToken);
|
||||
_logger.LogInformation("Created MinIO bucket {Bucket}", minioOpts.BucketName);
|
||||
}
|
||||
|
||||
_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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user