| | | 1 | | namespace Anichron.Infrastructure.Data; |
| | | 2 | | |
| | | 3 | | public interface IAdvisoryLock |
| | | 4 | | { |
| | | 5 | | Task<bool> TryAcquireAsync(CancellationToken ct); |
| | | 6 | | Task ReleaseAsync(CancellationToken ct); |
| | | 7 | | } |
| | | 8 | | |
| | 4 | 9 | | public sealed class AdvisoryLockMigrator(IAdvisoryLock advisoryLock, TimeProvider timeProvider, int maxAttempts) |
| | | 10 | | { |
| | 1 | 11 | | private static readonly TimeSpan pollInterval = TimeSpan.FromSeconds(1); |
| | | 12 | | |
| | | 13 | | public async Task RunAsync(Func<CancellationToken, Task> migrate, CancellationToken ct) |
| | 4 | 14 | | { |
| | 16 | 15 | | for (var attempt = 1; attempt <= maxAttempts; attempt++) |
| | 7 | 16 | | { |
| | 7 | 17 | | if (await advisoryLock.TryAcquireAsync(ct)) |
| | 3 | 18 | | { |
| | | 19 | | try |
| | 3 | 20 | | { |
| | 3 | 21 | | await migrate(ct); |
| | 2 | 22 | | return; |
| | | 23 | | } |
| | | 24 | | finally |
| | 3 | 25 | | { |
| | 3 | 26 | | await advisoryLock.ReleaseAsync(ct); |
| | 3 | 27 | | } |
| | 0 | 28 | | } |
| | | 29 | | |
| | 4 | 30 | | if (attempt < maxAttempts) |
| | 3 | 31 | | await Task.Delay(pollInterval, timeProvider, ct); |
| | 4 | 32 | | } |
| | | 33 | | |
| | 1 | 34 | | throw new TimeoutException( |
| | 1 | 35 | | $"Could not acquire the migration advisory lock after {maxAttempts} attempts."); |
| | 2 | 36 | | } |
| | | 37 | | } |