Skip to content

Commit

Permalink
Update migration step to retry for 10 seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
irby committed Jun 19, 2023
1 parent bcf4a10 commit 3c0c594
Showing 1 changed file with 32 additions and 17 deletions.
49 changes: 32 additions & 17 deletions src/api/SecretsSharingTool.Data/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,32 +21,47 @@ public static IServiceCollection AddDatabaseAccessor(this IServiceCollection ser

public static void ApplyPendingMigrations(this IServiceCollection services)
{
var numAttempts = 0;
var allowedAttempts = 10;
Exception exception = null;

Check warning on line 26 in src/api/SecretsSharingTool.Data/DependencyInjection.cs

View workflow job for this annotation

GitHub Actions / Test API (6.0.x)

Converting null literal or possible null value to non-nullable type.

var traceId = Guid.NewGuid();
var provider = services.BuildServiceProvider();
var db = provider.GetService<AppUnitOfWork>()!;
var logger = provider.GetService<ILogger<AppUnitOfWork>>()!;
var pendingMigrations = db.Database.GetPendingMigrations().ToList();
LogMessageWithTraceId(logger, $"{pendingMigrations.Count} database migration(s) waiting to be applied.", traceId);

if (!pendingMigrations.Any())
while (numAttempts < allowedAttempts)
{
LogMessageWithTraceId(logger, "No migrations will be applied.", traceId);
return;
}
try
{
var pendingMigrations = db.Database.GetPendingMigrations().ToList();

LogMessageWithTraceId(logger, $"{pendingMigrations.Count} database migration(s) waiting to be applied.", traceId);

if (!pendingMigrations.Any())
{
LogMessageWithTraceId(logger, "No migrations will be applied.", traceId);
return;
}

LogMessageWithTraceId(logger, $"Applying {pendingMigrations.Count} migration(s) to the database...", traceId);
LogMessageWithTraceId(logger, string.Join(", ", pendingMigrations), traceId);
LogMessageWithTraceId(logger, $"Applying {pendingMigrations.Count} migration(s) to the database...", traceId);
LogMessageWithTraceId(logger, string.Join(", ", pendingMigrations), traceId);

try
{
db.Database.Migrate();
LogMessageWithTraceId(logger, "Database migration(s) have been successfully applied.", traceId);
}
catch (Exception ex)
{
logger.LogCritical(ex, $"An error occurred while applying migration. \nError: {ex.Message}. \nTrace ID: {traceId}");
throw;
db.Database.Migrate();
LogMessageWithTraceId(logger, "Database migration(s) have been successfully applied.", traceId);

return;
}
catch (Exception ex)
{
exception = ex;
Thread.Sleep(1000);
numAttempts++;
}
}


logger.LogCritical(exception, $"An error occurred while applying migration. \nError: {exception!.Message}. \nTrace ID: {traceId}");
}

private static void LogMessageWithTraceId(ILogger logger, string message, Guid traceId)
Expand Down

0 comments on commit 3c0c594

Please sign in to comment.