| | | 1 | | using System; |
| | | 2 | | using System.Data.Common; |
| | | 3 | | using System.Linq; |
| | | 4 | | using System.Security.Cryptography; |
| | | 5 | | using System.Threading; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using Microsoft.EntityFrameworkCore; |
| | | 8 | | using Microsoft.EntityFrameworkCore.Diagnostics; |
| | | 9 | | using Microsoft.Extensions.Logging; |
| | | 10 | | using Polly; |
| | | 11 | | |
| | | 12 | | namespace Jellyfin.Database.Implementations.Locking; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Defines a locking mechanism that will retry any write operation for a few times. |
| | | 16 | | /// </summary> |
| | | 17 | | public class OptimisticLockBehavior : IEntityFrameworkCoreLockingBehavior |
| | | 18 | | { |
| | | 19 | | private readonly Policy _writePolicy; |
| | | 20 | | private readonly AsyncPolicy _writeAsyncPolicy; |
| | | 21 | | private readonly ILogger<OptimisticLockBehavior> _logger; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Initializes a new instance of the <see cref="OptimisticLockBehavior"/> class. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="logger">The application logger.</param> |
| | | 27 | | public OptimisticLockBehavior(ILogger<OptimisticLockBehavior> logger) |
| | | 28 | | { |
| | 0 | 29 | | TimeSpan[] sleepDurations = [ |
| | 0 | 30 | | TimeSpan.FromMilliseconds(50), |
| | 0 | 31 | | TimeSpan.FromMilliseconds(50), |
| | 0 | 32 | | TimeSpan.FromMilliseconds(50), |
| | 0 | 33 | | TimeSpan.FromMilliseconds(50), |
| | 0 | 34 | | TimeSpan.FromMilliseconds(250), |
| | 0 | 35 | | TimeSpan.FromMilliseconds(250), |
| | 0 | 36 | | TimeSpan.FromMilliseconds(250), |
| | 0 | 37 | | TimeSpan.FromMilliseconds(150), |
| | 0 | 38 | | TimeSpan.FromMilliseconds(150), |
| | 0 | 39 | | TimeSpan.FromMilliseconds(150), |
| | 0 | 40 | | TimeSpan.FromMilliseconds(500), |
| | 0 | 41 | | TimeSpan.FromMilliseconds(150), |
| | 0 | 42 | | TimeSpan.FromMilliseconds(500), |
| | 0 | 43 | | TimeSpan.FromMilliseconds(150), |
| | 0 | 44 | | TimeSpan.FromSeconds(3) |
| | 0 | 45 | | ]; |
| | | 46 | | |
| | 0 | 47 | | Func<int, Context, TimeSpan> backoffProvider = (index, context) => |
| | 0 | 48 | | { |
| | 0 | 49 | | var backoff = sleepDurations[index]; |
| | 0 | 50 | | return backoff + TimeSpan.FromMilliseconds(RandomNumberGenerator.GetInt32(0, (int)(backoff.TotalMilliseconds |
| | 0 | 51 | | }; |
| | | 52 | | |
| | 0 | 53 | | _logger = logger; |
| | 0 | 54 | | _writePolicy = Policy |
| | 0 | 55 | | .HandleInner<Exception>(e => |
| | 0 | 56 | | e.Message.Contains("database is locked", StringComparison.InvariantCultureIgnoreCase) || |
| | 0 | 57 | | e.Message.Contains("database table is locked", StringComparison.InvariantCultureIgnoreCase)) |
| | 0 | 58 | | .WaitAndRetry(sleepDurations.Length, backoffProvider, RetryHandle); |
| | 0 | 59 | | _writeAsyncPolicy = Policy |
| | 0 | 60 | | .HandleInner<Exception>(e => |
| | 0 | 61 | | e.Message.Contains("database is locked", StringComparison.InvariantCultureIgnoreCase) || |
| | 0 | 62 | | e.Message.Contains("database table is locked", StringComparison.InvariantCultureIgnoreCase)) |
| | 0 | 63 | | .WaitAndRetryAsync(sleepDurations.Length, backoffProvider, RetryHandle); |
| | | 64 | | |
| | | 65 | | void RetryHandle(Exception exception, TimeSpan timespan, int retryNo, Context context) |
| | | 66 | | { |
| | | 67 | | if (retryNo < sleepDurations.Length) |
| | | 68 | | { |
| | | 69 | | _logger.LogWarning("Operation failed retry {RetryNo}", retryNo); |
| | | 70 | | } |
| | | 71 | | else |
| | | 72 | | { |
| | | 73 | | _logger.LogError(exception, "Operation failed retry {RetryNo}", retryNo); |
| | | 74 | | } |
| | | 75 | | } |
| | 0 | 76 | | } |
| | | 77 | | |
| | | 78 | | /// <inheritdoc/> |
| | | 79 | | public void Initialise(DbContextOptionsBuilder optionsBuilder) |
| | | 80 | | { |
| | 0 | 81 | | _logger.LogInformation("The database locking mode has been set to: Optimistic."); |
| | 0 | 82 | | optionsBuilder.AddInterceptors(new RetryInterceptor(_writeAsyncPolicy, _writePolicy)); |
| | 0 | 83 | | optionsBuilder.AddInterceptors(new TransactionLockingInterceptor(_writeAsyncPolicy, _writePolicy)); |
| | 0 | 84 | | } |
| | | 85 | | |
| | | 86 | | /// <inheritdoc/> |
| | | 87 | | public void OnSaveChanges(JellyfinDbContext context, Action saveChanges) |
| | | 88 | | { |
| | 0 | 89 | | _writePolicy.ExecuteAndCapture(saveChanges); |
| | 0 | 90 | | } |
| | | 91 | | |
| | | 92 | | /// <inheritdoc/> |
| | | 93 | | public async Task OnSaveChangesAsync(JellyfinDbContext context, Func<Task> saveChanges) |
| | | 94 | | { |
| | | 95 | | await _writeAsyncPolicy.ExecuteAndCaptureAsync(saveChanges).ConfigureAwait(false); |
| | | 96 | | } |
| | | 97 | | |
| | | 98 | | private sealed class TransactionLockingInterceptor : DbTransactionInterceptor |
| | | 99 | | { |
| | | 100 | | private readonly AsyncPolicy _asyncRetryPolicy; |
| | | 101 | | private readonly Policy _retryPolicy; |
| | | 102 | | |
| | 0 | 103 | | public TransactionLockingInterceptor(AsyncPolicy asyncRetryPolicy, Policy retryPolicy) |
| | | 104 | | { |
| | 0 | 105 | | _asyncRetryPolicy = asyncRetryPolicy; |
| | 0 | 106 | | _retryPolicy = retryPolicy; |
| | 0 | 107 | | } |
| | | 108 | | |
| | | 109 | | public override InterceptionResult<DbTransaction> TransactionStarting(DbConnection connection, TransactionStarti |
| | | 110 | | { |
| | 0 | 111 | | return InterceptionResult<DbTransaction>.SuppressWithResult(_retryPolicy.Execute(() => connection.BeginTrans |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | public override async ValueTask<InterceptionResult<DbTransaction>> TransactionStartingAsync(DbConnection connect |
| | | 115 | | { |
| | | 116 | | return InterceptionResult<DbTransaction>.SuppressWithResult(await _asyncRetryPolicy.ExecuteAsync(async () => |
| | | 117 | | } |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | private sealed class RetryInterceptor : DbCommandInterceptor |
| | | 121 | | { |
| | | 122 | | private readonly AsyncPolicy _asyncRetryPolicy; |
| | | 123 | | private readonly Policy _retryPolicy; |
| | | 124 | | |
| | 0 | 125 | | public RetryInterceptor(AsyncPolicy asyncRetryPolicy, Policy retryPolicy) |
| | | 126 | | { |
| | 0 | 127 | | _asyncRetryPolicy = asyncRetryPolicy; |
| | 0 | 128 | | _retryPolicy = retryPolicy; |
| | 0 | 129 | | } |
| | | 130 | | |
| | | 131 | | public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, Interce |
| | | 132 | | { |
| | 0 | 133 | | return InterceptionResult<int>.SuppressWithResult(_retryPolicy.Execute(command.ExecuteNonQuery)); |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | public override async ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventD |
| | | 137 | | { |
| | | 138 | | return InterceptionResult<int>.SuppressWithResult(await _asyncRetryPolicy.ExecuteAsync(async () => await com |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, Interc |
| | | 142 | | { |
| | 0 | 143 | | return InterceptionResult<object>.SuppressWithResult(_retryPolicy.Execute(() => command.ExecuteScalar()!)); |
| | | 144 | | } |
| | | 145 | | |
| | | 146 | | public override async ValueTask<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEvent |
| | | 147 | | { |
| | | 148 | | return InterceptionResult<object>.SuppressWithResult((await _asyncRetryPolicy.ExecuteAsync(async () => await |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, |
| | | 152 | | { |
| | 0 | 153 | | return InterceptionResult<DbDataReader>.SuppressWithResult(_retryPolicy.Execute(command.ExecuteReader)); |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, Comman |
| | | 157 | | { |
| | | 158 | | return InterceptionResult<DbDataReader>.SuppressWithResult(await _asyncRetryPolicy.ExecuteAsync(async () => |
| | | 159 | | } |
| | | 160 | | } |
| | | 161 | | } |