| | | 1 | | using System.Linq.Expressions; |
| | | 2 | | using ArturRios.Data.MongoDb.Exceptions; |
| | | 3 | | using ArturRios.Data.MongoDb.Interfaces; |
| | | 4 | | using ArturRios.Output; |
| | | 5 | | using MongoDB.Bson; |
| | | 6 | | using MongoDB.Bson.Serialization; |
| | | 7 | | using MongoDB.Driver; |
| | | 8 | | |
| | | 9 | | namespace ArturRios.Data.MongoDb.Repositories; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// MongoDB implementation of the document repository contracts. Runs against the |
| | | 13 | | /// <see cref="MongoContext" /> collection and enlists in its ambient session so operations |
| | | 14 | | /// participate in a unit-of-work transaction. Failures are returned as <see cref="DataOutput{T}" />. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <typeparam name="T">The document type.</typeparam> |
| | | 17 | | /// <param name="context">The Mongo context.</param> |
| | 17 | 18 | | public class MongoDocumentRepository<T>(MongoContext context) |
| | | 19 | | : IDocumentRepository<T>, IAsyncDocumentRepository<T> where T : Document |
| | | 20 | | { |
| | | 21 | | /// <summary>Message prefix returned when an operation fails.</summary> |
| | | 22 | | protected const string OperationFailedMessage = "A data-access error occurred:"; |
| | | 23 | | |
| | | 24 | | /// <summary>Message returned on an optimistic-concurrency conflict.</summary> |
| | | 25 | | protected const string ConcurrencyMessage = |
| | | 26 | | "Concurrency conflict: the document was modified or removed by another process."; |
| | | 27 | | |
| | | 28 | | // Cached: the serialized BSON element name for VersionedDocument.Version on T |
| | | 29 | | // (respects any element-name convention the consumer registered). |
| | 2 | 30 | | private static readonly string VersionElementName = |
| | 2 | 31 | | BsonClassMap.LookupClassMap(typeof(T)).AllMemberMaps |
| | 4 | 32 | | .FirstOrDefault(m => m.MemberName == nameof(VersionedDocument.Version))?.ElementName |
| | 2 | 33 | | ?? nameof(VersionedDocument.Version); |
| | | 34 | | |
| | | 35 | | /// <summary>The collection for <typeparamref name="T" />.</summary> |
| | 46 | 36 | | protected IMongoCollection<T> Collection => context.GetCollection<T>(); |
| | | 37 | | |
| | 45 | 38 | | private IClientSessionHandle? Session => context.Session; |
| | | 39 | | |
| | | 40 | | /// <inheritdoc /> |
| | | 41 | | public Task<DataOutput<IEnumerable<T>>> GetAllAsync(CancellationToken ct = default) => |
| | 6 | 42 | | GuardedAsync<IEnumerable<T>>(async () => await FindFluent(FilterDefinition<T>.Empty).ToListAsync(ct)); |
| | | 43 | | |
| | | 44 | | /// <inheritdoc /> |
| | | 45 | | public Task<DataOutput<T?>> GetByIdAsync(string id, CancellationToken ct = default) => |
| | 6 | 46 | | GuardedAsync<T?>(async () => await FindFluent(IdFilter(id)).FirstOrDefaultAsync(ct)); |
| | | 47 | | |
| | | 48 | | /// <inheritdoc /> |
| | | 49 | | public Task<DataOutput<IEnumerable<T>>> FindAsync(Expression<Func<T, bool>> predicate, |
| | | 50 | | CancellationToken ct = default) => |
| | 2 | 51 | | GuardedAsync<IEnumerable<T>>(async () => await FindFluent(Builders<T>.Filter.Where(predicate)).ToListAsync(ct)); |
| | | 52 | | |
| | | 53 | | /// <inheritdoc /> |
| | | 54 | | public Task<DataOutput<string>> CreateAsync(T document, CancellationToken ct = default) => |
| | 6 | 55 | | GuardedAsync(async () => |
| | 6 | 56 | | { |
| | 6 | 57 | | EnsureId(document); |
| | 6 | 58 | | await InsertOneAsync(document, ct); |
| | 6 | 59 | | return document.Id; |
| | 12 | 60 | | }); |
| | | 61 | | |
| | | 62 | | /// <inheritdoc /> |
| | | 63 | | public Task<DataOutput<IEnumerable<string>>> CreateRangeAsync(IEnumerable<T> documents, |
| | | 64 | | CancellationToken ct = default) => |
| | 2 | 65 | | GuardedAsync<IEnumerable<string>>(async () => |
| | 2 | 66 | | { |
| | 2 | 67 | | var list = documents.ToList(); |
| | 14 | 68 | | foreach (var d in list) |
| | 4 | 69 | | { |
| | 4 | 70 | | EnsureId(d); |
| | 4 | 71 | | } |
| | 2 | 72 | | |
| | 2 | 73 | | await InsertManyAsync(list, ct); |
| | 6 | 74 | | return list.Select(d => d.Id).ToList(); |
| | 4 | 75 | | }); |
| | | 76 | | |
| | | 77 | | /// <inheritdoc /> |
| | | 78 | | public Task<DataOutput<T>> UpdateAsync(T document, CancellationToken ct = default) => |
| | 1 | 79 | | GuardedAsync(async () => |
| | 1 | 80 | | { |
| | 1 | 81 | | await ReplaceAsync(document, ct); |
| | 1 | 82 | | return document; |
| | 2 | 83 | | }); |
| | | 84 | | |
| | | 85 | | /// <inheritdoc /> |
| | | 86 | | public Task<DataOutput<IEnumerable<T>>> |
| | | 87 | | UpdateRangeAsync(IEnumerable<T> documents, CancellationToken ct = default) => |
| | 0 | 88 | | GuardedAsync<IEnumerable<T>>(async () => |
| | 0 | 89 | | { |
| | 0 | 90 | | var list = documents.ToList(); |
| | 0 | 91 | | foreach (var d in list) |
| | 0 | 92 | | { |
| | 0 | 93 | | await ReplaceAsync(d, ct); |
| | 0 | 94 | | } |
| | 0 | 95 | | |
| | 0 | 96 | | return list; |
| | 0 | 97 | | }); |
| | | 98 | | |
| | | 99 | | /// <inheritdoc /> |
| | | 100 | | public Task<DataOutput<string>> DeleteAsync(T document, CancellationToken ct = default) => |
| | 1 | 101 | | GuardedAsync(async () => |
| | 1 | 102 | | { |
| | 1 | 103 | | await DeleteManyAsync(IdFilter(document.Id), ct); |
| | 1 | 104 | | return document.Id; |
| | 2 | 105 | | }); |
| | | 106 | | |
| | | 107 | | /// <inheritdoc /> |
| | | 108 | | public Task<DataOutput<IEnumerable<string>>> DeleteRangeAsync(IEnumerable<string> ids, |
| | | 109 | | CancellationToken ct = default) => |
| | 1 | 110 | | GuardedAsync<IEnumerable<string>>(async () => |
| | 1 | 111 | | { |
| | 1 | 112 | | var idList = ids.ToList(); |
| | 1 | 113 | | await DeleteManyAsync(Builders<T>.Filter.In(d => d.Id, idList), ct); |
| | 1 | 114 | | return idList; |
| | 2 | 115 | | }); |
| | | 116 | | |
| | | 117 | | /// <inheritdoc /> |
| | 1 | 118 | | public IQueryable<T> Query() => Collection.AsQueryable(); |
| | | 119 | | |
| | | 120 | | /// <inheritdoc /> |
| | | 121 | | public DataOutput<IEnumerable<T>> GetAll() => |
| | 8 | 122 | | Guarded(IEnumerable<T> () => FindFluent(FilterDefinition<T>.Empty).ToList()); |
| | | 123 | | |
| | | 124 | | /// <inheritdoc /> |
| | | 125 | | public DataOutput<T?> GetById(string id) => |
| | 12 | 126 | | Guarded<T?>(() => FindFluent(IdFilter(id)).FirstOrDefault()); |
| | | 127 | | |
| | | 128 | | /// <inheritdoc /> |
| | | 129 | | public DataOutput<IEnumerable<T>> Find(Expression<Func<T, bool>> predicate) => |
| | 2 | 130 | | Guarded(IEnumerable<T> () => FindFluent(Builders<T>.Filter.Where(predicate)).ToList()); |
| | | 131 | | |
| | | 132 | | /// <inheritdoc /> |
| | 7 | 133 | | public DataOutput<string> Create(T document) => Guarded(() => |
| | 7 | 134 | | { |
| | 7 | 135 | | EnsureId(document); |
| | 7 | 136 | | InsertOne(document); |
| | 6 | 137 | | return document.Id; |
| | 13 | 138 | | }); |
| | | 139 | | |
| | | 140 | | /// <inheritdoc /> |
| | 2 | 141 | | public DataOutput<IEnumerable<string>> CreateRange(IEnumerable<T> documents) => Guarded(IEnumerable<string> () => |
| | 2 | 142 | | { |
| | 2 | 143 | | var list = documents.ToList(); |
| | 14 | 144 | | foreach (var d in list) |
| | 4 | 145 | | { |
| | 4 | 146 | | EnsureId(d); |
| | 4 | 147 | | } |
| | 2 | 148 | | |
| | 2 | 149 | | InsertMany(list); |
| | 6 | 150 | | return list.Select(d => d.Id).ToList(); |
| | 4 | 151 | | }); |
| | | 152 | | |
| | | 153 | | /// <inheritdoc /> |
| | 5 | 154 | | public DataOutput<T> Update(T document) => Guarded(() => |
| | 5 | 155 | | { |
| | 5 | 156 | | Replace(document); |
| | 3 | 157 | | return document; |
| | 8 | 158 | | }); |
| | | 159 | | |
| | | 160 | | /// <inheritdoc /> |
| | 0 | 161 | | public DataOutput<IEnumerable<T>> UpdateRange(IEnumerable<T> documents) => Guarded(IEnumerable<T> () => |
| | 0 | 162 | | { |
| | 0 | 163 | | var list = documents.ToList(); |
| | 0 | 164 | | foreach (var d in list) |
| | 0 | 165 | | { |
| | 0 | 166 | | Replace(d); |
| | 0 | 167 | | } |
| | 0 | 168 | | |
| | 0 | 169 | | return list; |
| | 0 | 170 | | }); |
| | | 171 | | |
| | | 172 | | /// <inheritdoc /> |
| | 1 | 173 | | public DataOutput<string> Delete(T document) => Guarded(() => |
| | 1 | 174 | | { |
| | 1 | 175 | | DeleteMany(IdFilter(document.Id)); |
| | 1 | 176 | | return document.Id; |
| | 2 | 177 | | }); |
| | | 178 | | |
| | | 179 | | /// <inheritdoc /> |
| | 1 | 180 | | public DataOutput<IEnumerable<string>> DeleteRange(IEnumerable<string> ids) => Guarded(IEnumerable<string> () => |
| | 1 | 181 | | { |
| | 1 | 182 | | var idList = ids.ToList(); |
| | 1 | 183 | | DeleteMany(Builders<T>.Filter.In(d => d.Id, idList)); |
| | 1 | 184 | | return idList; |
| | 2 | 185 | | }); |
| | | 186 | | |
| | | 187 | | // --- session-aware driver helpers (sync) --- |
| | 17 | 188 | | private static FilterDefinition<T> IdFilter(string id) => Builders<T>.Filter.Eq(d => d.Id, id); |
| | | 189 | | |
| | | 190 | | private static void EnsureId(T document) |
| | 21 | 191 | | { |
| | 21 | 192 | | if (string.IsNullOrEmpty(document.Id)) |
| | 19 | 193 | | { |
| | 19 | 194 | | document.Id = ObjectId.GenerateNewId().ToString(); |
| | 19 | 195 | | } |
| | 21 | 196 | | } |
| | | 197 | | |
| | | 198 | | private IFindFluent<T, T> FindFluent(FilterDefinition<T> filter) => |
| | 18 | 199 | | Session is { } s ? Collection.Find(s, filter) : Collection.Find(filter); |
| | | 200 | | |
| | | 201 | | private void InsertOne(T document) |
| | 7 | 202 | | { |
| | 7 | 203 | | if (Session is { } s) |
| | 0 | 204 | | { |
| | 0 | 205 | | Collection.InsertOne(s, document); |
| | 0 | 206 | | } |
| | | 207 | | else |
| | 7 | 208 | | { |
| | 7 | 209 | | Collection.InsertOne(document); |
| | 6 | 210 | | } |
| | 6 | 211 | | } |
| | | 212 | | |
| | | 213 | | private void InsertMany(IEnumerable<T> documents) |
| | 2 | 214 | | { |
| | 2 | 215 | | if (Session is { } s) |
| | 0 | 216 | | { |
| | 0 | 217 | | Collection.InsertMany(s, documents); |
| | 0 | 218 | | } |
| | | 219 | | else |
| | 2 | 220 | | { |
| | 2 | 221 | | Collection.InsertMany(documents); |
| | 2 | 222 | | } |
| | 2 | 223 | | } |
| | | 224 | | |
| | | 225 | | private void DeleteMany(FilterDefinition<T> filter) |
| | 2 | 226 | | { |
| | 2 | 227 | | if (Session is { } s) |
| | 0 | 228 | | { |
| | 0 | 229 | | Collection.DeleteMany(s, filter); |
| | 0 | 230 | | } |
| | | 231 | | else |
| | 2 | 232 | | { |
| | 2 | 233 | | Collection.DeleteMany(filter); |
| | 2 | 234 | | } |
| | 2 | 235 | | } |
| | | 236 | | |
| | | 237 | | // Replace with optimistic-concurrency handling for VersionedDocument. |
| | | 238 | | private void Replace(T document) |
| | 5 | 239 | | { |
| | 5 | 240 | | if (document is VersionedDocument versioned) |
| | 4 | 241 | | { |
| | 4 | 242 | | var expected = versioned.Version; |
| | 4 | 243 | | versioned.Version = expected + 1; |
| | 4 | 244 | | var filter = Builders<T>.Filter.And(IdFilter(document.Id), |
| | 4 | 245 | | Builders<T>.Filter.Eq(VersionElementName, expected)); |
| | 4 | 246 | | var result = ReplaceOne(filter, document); |
| | 4 | 247 | | if (result.MatchedCount == 0) |
| | 2 | 248 | | { |
| | 2 | 249 | | versioned.Version = expected; // roll back the in-memory bump on a failed (stale) update |
| | 2 | 250 | | throw new MongoConcurrencyException(); |
| | | 251 | | } |
| | | 252 | | |
| | 0 | 253 | | return; |
| | | 254 | | } |
| | | 255 | | |
| | 1 | 256 | | ReplaceOne(IdFilter(document.Id), document); |
| | 3 | 257 | | } |
| | | 258 | | |
| | | 259 | | private ReplaceOneResult ReplaceOne(FilterDefinition<T> filter, T document) => |
| | 5 | 260 | | Session is { } s ? Collection.ReplaceOne(s, filter, document) : Collection.ReplaceOne(filter, document); |
| | | 261 | | |
| | | 262 | | /// <summary>Runs a synchronous operation, converting failures to envelope errors.</summary> |
| | | 263 | | protected static DataOutput<TResult> Guarded<TResult>(Func<TResult> operation) |
| | 27 | 264 | | { |
| | | 265 | | try |
| | 27 | 266 | | { |
| | 27 | 267 | | return DataOutput<TResult>.New.WithData(operation()); |
| | | 268 | | } |
| | 0 | 269 | | catch (OperationCanceledException) |
| | 0 | 270 | | { |
| | 0 | 271 | | throw; |
| | | 272 | | } |
| | 3 | 273 | | catch (Exception ex) |
| | 3 | 274 | | { |
| | 3 | 275 | | return Fail<TResult>(ex); |
| | | 276 | | } |
| | 27 | 277 | | } |
| | | 278 | | |
| | | 279 | | // --- session-aware driver helpers (async) --- |
| | | 280 | | private Task InsertOneAsync(T document, CancellationToken ct) => |
| | 6 | 281 | | Session is { } s |
| | 6 | 282 | | ? Collection.InsertOneAsync(s, document, null, ct) |
| | 6 | 283 | | : Collection.InsertOneAsync(document, null, ct); |
| | | 284 | | |
| | | 285 | | private Task InsertManyAsync(IEnumerable<T> documents, CancellationToken ct) => |
| | 2 | 286 | | Session is { } s |
| | 2 | 287 | | ? Collection.InsertManyAsync(s, documents, null, ct) |
| | 2 | 288 | | : Collection.InsertManyAsync(documents, null, ct); |
| | | 289 | | |
| | | 290 | | private Task DeleteManyAsync(FilterDefinition<T> filter, CancellationToken ct) => |
| | 2 | 291 | | Session is { } s ? Collection.DeleteManyAsync(s, filter, null, ct) : Collection.DeleteManyAsync(filter, ct); |
| | | 292 | | |
| | | 293 | | private async Task ReplaceAsync(T document, CancellationToken ct) |
| | 1 | 294 | | { |
| | 1 | 295 | | if (document is VersionedDocument versioned) |
| | 0 | 296 | | { |
| | 0 | 297 | | var expected = versioned.Version; |
| | 0 | 298 | | versioned.Version = expected + 1; |
| | 0 | 299 | | var filter = Builders<T>.Filter.And(IdFilter(document.Id), |
| | 0 | 300 | | Builders<T>.Filter.Eq(VersionElementName, expected)); |
| | 0 | 301 | | var result = Session is { } s |
| | 0 | 302 | | ? await Collection.ReplaceOneAsync(s, filter, document, cancellationToken: ct) |
| | 0 | 303 | | : await Collection.ReplaceOneAsync(filter, document, cancellationToken: ct); |
| | 0 | 304 | | if (result.MatchedCount == 0) |
| | 0 | 305 | | { |
| | 0 | 306 | | versioned.Version = expected; // roll back the in-memory bump on a failed (stale) update |
| | 0 | 307 | | throw new MongoConcurrencyException(); |
| | | 308 | | } |
| | | 309 | | |
| | 0 | 310 | | return; |
| | | 311 | | } |
| | | 312 | | |
| | 1 | 313 | | var idFilter = IdFilter(document.Id); |
| | 1 | 314 | | if (Session is { } session) |
| | 0 | 315 | | { |
| | 0 | 316 | | await Collection.ReplaceOneAsync(session, idFilter, document, cancellationToken: ct); |
| | 0 | 317 | | } |
| | | 318 | | else |
| | 1 | 319 | | { |
| | 1 | 320 | | await Collection.ReplaceOneAsync(idFilter, document, cancellationToken: ct); |
| | 1 | 321 | | } |
| | 1 | 322 | | } |
| | | 323 | | |
| | | 324 | | /// <summary>Runs an asynchronous operation, converting failures to envelope errors.</summary> |
| | | 325 | | protected static async Task<DataOutput<TResult>> GuardedAsync<TResult>(Func<Task<TResult>> operation) |
| | 18 | 326 | | { |
| | | 327 | | try |
| | 18 | 328 | | { |
| | 18 | 329 | | return DataOutput<TResult>.New.WithData(await operation()); |
| | | 330 | | } |
| | 0 | 331 | | catch (OperationCanceledException) |
| | 0 | 332 | | { |
| | 0 | 333 | | throw; |
| | | 334 | | } |
| | 0 | 335 | | catch (Exception ex) |
| | 0 | 336 | | { |
| | 0 | 337 | | return Fail<TResult>(ex); |
| | | 338 | | } |
| | 18 | 339 | | } |
| | | 340 | | |
| | | 341 | | /// <summary>Maps an exception to an error envelope.</summary> |
| | 3 | 342 | | protected static DataOutput<TResult> Fail<TResult>(Exception ex) => ex switch |
| | 3 | 343 | | { |
| | 2 | 344 | | MongoConcurrencyException => DataOutput<TResult>.New.WithError(ConcurrencyMessage), |
| | 1 | 345 | | _ => DataOutput<TResult>.New.WithError($"{OperationFailedMessage} {ex.GetBaseException().Message}") |
| | 3 | 346 | | }; |
| | | 347 | | } |