| | | 1 | | using ArturRios.Data.MongoDb.Repositories; |
| | | 2 | | using ArturRios.Output; |
| | | 3 | | using MongoDB.Driver; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Data.MongoDb.Transactions; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// MongoDB implementation of the unit of work. Opens a client session, sets it as the context's |
| | | 9 | | /// ambient session so repository operations enlist, and commits/aborts the transaction. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <param name="client">The Mongo client.</param> |
| | | 12 | | /// <param name="context">The Mongo context whose ambient session is managed.</param> |
| | 36 | 13 | | public class MongoUnitOfWork(IMongoClient client, MongoContext context) : IMongoUnitOfWork, IAsyncMongoUnitOfWork |
| | | 14 | | { |
| | | 15 | | /// <inheritdoc /> |
| | | 16 | | public Task<ProcessOutput> ExecuteInTransactionAsync(Func<Task> work, CancellationToken ct = default) => |
| | 14 | 17 | | RunAsync(async () => |
| | 14 | 18 | | { |
| | 10 | 19 | | await work().ConfigureAwait(false); |
| | 6 | 20 | | return ProcessOutput.New; |
| | 28 | 21 | | }, error => ProcessOutput.New.WithError(error), ct); |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | | 24 | | public Task<DataOutput<TResult>> ExecuteInTransactionAsync<TResult>(Func<Task<TResult>> work, |
| | | 25 | | CancellationToken ct = default) => |
| | 10 | 26 | | RunAsync(async () => DataOutput<TResult>.New.WithData(await work().ConfigureAwait(false)), |
| | 14 | 27 | | error => DataOutput<TResult>.New.WithError(error), ct); |
| | | 28 | | |
| | | 29 | | /// <inheritdoc /> |
| | | 30 | | public ProcessOutput ExecuteInTransaction(Action work) => |
| | 4 | 31 | | Run(() => |
| | 4 | 32 | | { |
| | 0 | 33 | | work(); |
| | 0 | 34 | | return ProcessOutput.New; |
| | 8 | 35 | | }, error => ProcessOutput.New.WithError(error)); |
| | | 36 | | |
| | | 37 | | /// <inheritdoc /> |
| | | 38 | | public DataOutput<TResult> ExecuteInTransaction<TResult>(Func<TResult> work) => |
| | 12 | 39 | | Run(() => DataOutput<TResult>.New.WithData(work()), error => DataOutput<TResult>.New.WithError(error)); |
| | | 40 | | |
| | | 41 | | // Every step that can fail — opening the session, starting the transaction (which throws on a standalone |
| | | 42 | | // server), the work and the commit — runs inside the guard, so a failure is enveloped like any other and |
| | | 43 | | // the finally always restores the caller's ambient session before the session is disposed. The session is |
| | | 44 | | // made ambient only once its transaction has started. |
| | | 45 | | private async Task<TOutput> RunAsync<TOutput>(Func<Task<TOutput>> work, Func<string, TOutput> fail, |
| | | 46 | | CancellationToken ct) |
| | | 47 | | { |
| | 22 | 48 | | var previousSession = context.Session; |
| | 22 | 49 | | IClientSessionHandle? session = null; |
| | | 50 | | try |
| | | 51 | | { |
| | 22 | 52 | | session = await client.StartSessionAsync(cancellationToken: ct).ConfigureAwait(false); |
| | 22 | 53 | | session.StartTransaction(); |
| | 12 | 54 | | context.Session = session; |
| | 12 | 55 | | var output = await work().ConfigureAwait(false); |
| | 8 | 56 | | await session.CommitTransactionAsync(ct).ConfigureAwait(false); |
| | 8 | 57 | | return output; |
| | | 58 | | } |
| | 14 | 59 | | catch (Exception ex) |
| | | 60 | | { |
| | 14 | 61 | | if (session is not null) |
| | | 62 | | { |
| | 14 | 63 | | await AbortQuietlyAsync(session).ConfigureAwait(false); |
| | | 64 | | } |
| | | 65 | | |
| | 14 | 66 | | if (ex is OperationCanceledException) |
| | | 67 | | { |
| | 0 | 68 | | throw; |
| | | 69 | | } |
| | | 70 | | |
| | 14 | 71 | | return fail(MongoErrors.Describe(ex)); |
| | | 72 | | } |
| | | 73 | | finally |
| | | 74 | | { |
| | 22 | 75 | | context.Session = previousSession; |
| | 22 | 76 | | session?.Dispose(); |
| | | 77 | | } |
| | 22 | 78 | | } |
| | | 79 | | |
| | | 80 | | private TOutput Run<TOutput>(Func<TOutput> work, Func<string, TOutput> fail) |
| | | 81 | | { |
| | 10 | 82 | | var previousSession = context.Session; |
| | 10 | 83 | | IClientSessionHandle? session = null; |
| | | 84 | | try |
| | | 85 | | { |
| | 10 | 86 | | session = client.StartSession(); |
| | 10 | 87 | | session.StartTransaction(); |
| | 0 | 88 | | context.Session = session; |
| | 0 | 89 | | var output = work(); |
| | 0 | 90 | | session.CommitTransaction(); |
| | 0 | 91 | | return output; |
| | | 92 | | } |
| | 10 | 93 | | catch (Exception ex) |
| | | 94 | | { |
| | 10 | 95 | | if (session is not null) |
| | | 96 | | { |
| | 10 | 97 | | AbortQuietly(session); |
| | | 98 | | } |
| | | 99 | | |
| | 10 | 100 | | if (ex is OperationCanceledException) |
| | | 101 | | { |
| | 0 | 102 | | throw; |
| | | 103 | | } |
| | | 104 | | |
| | 10 | 105 | | return fail(MongoErrors.Describe(ex)); |
| | | 106 | | } |
| | | 107 | | finally |
| | | 108 | | { |
| | 10 | 109 | | context.Session = previousSession; |
| | 10 | 110 | | session?.Dispose(); |
| | 10 | 111 | | } |
| | 10 | 112 | | } |
| | | 113 | | |
| | | 114 | | // Abort must never mask the failure that triggered it: the server aborts the transaction itself |
| | | 115 | | // on a write conflict, so an explicit abort can fail on a transaction that is already gone. It |
| | | 116 | | // also runs untied to the caller's token, which may already be canceled. |
| | | 117 | | private static async Task AbortQuietlyAsync(IClientSessionHandle session) |
| | | 118 | | { |
| | | 119 | | try |
| | | 120 | | { |
| | 14 | 121 | | await session.AbortTransactionAsync(CancellationToken.None).ConfigureAwait(false); |
| | 4 | 122 | | } |
| | 10 | 123 | | catch |
| | | 124 | | { |
| | | 125 | | // Never started, already aborted, or the session is gone. Disposing the session completes the cleanup. |
| | 10 | 126 | | } |
| | 14 | 127 | | } |
| | | 128 | | |
| | | 129 | | private static void AbortQuietly(IClientSessionHandle session) |
| | | 130 | | { |
| | | 131 | | try |
| | | 132 | | { |
| | 10 | 133 | | session.AbortTransaction(); |
| | 0 | 134 | | } |
| | 10 | 135 | | catch |
| | | 136 | | { |
| | | 137 | | // Never started, already aborted, or the session is gone. Disposing the session completes the cleanup. |
| | 10 | 138 | | } |
| | 10 | 139 | | } |
| | | 140 | | } |