|
| 1 | +using Microsoft.Azure.Cosmos; |
| 2 | + |
| 3 | +namespace CosmosDbTestTool |
| 4 | +{ |
| 5 | + /// <summary> |
| 6 | + /// Runs a real Cosmos DB change feed processor against the monitored container, creating |
| 7 | + /// authentic .NET SDK lease documents in the lease container. This is what the KEDA |
| 8 | + /// azure-cosmosdb scaler e2e test needs bootstrapped before it can measure change feed lag - |
| 9 | + /// the scaler only reads lease/change-feed state via REST, it never creates leases itself. |
| 10 | + /// </summary> |
| 11 | + public class ChangeFeedProcessorWorker : BackgroundService |
| 12 | + { |
| 13 | + private readonly ILogger<ChangeFeedProcessorWorker> _logger; |
| 14 | + private readonly CosmosDbOptions _options; |
| 15 | + private CosmosClient? _client; |
| 16 | + private CosmosClient? _leaseClient; |
| 17 | + private ChangeFeedProcessor? _processor; |
| 18 | + |
| 19 | + public ChangeFeedProcessorWorker(ILogger<ChangeFeedProcessorWorker> logger, IConfiguration configuration) |
| 20 | + { |
| 21 | + _logger = logger; |
| 22 | + _options = CosmosDbOptions.FromEnvironment(configuration); |
| 23 | + } |
| 24 | + |
| 25 | + public override async Task StartAsync(CancellationToken cancellationToken) |
| 26 | + { |
| 27 | + var clientOptions = new CosmosClientOptions { ConnectionMode = ConnectionMode.Gateway }; |
| 28 | + _client = new CosmosClient(_options.Connection, clientOptions); |
| 29 | + _leaseClient = _options.LeaseConnection == _options.Connection |
| 30 | + ? _client |
| 31 | + : new CosmosClient(_options.LeaseConnection, clientOptions); |
| 32 | + |
| 33 | + Database database = await _client.CreateDatabaseIfNotExistsAsync(_options.DatabaseId); |
| 34 | + Container monitoredContainer = await database.CreateContainerIfNotExistsAsync(_options.ContainerId, "/id"); |
| 35 | + |
| 36 | + Database leaseDatabase = _options.LeaseDatabaseId == _options.DatabaseId |
| 37 | + ? database |
| 38 | + : await _leaseClient.CreateDatabaseIfNotExistsAsync(_options.LeaseDatabaseId); |
| 39 | + Container leaseContainer = await leaseDatabase.CreateContainerIfNotExistsAsync(_options.LeaseContainerId, "/id"); |
| 40 | + |
| 41 | + _processor = monitoredContainer |
| 42 | + .GetChangeFeedProcessorBuilder<dynamic>(_options.ProcessorName, HandleChangesAsync) |
| 43 | + .WithInstanceName(Environment.MachineName) |
| 44 | + .WithLeaseContainer(leaseContainer) |
| 45 | + .WithErrorNotification(HandleErrorAsync) |
| 46 | + .Build(); |
| 47 | + |
| 48 | + await _processor.StartAsync(); |
| 49 | + _logger.LogInformation( |
| 50 | + "Change feed processor '{ProcessorName}' started on {Database}/{Container}, leases in {LeaseDatabase}/{LeaseContainer}", |
| 51 | + _options.ProcessorName, _options.DatabaseId, _options.ContainerId, _options.LeaseDatabaseId, _options.LeaseContainerId); |
| 52 | + |
| 53 | + await base.StartAsync(cancellationToken); |
| 54 | + } |
| 55 | + |
| 56 | + protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 57 | + { |
| 58 | + // All the work happens in the SDK's own change feed pump; just wait for shutdown. |
| 59 | + try |
| 60 | + { |
| 61 | + await Task.Delay(Timeout.Infinite, stoppingToken); |
| 62 | + } |
| 63 | + catch (TaskCanceledException) |
| 64 | + { |
| 65 | + // expected on shutdown |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public override async Task StopAsync(CancellationToken cancellationToken) |
| 70 | + { |
| 71 | + if (_processor != null) |
| 72 | + { |
| 73 | + await _processor.StopAsync(); |
| 74 | + } |
| 75 | + await base.StopAsync(cancellationToken); |
| 76 | + } |
| 77 | + |
| 78 | + private Task HandleChangesAsync(IReadOnlyCollection<dynamic> changes, CancellationToken cancellationToken) |
| 79 | + { |
| 80 | + _logger.LogInformation("Processed {Count} change(s) from the change feed", changes.Count); |
| 81 | + return Task.CompletedTask; |
| 82 | + } |
| 83 | + |
| 84 | + private Task HandleErrorAsync(string leaseToken, Exception exception) |
| 85 | + { |
| 86 | + _logger.LogError(exception, "Unhandled exception on lease {LeaseToken}", leaseToken); |
| 87 | + return Task.CompletedTask; |
| 88 | + } |
| 89 | + |
| 90 | + public override void Dispose() |
| 91 | + { |
| 92 | + _client?.Dispose(); |
| 93 | + if (_leaseClient != _client) |
| 94 | + { |
| 95 | + _leaseClient?.Dispose(); |
| 96 | + } |
| 97 | + base.Dispose(); |
| 98 | + } |
| 99 | + } |
| 100 | +} |
0 commit comments