|
| 1 | +using System.ComponentModel.Composition; |
| 2 | +using Cosmos.DataTransfer.Interfaces; |
| 3 | +using Cosmos.DataTransfer.MongoExtension.Settings; |
| 4 | +using Microsoft.Extensions.Configuration; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using MongoDB.Bson; |
| 7 | + |
| 8 | +namespace Cosmos.DataTransfer.MongoExtension; |
| 9 | +[Export(typeof(IDataSinkExtension))] |
| 10 | +public class MongoDataSinkExtension : IDataSinkExtensionWithSettings |
| 11 | +{ |
| 12 | + public string DisplayName => "MongoDB"; |
| 13 | + |
| 14 | + public async Task WriteAsync(IAsyncEnumerable<IDataItem> dataItems, IConfiguration config, IDataSourceExtension dataSource, ILogger logger, CancellationToken cancellationToken = default) |
| 15 | + { |
| 16 | + var settings = config.Get<MongoSinkSettings>(); |
| 17 | + settings.Validate(); |
| 18 | + |
| 19 | + if (!string.IsNullOrEmpty(settings.ConnectionString) && !string.IsNullOrEmpty(settings.DatabaseName) && !string.IsNullOrEmpty(settings.Collection)) |
| 20 | + { |
| 21 | + var context = new Context(settings.ConnectionString, settings.DatabaseName); |
| 22 | + var repo = context.GetRepository<BsonDocument>(settings.Collection); |
| 23 | + |
| 24 | + var batchSize = settings.BatchSize ?? 1000; |
| 25 | + |
| 26 | + var objects = new List<BsonDocument>(); |
| 27 | + int itemCount = 0; |
| 28 | + await foreach (var item in dataItems.WithCancellation(cancellationToken)) |
| 29 | + { |
| 30 | + var dict = item.BuildDynamicObjectTree(); |
| 31 | + objects.Add(new BsonDocument(dict)); |
| 32 | + itemCount++; |
| 33 | + |
| 34 | + if (objects.Count == batchSize) |
| 35 | + { |
| 36 | + await repo.AddRange(objects); |
| 37 | + logger.LogInformation("Added {ItemCount} items to collection '{Collection}'", itemCount, settings.Collection); |
| 38 | + objects.Clear(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + if (objects.Any()) |
| 43 | + { |
| 44 | + await repo.AddRange(objects); |
| 45 | + } |
| 46 | + |
| 47 | + if (itemCount > 0) |
| 48 | + logger.LogInformation("Added {ItemCount} total items to collection '{Collection}'", itemCount, settings.Collection); |
| 49 | + else |
| 50 | + logger.LogWarning("No items added to collection '{Collection}'", settings.Collection); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public IEnumerable<IDataExtensionSettings> GetSettings() |
| 55 | + { |
| 56 | + yield return new MongoSinkSettings(); |
| 57 | + } |
| 58 | +} |
0 commit comments