Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add information logging for pending DB migrations (#2159)

Leendert de Borst31a97215e7be
diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.cs
index efe3c1778..e3a83cbee 100644
--- a/apps/server/AliasVault.Api/Program.cs
+++ b/apps/server/AliasVault.Api/Program.cs
@@ -220,11 +220,12 @@ app.MapControllers();
using (var scope = app.Services.CreateScope())
{
var container = scope.ServiceProvider;
+ var migrationLogger = container.GetRequiredService<ILoggerFactory>().CreateLogger("AliasVault.DatabaseMigrations");
await using var db = await container.GetRequiredService<IAliasServerDbContextFactory>().CreateDbContextAsync();
// Raise the command timeout for migrations.
db.Database.SetCommandTimeout((int)TimeSpan.FromMinutes(60).TotalSeconds);
- await db.Database.MigrateAsync();
+ await db.MigrateWithLoggingAsync(migrationLogger);
}
await app.RunAsync();
diff --git a/apps/server/AliasVault.Api/appsettings.json b/apps/server/AliasVault.Api/appsettings.json
index ad5f9a95f..2466e1d4a 100644
--- a/apps/server/AliasVault.Api/appsettings.json
+++ b/apps/server/AliasVault.Api/appsettings.json
@@ -2,6 +2,7 @@
"Logging": {
"LogLevel": {
"Default": "Warning",
+ "AliasVault.DatabaseMigrations": "Information",
"Microsoft.AspNetCore.Server.Kestrel": "Error",
"Microsoft.AspNetCore.Hosting.Diagnostics" : "Error",
"Microsoft.EntityFrameworkCore": "Warning",
diff --git a/apps/server/Databases/AliasServerDb/Configuration/DatabaseConfiguration.cs b/apps/server/Databases/AliasServerDb/Configuration/DatabaseConfiguration.cs
index 7e1c81e1b..0780015c9 100644
--- a/apps/server/Databases/AliasServerDb/Configuration/DatabaseConfiguration.cs
+++ b/apps/server/Databases/AliasServerDb/Configuration/DatabaseConfiguration.cs
@@ -7,6 +7,7 @@
namespace AliasServerDb.Configuration;
+using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -71,6 +72,39 @@ public static class DatabaseConfiguration
return services;
}
+ /// <summary>
+ /// Applies all pending migrations, reporting which migration is being applied and how long each one took.
+ /// </summary>
+ /// <param name="context">The database context to migrate.</param>
+ /// <param name="logger">Logger to report the migration progress on.</param>
+ /// <param name="cancellationToken">Cancellation token.</param>
+ /// <returns>A task representing the asynchronous operation.</returns>
+ public static async Task MigrateWithLoggingAsync(this DbContext context, ILogger logger, CancellationToken cancellationToken = default)
+ {
+ var pendingMigrations = (await context.Database.GetPendingMigrationsAsync(cancellationToken)).ToList();
+ if (pendingMigrations.Count == 0)
+ {
+ logger.LogInformation("Database schema is up-to-date, no migrations to apply.");
+ return;
+ }
+
+ logger.LogInformation("Database schema is behind, applying {Count} pending migration(s): {Migrations}", pendingMigrations.Count, string.Join(", ", pendingMigrations));
+
+ var totalStopwatch = Stopwatch.StartNew();
+ for (var index = 0; index < pendingMigrations.Count; index++)
+ {
+ var migration = pendingMigrations[index];
+ logger.LogInformation("Applying migration {Index}/{Count}: {Migration} ...", index + 1, pendingMigrations.Count, migration);
+
+ var migrationStopwatch = Stopwatch.StartNew();
+ await context.Database.MigrateAsync(migration, cancellationToken);
+
+ logger.LogInformation("Applied migration {Index}/{Count}: {Migration} in {Duration}", index + 1, pendingMigrations.Count, migration, FormatDuration(migrationStopwatch.Elapsed));
+ }
+
+ logger.LogInformation("Database schema is up-to-date, applied {Count} migration(s) in {Duration}.", pendingMigrations.Count, FormatDuration(totalStopwatch.Elapsed));
+ }
+
/// <summary>
/// Waits for the database to be ready by checking if all migrations have been applied.
/// This is useful for services that should not run migrations themselves but need to wait
@@ -153,4 +187,24 @@ public static class DatabaseConfiguration
throw new TimeoutException($"Database did not become ready within {timeoutSeconds} seconds. Migrations may not have completed.");
}
+
+ /// <summary>
+ /// Formats an elapsed timespan as a short human readable duration, scaled to how long it actually took.
+ /// </summary>
+ /// <param name="elapsed">The elapsed time to format.</param>
+ /// <returns>The formatted duration, e.g. "84ms", "7.0s" or "2m 5s".</returns>
+ private static string FormatDuration(TimeSpan elapsed)
+ {
+ if (elapsed.TotalSeconds < 1)
+ {
+ return FormattableString.Invariant($"{elapsed.TotalMilliseconds:F0}ms");
+ }
+
+ if (elapsed.TotalMinutes < 1)
+ {
+ return FormattableString.Invariant($"{elapsed.TotalSeconds:F1}s");
+ }
+
+ return FormattableString.Invariant($"{(int)elapsed.TotalMinutes}m {elapsed.Seconds}s");
+ }
}