| | | 1 | | using System.Linq.Expressions; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | using ArturRios.Data.MongoDb.Exceptions; |
| | | 4 | | using ArturRios.Data.MongoDb.Interfaces; |
| | | 5 | | using ArturRios.Output; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | using MongoDB.Bson; |
| | | 8 | | using MongoDB.Bson.Serialization; |
| | | 9 | | using MongoDB.Driver; |
| | | 10 | | |
| | | 11 | | namespace ArturRios.Data.MongoDb.Repositories; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// MongoDB implementation of the document repository contracts. Runs against the |
| | | 15 | | /// <see cref="MongoContext" /> collection and enlists in its ambient session so operations |
| | | 16 | | /// participate in a unit-of-work transaction. Failures are returned as <see cref="DataOutput{T}" />. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <typeparam name="T">The document type.</typeparam> |
| | | 19 | | /// <param name="context">The Mongo context.</param> |
| | | 20 | | /// <param name="logger"> |
| | | 21 | | /// Optional logger. Envelopes never carry driver text, so a failure is otherwise |
| | | 22 | | /// undiagnosable: supply a logger and the full exception, plus the document type and the |
| | | 23 | | /// repository method that failed, is written at <see cref="LogLevel.Error" />. Document |
| | | 24 | | /// contents and key values are never logged. Resolved from DI when logging is registered. |
| | | 25 | | /// </param> |
| | 70 | 26 | | public class MongoDocumentRepository<T>(MongoContext context, ILogger<MongoDocumentRepository<T>>? logger = null) |
| | | 27 | | : IDocumentRepository<T>, IAsyncDocumentRepository<T> where T : Document |
| | | 28 | | { |
| | | 29 | | /// <summary>Message returned when an operation fails with no finer classification.</summary> |
| | | 30 | | protected const string OperationFailedMessage = MongoErrors.GenericMessage; |
| | | 31 | | |
| | | 32 | | /// <summary>Message returned when the failure is transient and the operation may be retried.</summary> |
| | | 33 | | protected const string TransientMessage = MongoErrors.TransientMessage; |
| | | 34 | | |
| | | 35 | | /// <summary>Message returned on an optimistic-concurrency conflict.</summary> |
| | | 36 | | protected const string ConcurrencyMessage = MongoErrors.ConcurrencyMessage; |
| | | 37 | | |
| | | 38 | | /// <summary>Message returned when a write violates a unique index.</summary> |
| | | 39 | | protected const string UniqueViolationMessage = MongoErrors.UniqueViolationMessage; |
| | | 40 | | |
| | | 41 | | // Cached: the serialized BSON element name for VersionedDocument.Version on T |
| | | 42 | | // (respects any element-name convention the consumer registered). |
| | 4 | 43 | | private static readonly string VersionElementName = |
| | 4 | 44 | | BsonClassMap.LookupClassMap(typeof(T)).AllMemberMaps |
| | 8 | 45 | | .FirstOrDefault(m => m.MemberName == nameof(VersionedDocument.Version))?.ElementName |
| | 4 | 46 | | ?? nameof(VersionedDocument.Version); |
| | | 47 | | |
| | | 48 | | /// <summary>The collection for <typeparamref name="T" />.</summary> |
| | 168 | 49 | | protected IMongoCollection<T> Collection => context.GetCollection<T>(); |
| | | 50 | | |
| | 166 | 51 | | private IClientSessionHandle? Session => context.Session; |
| | | 52 | | |
| | | 53 | | /// <inheritdoc /> |
| | | 54 | | public Task<DataOutput<IEnumerable<T>>> GetAllAsync(CancellationToken ct = default) => |
| | 24 | 55 | | GuardedAsync<IEnumerable<T>>(async () => await FindFluent(FilterDefinition<T>.Empty).ToListAsync(ct).ConfigureAw |
| | | 56 | | |
| | | 57 | | /// <inheritdoc /> |
| | | 58 | | public Task<DataOutput<T?>> GetByIdAsync(string id, CancellationToken ct = default) => |
| | 28 | 59 | | GuardedAsync<T?>(async () => IsObjectId(id) |
| | 28 | 60 | | ? await FindFluent(IdFilter(id)).FirstOrDefaultAsync(ct).ConfigureAwait(false) |
| | 28 | 61 | | : null); |
| | | 62 | | |
| | | 63 | | /// <inheritdoc /> |
| | | 64 | | public Task<DataOutput<IEnumerable<T>>> FindAsync(Expression<Func<T, bool>> predicate, |
| | | 65 | | CancellationToken ct = default) => |
| | 4 | 66 | | GuardedAsync<IEnumerable<T>>(async () => await FindFluent(Builders<T>.Filter.Where(predicate)).ToListAsync(ct).C |
| | | 67 | | |
| | | 68 | | /// <inheritdoc /> |
| | | 69 | | public Task<DataOutput<string>> CreateAsync(T document, CancellationToken ct = default) => |
| | 24 | 70 | | GuardedAsync(async () => |
| | 24 | 71 | | { |
| | 24 | 72 | | EnsureId(document); |
| | 24 | 73 | | await InsertOneAsync(document, ct).ConfigureAwait(false); |
| | 24 | 74 | | return document.Id; |
| | 48 | 75 | | }); |
| | | 76 | | |
| | | 77 | | /// <inheritdoc /> |
| | | 78 | | public Task<DataOutput<IEnumerable<string>>> CreateRangeAsync(IEnumerable<T> documents, |
| | | 79 | | CancellationToken ct = default) => |
| | 6 | 80 | | GuardedAsync<IEnumerable<string>>(async () => |
| | 6 | 81 | | { |
| | 6 | 82 | | var list = documents.ToList(); |
| | 28 | 83 | | foreach (var d in list) |
| | 6 | 84 | | { |
| | 8 | 85 | | EnsureId(d); |
| | 6 | 86 | | } |
| | 6 | 87 | | |
| | 6 | 88 | | if (list.Count > 0) |
| | 6 | 89 | | { |
| | 4 | 90 | | await InsertManyAsync(list, ct).ConfigureAwait(false); |
| | 6 | 91 | | } |
| | 6 | 92 | | |
| | 14 | 93 | | return list.Select(d => d.Id).ToList(); |
| | 12 | 94 | | }); |
| | | 95 | | |
| | | 96 | | /// <inheritdoc /> |
| | | 97 | | public Task<DataOutput<T>> UpdateAsync(T document, CancellationToken ct = default) => |
| | 10 | 98 | | GuardedAsync(async () => |
| | 10 | 99 | | { |
| | 10 | 100 | | await ReplaceAsync(document, ct).ConfigureAwait(false); |
| | 8 | 101 | | return document; |
| | 18 | 102 | | }); |
| | | 103 | | |
| | | 104 | | /// <inheritdoc /> |
| | | 105 | | public Task<DataOutput<IEnumerable<T>>> |
| | | 106 | | UpdateRangeAsync(IEnumerable<T> documents, CancellationToken ct = default) => |
| | 2 | 107 | | GuardedAsync<IEnumerable<T>>(async () => |
| | 2 | 108 | | { |
| | 2 | 109 | | var list = documents.ToList(); |
| | 10 | 110 | | foreach (var d in list) |
| | 2 | 111 | | { |
| | 4 | 112 | | await ReplaceAsync(d, ct).ConfigureAwait(false); |
| | 2 | 113 | | } |
| | 2 | 114 | | |
| | 0 | 115 | | return list; |
| | 2 | 116 | | }); |
| | | 117 | | |
| | | 118 | | /// <inheritdoc /> |
| | | 119 | | public Task<DataOutput<string>> DeleteAsync(T document, CancellationToken ct = default) => |
| | 6 | 120 | | GuardedAsync(async () => |
| | 6 | 121 | | { |
| | 6 | 122 | | await DeleteOneAsync(document, ct).ConfigureAwait(false); |
| | 4 | 123 | | return document.Id; |
| | 10 | 124 | | }); |
| | | 125 | | |
| | | 126 | | /// <inheritdoc /> |
| | | 127 | | public Task<DataOutput<IEnumerable<string>>> DeleteRangeAsync(IEnumerable<string> ids, |
| | | 128 | | CancellationToken ct = default) => |
| | 6 | 129 | | GuardedAsync<IEnumerable<string>>(async () => |
| | 6 | 130 | | { |
| | 6 | 131 | | var candidates = ExistingIdCandidates(ids); |
| | 6 | 132 | | if (candidates.Count == 0) |
| | 6 | 133 | | { |
| | 0 | 134 | | return []; |
| | 6 | 135 | | } |
| | 6 | 136 | | |
| | 6 | 137 | | var found = await FindFluent(Builders<T>.Filter.In(d => d.Id, candidates)).Project(d => d.Id) |
| | 6 | 138 | | .ToListAsync(ct).ConfigureAwait(false); |
| | 6 | 139 | | if (found.Count > 0) |
| | 6 | 140 | | { |
| | 4 | 141 | | await DeleteManyAsync(Builders<T>.Filter.In(d => d.Id, found), ct).ConfigureAwait(false); |
| | 6 | 142 | | } |
| | 6 | 143 | | |
| | 6 | 144 | | return InRequestOrder(candidates, found); |
| | 12 | 145 | | }); |
| | | 146 | | |
| | | 147 | | /// <inheritdoc /> |
| | 2 | 148 | | public IQueryable<T> Query() => Collection.AsQueryable(); |
| | | 149 | | |
| | | 150 | | /// <inheritdoc /> |
| | | 151 | | public DataOutput<IEnumerable<T>> GetAll() => |
| | 20 | 152 | | Guarded(IEnumerable<T> () => FindFluent(FilterDefinition<T>.Empty).ToList()); |
| | | 153 | | |
| | | 154 | | /// <inheritdoc /> |
| | | 155 | | public DataOutput<T?> GetById(string id) => |
| | 36 | 156 | | Guarded<T?>(() => IsObjectId(id) ? FindFluent(IdFilter(id)).FirstOrDefault() : null); |
| | | 157 | | |
| | | 158 | | /// <inheritdoc /> |
| | | 159 | | public DataOutput<IEnumerable<T>> Find(Expression<Func<T, bool>> predicate) => |
| | 4 | 160 | | Guarded(IEnumerable<T> () => FindFluent(Builders<T>.Filter.Where(predicate)).ToList()); |
| | | 161 | | |
| | | 162 | | /// <inheritdoc /> |
| | 24 | 163 | | public DataOutput<string> Create(T document) => Guarded(() => |
| | 24 | 164 | | { |
| | 24 | 165 | | EnsureId(document); |
| | 24 | 166 | | InsertOne(document); |
| | 20 | 167 | | return document.Id; |
| | 24 | 168 | | }); |
| | | 169 | | |
| | | 170 | | /// <inheritdoc /> |
| | 6 | 171 | | public DataOutput<IEnumerable<string>> CreateRange(IEnumerable<T> documents) => Guarded(IEnumerable<string> () => |
| | 6 | 172 | | { |
| | 6 | 173 | | var list = documents.ToList(); |
| | 28 | 174 | | foreach (var d in list) |
| | 6 | 175 | | { |
| | 8 | 176 | | EnsureId(d); |
| | 6 | 177 | | } |
| | 6 | 178 | | |
| | 6 | 179 | | if (list.Count > 0) |
| | 6 | 180 | | { |
| | 4 | 181 | | InsertMany(list); |
| | 6 | 182 | | } |
| | 6 | 183 | | |
| | 14 | 184 | | return list.Select(d => d.Id).ToList(); |
| | 6 | 185 | | }); |
| | | 186 | | |
| | | 187 | | /// <inheritdoc /> |
| | 14 | 188 | | public DataOutput<T> Update(T document) => Guarded(() => |
| | 14 | 189 | | { |
| | 14 | 190 | | Replace(document); |
| | 8 | 191 | | return document; |
| | 14 | 192 | | }); |
| | | 193 | | |
| | | 194 | | /// <inheritdoc /> |
| | 0 | 195 | | public DataOutput<IEnumerable<T>> UpdateRange(IEnumerable<T> documents) => Guarded(IEnumerable<T> () => |
| | 0 | 196 | | { |
| | 0 | 197 | | var list = documents.ToList(); |
| | 0 | 198 | | foreach (var d in list) |
| | 0 | 199 | | { |
| | 0 | 200 | | Replace(d); |
| | 0 | 201 | | } |
| | 0 | 202 | | |
| | 0 | 203 | | return list; |
| | 0 | 204 | | }); |
| | | 205 | | |
| | | 206 | | /// <inheritdoc /> |
| | 4 | 207 | | public DataOutput<string> Delete(T document) => Guarded(() => |
| | 4 | 208 | | { |
| | 4 | 209 | | DeleteOne(document); |
| | 2 | 210 | | return document.Id; |
| | 4 | 211 | | }); |
| | | 212 | | |
| | | 213 | | /// <inheritdoc /> |
| | 4 | 214 | | public DataOutput<IEnumerable<string>> DeleteRange(IEnumerable<string> ids) => Guarded(IEnumerable<string> () => |
| | 4 | 215 | | { |
| | 4 | 216 | | var candidates = ExistingIdCandidates(ids); |
| | 4 | 217 | | if (candidates.Count == 0) |
| | 4 | 218 | | { |
| | 0 | 219 | | return []; |
| | 4 | 220 | | } |
| | 4 | 221 | | |
| | 4 | 222 | | var found = FindFluent(Builders<T>.Filter.In(d => d.Id, candidates)).Project(d => d.Id).ToList(); |
| | 4 | 223 | | if (found.Count > 0) |
| | 4 | 224 | | { |
| | 4 | 225 | | DeleteMany(Builders<T>.Filter.In(d => d.Id, found)); |
| | 4 | 226 | | } |
| | 4 | 227 | | |
| | 4 | 228 | | return InRequestOrder(candidates, found); |
| | 4 | 229 | | }); |
| | | 230 | | |
| | | 231 | | // --- session-aware driver helpers (sync) --- |
| | 66 | 232 | | private static FilterDefinition<T> IdFilter(string id) => Builders<T>.Filter.Eq(d => d.Id, id); |
| | | 233 | | |
| | | 234 | | // Document.Id is stored as an ObjectId, so a string that is not one cannot match any document. It is |
| | | 235 | | // answered as not-found rather than sent to the server, where serializing the filter would fail. |
| | 54 | 236 | | private static bool IsObjectId(string? id) => ObjectId.TryParse(id, out _); |
| | | 237 | | |
| | | 238 | | private static List<string> ExistingIdCandidates(IEnumerable<string> ids) => |
| | 10 | 239 | | ids.Where(IsObjectId).Distinct().ToList(); |
| | | 240 | | |
| | | 241 | | private static List<string> InRequestOrder(List<string> requested, List<string> found) |
| | | 242 | | { |
| | 10 | 243 | | var deleted = found.ToHashSet(); |
| | 10 | 244 | | return requested.Where(deleted.Contains).ToList(); |
| | | 245 | | } |
| | | 246 | | |
| | | 247 | | // A versioned document is deleted only at the version the caller holds, as the relational and |
| | | 248 | | // DynamoDB repositories do; a stale delete is a concurrency conflict rather than a silent removal of |
| | | 249 | | // someone else's newer write. A plain document's delete stays idempotent. |
| | | 250 | | private static FilterDefinition<T> DeleteFilter(T document) => |
| | 10 | 251 | | document is VersionedDocument versioned |
| | 10 | 252 | | ? Builders<T>.Filter.And(IdFilter(document.Id), |
| | 10 | 253 | | Builders<T>.Filter.Eq(VersionElementName, versioned.Version)) |
| | 10 | 254 | | : IdFilter(document.Id); |
| | | 255 | | |
| | | 256 | | private static void EnsureDeleted(T document, DeleteResult result) |
| | | 257 | | { |
| | 10 | 258 | | if (document is VersionedDocument && result.IsAcknowledged && result.DeletedCount == 0) |
| | | 259 | | { |
| | 4 | 260 | | throw new MongoConcurrencyException(); |
| | | 261 | | } |
| | 6 | 262 | | } |
| | | 263 | | |
| | | 264 | | private void DeleteOne(T document) |
| | | 265 | | { |
| | 4 | 266 | | var filter = DeleteFilter(document); |
| | 4 | 267 | | EnsureDeleted(document, Session is { } s ? Collection.DeleteOne(s, filter) : Collection.DeleteOne(filter)); |
| | 2 | 268 | | } |
| | | 269 | | |
| | | 270 | | private static void EnsureId(T document) |
| | | 271 | | { |
| | 64 | 272 | | if (string.IsNullOrEmpty(document.Id)) |
| | | 273 | | { |
| | 56 | 274 | | document.Id = ObjectId.GenerateNewId().ToString(); |
| | | 275 | | } |
| | 64 | 276 | | } |
| | | 277 | | |
| | | 278 | | private IFindFluent<T, T> FindFluent(FilterDefinition<T> filter) => |
| | 64 | 279 | | Session is { } s ? Collection.Find(s, filter) : Collection.Find(filter); |
| | | 280 | | |
| | | 281 | | private void InsertOne(T document) |
| | | 282 | | { |
| | 24 | 283 | | if (Session is { } s) |
| | | 284 | | { |
| | 0 | 285 | | Collection.InsertOne(s, document); |
| | | 286 | | } |
| | | 287 | | else |
| | | 288 | | { |
| | 24 | 289 | | Collection.InsertOne(document); |
| | | 290 | | } |
| | 20 | 291 | | } |
| | | 292 | | |
| | | 293 | | private void InsertMany(IEnumerable<T> documents) |
| | | 294 | | { |
| | 4 | 295 | | if (Session is { } s) |
| | | 296 | | { |
| | 0 | 297 | | Collection.InsertMany(s, documents); |
| | | 298 | | } |
| | | 299 | | else |
| | | 300 | | { |
| | 4 | 301 | | Collection.InsertMany(documents); |
| | | 302 | | } |
| | 4 | 303 | | } |
| | | 304 | | |
| | | 305 | | private void DeleteMany(FilterDefinition<T> filter) |
| | | 306 | | { |
| | 4 | 307 | | if (Session is { } s) |
| | | 308 | | { |
| | 0 | 309 | | Collection.DeleteMany(s, filter); |
| | | 310 | | } |
| | | 311 | | else |
| | | 312 | | { |
| | 4 | 313 | | Collection.DeleteMany(filter); |
| | | 314 | | } |
| | 4 | 315 | | } |
| | | 316 | | |
| | | 317 | | // Replace with optimistic-concurrency handling for VersionedDocument. |
| | | 318 | | private void Replace(T document) |
| | | 319 | | { |
| | 14 | 320 | | if (document is VersionedDocument versioned) |
| | | 321 | | { |
| | 10 | 322 | | var expected = versioned.Version; |
| | 10 | 323 | | versioned.Version = expected + 1; |
| | 10 | 324 | | var filter = Builders<T>.Filter.And(IdFilter(document.Id), |
| | 10 | 325 | | Builders<T>.Filter.Eq(VersionElementName, expected)); |
| | | 326 | | |
| | | 327 | | ReplaceOneResult result; |
| | | 328 | | try |
| | | 329 | | { |
| | 10 | 330 | | result = ReplaceOne(filter, document); |
| | 10 | 331 | | } |
| | 0 | 332 | | catch |
| | | 333 | | { |
| | | 334 | | // The write never landed, so the in-memory bump must not survive: keeping it would |
| | | 335 | | // make every retry filter on a version the server never stored. |
| | 0 | 336 | | versioned.Version = expected; |
| | 0 | 337 | | throw; |
| | | 338 | | } |
| | | 339 | | |
| | 10 | 340 | | if (result.MatchedCount == 0) |
| | | 341 | | { |
| | 4 | 342 | | versioned.Version = expected; // roll back the in-memory bump on a failed (stale) update |
| | 4 | 343 | | throw new MongoConcurrencyException(); |
| | | 344 | | } |
| | | 345 | | |
| | 6 | 346 | | return; |
| | | 347 | | } |
| | | 348 | | |
| | 4 | 349 | | EnsureMatched(ReplaceOne(IdFilter(document.Id), document)); |
| | 2 | 350 | | } |
| | | 351 | | |
| | | 352 | | // Update replaces an existing document. One that matched nothing was removed by another process (or |
| | | 353 | | // never existed), which the relational repository reports as a concurrency conflict too - so this one |
| | | 354 | | // does, instead of reporting a write that never happened as a success. |
| | | 355 | | private static void EnsureMatched(ReplaceOneResult result) |
| | | 356 | | { |
| | 14 | 357 | | if (result.IsAcknowledged && result.MatchedCount == 0) |
| | | 358 | | { |
| | 6 | 359 | | throw new MongoConcurrencyException(); |
| | | 360 | | } |
| | 8 | 361 | | } |
| | | 362 | | |
| | | 363 | | private ReplaceOneResult ReplaceOne(FilterDefinition<T> filter, T document) => |
| | 14 | 364 | | Session is { } s ? Collection.ReplaceOne(s, filter, document) : Collection.ReplaceOne(filter, document); |
| | | 365 | | |
| | | 366 | | /// <summary>Runs a synchronous operation, converting failures to envelope errors.</summary> |
| | | 367 | | /// <param name="operation">The operation to run.</param> |
| | | 368 | | /// <param name="operationName">The calling repository method, used as log context.</param> |
| | | 369 | | protected DataOutput<TResult> Guarded<TResult>(Func<TResult> operation, |
| | | 370 | | [CallerMemberName] string operationName = "") |
| | | 371 | | { |
| | | 372 | | try |
| | | 373 | | { |
| | 82 | 374 | | return DataOutput<TResult>.New.WithData(operation()); |
| | | 375 | | } |
| | 0 | 376 | | catch (OperationCanceledException) |
| | | 377 | | { |
| | 0 | 378 | | throw; |
| | | 379 | | } |
| | 12 | 380 | | catch (Exception ex) |
| | | 381 | | { |
| | 12 | 382 | | return Fail<TResult>(ex, operationName); |
| | | 383 | | } |
| | 82 | 384 | | } |
| | | 385 | | |
| | | 386 | | // --- session-aware driver helpers (async) --- |
| | | 387 | | private Task InsertOneAsync(T document, CancellationToken ct) => |
| | 24 | 388 | | Session is { } s |
| | 24 | 389 | | ? Collection.InsertOneAsync(s, document, null, ct) |
| | 24 | 390 | | : Collection.InsertOneAsync(document, null, ct); |
| | | 391 | | |
| | | 392 | | private Task InsertManyAsync(IEnumerable<T> documents, CancellationToken ct) => |
| | 4 | 393 | | Session is { } s |
| | 4 | 394 | | ? Collection.InsertManyAsync(s, documents, null, ct) |
| | 4 | 395 | | : Collection.InsertManyAsync(documents, null, ct); |
| | | 396 | | |
| | | 397 | | private Task DeleteManyAsync(FilterDefinition<T> filter, CancellationToken ct) => |
| | 4 | 398 | | Session is { } s ? Collection.DeleteManyAsync(s, filter, null, ct) : Collection.DeleteManyAsync(filter, ct); |
| | | 399 | | |
| | | 400 | | private async Task DeleteOneAsync(T document, CancellationToken ct) |
| | | 401 | | { |
| | 6 | 402 | | var filter = DeleteFilter(document); |
| | 6 | 403 | | EnsureDeleted(document, Session is { } s |
| | 6 | 404 | | ? await Collection.DeleteOneAsync(s, filter, null, ct).ConfigureAwait(false) |
| | 6 | 405 | | : await Collection.DeleteOneAsync(filter, ct).ConfigureAwait(false)); |
| | 4 | 406 | | } |
| | | 407 | | |
| | | 408 | | private async Task ReplaceAsync(T document, CancellationToken ct) |
| | | 409 | | { |
| | 14 | 410 | | if (document is VersionedDocument versioned) |
| | | 411 | | { |
| | 4 | 412 | | var expected = versioned.Version; |
| | 4 | 413 | | versioned.Version = expected + 1; |
| | 4 | 414 | | var filter = Builders<T>.Filter.And(IdFilter(document.Id), |
| | 4 | 415 | | Builders<T>.Filter.Eq(VersionElementName, expected)); |
| | | 416 | | ReplaceOneResult result; |
| | | 417 | | try |
| | | 418 | | { |
| | 4 | 419 | | result = Session is { } s |
| | 4 | 420 | | ? await Collection.ReplaceOneAsync(s, filter, document, cancellationToken: ct).ConfigureAwait(false) |
| | 4 | 421 | | : await Collection.ReplaceOneAsync(filter, document, cancellationToken: ct).ConfigureAwait(false); |
| | 4 | 422 | | } |
| | 0 | 423 | | catch |
| | | 424 | | { |
| | | 425 | | // The write never landed, so the in-memory bump must not survive: keeping it would |
| | | 426 | | // make every retry filter on a version the server never stored. |
| | 0 | 427 | | versioned.Version = expected; |
| | 0 | 428 | | throw; |
| | | 429 | | } |
| | | 430 | | |
| | 4 | 431 | | if (result.MatchedCount == 0) |
| | | 432 | | { |
| | 0 | 433 | | versioned.Version = expected; // roll back the in-memory bump on a failed (stale) update |
| | 0 | 434 | | throw new MongoConcurrencyException(); |
| | | 435 | | } |
| | | 436 | | |
| | 4 | 437 | | return; |
| | | 438 | | } |
| | | 439 | | |
| | 10 | 440 | | var idFilter = IdFilter(document.Id); |
| | 10 | 441 | | var replaced = Session is { } session |
| | 10 | 442 | | ? await Collection.ReplaceOneAsync(session, idFilter, document, cancellationToken: ct).ConfigureAwait(false) |
| | 10 | 443 | | : await Collection.ReplaceOneAsync(idFilter, document, cancellationToken: ct).ConfigureAwait(false); |
| | | 444 | | |
| | 10 | 445 | | EnsureMatched(replaced); |
| | 10 | 446 | | } |
| | | 447 | | |
| | | 448 | | /// <summary>Runs an asynchronous operation, converting failures to envelope errors.</summary> |
| | | 449 | | /// <param name="operation">The operation to run.</param> |
| | | 450 | | /// <param name="operationName">The calling repository method, used as log context.</param> |
| | | 451 | | protected async Task<DataOutput<TResult>> GuardedAsync<TResult>(Func<Task<TResult>> operation, |
| | | 452 | | [CallerMemberName] string operationName = "") |
| | | 453 | | { |
| | | 454 | | try |
| | | 455 | | { |
| | 82 | 456 | | return DataOutput<TResult>.New.WithData(await operation().ConfigureAwait(false)); |
| | | 457 | | } |
| | 0 | 458 | | catch (OperationCanceledException) |
| | | 459 | | { |
| | 0 | 460 | | throw; |
| | | 461 | | } |
| | 6 | 462 | | catch (Exception ex) |
| | | 463 | | { |
| | 6 | 464 | | return Fail<TResult>(ex, operationName); |
| | | 465 | | } |
| | 82 | 466 | | } |
| | | 467 | | |
| | | 468 | | /// <summary> |
| | | 469 | | /// Logs the failure when a logger is configured, and maps it to an error envelope. |
| | | 470 | | /// Driver text names indexes, collections, key values and cluster endpoints, so it goes to |
| | | 471 | | /// the log and never to the caller. |
| | | 472 | | /// </summary> |
| | | 473 | | /// <param name="ex">The exception caught by a guard.</param> |
| | | 474 | | /// <param name="operationName">The repository method that failed, used as log context.</param> |
| | | 475 | | protected DataOutput<TResult> Fail<TResult>(Exception ex, string operationName = "") |
| | | 476 | | { |
| | | 477 | | // A concurrency conflict is an expected outcome of optimistic locking, not an operational |
| | | 478 | | // fault: logging it at Error would fill the log with routine contention. |
| | 18 | 479 | | var level = ex is MongoConcurrencyException ? LogLevel.Debug : LogLevel.Error; |
| | | 480 | | |
| | 18 | 481 | | logger?.Log(level, ex, "Mongo operation failed. Document: {Document}, operation: {Operation}", |
| | 18 | 482 | | typeof(T).Name, operationName); |
| | | 483 | | |
| | 18 | 484 | | return DataOutput<TResult>.New.WithError(MongoErrors.Describe(ex)); |
| | | 485 | | } |
| | | 486 | | } |