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