| | | 1 | | using Microsoft.Extensions.Hosting; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using System.Text; |
| | | 5 | | |
| | | 6 | | namespace AsyncResponse.Transports.Kafka; |
| | | 7 | | |
| | | 8 | | internal abstract class KafkaSubscriberService : BackgroundService |
| | | 9 | | { |
| | | 10 | | private readonly IKafkaConsumerClientFactory _consumerFactory; |
| | | 11 | | private readonly IKafkaProducerClient _producer; |
| | | 12 | | private readonly IKafkaAdminClient _adminClient; |
| | | 13 | | |
| | | 14 | | /// <summary>Runs the KafkaSubscriberService operation.</summary> |
| | 3 | 15 | | protected KafkaSubscriberService( |
| | 3 | 16 | | IOptions<KafkaAsyncResponseTransportOptions> options, |
| | 3 | 17 | | IKafkaConsumerClientFactory consumerFactory, |
| | 3 | 18 | | IKafkaProducerClient producer, |
| | 3 | 19 | | IKafkaAdminClient adminClient, |
| | 3 | 20 | | ILogger logger) |
| | | 21 | | { |
| | 3 | 22 | | Options = options.Value; |
| | 3 | 23 | | KafkaTransportOptionsValidator.ValidateCommon(Options); |
| | 3 | 24 | | _consumerFactory = consumerFactory; |
| | 3 | 25 | | _producer = producer; |
| | 3 | 26 | | _adminClient = adminClient; |
| | 3 | 27 | | Logger = logger; |
| | 3 | 28 | | } |
| | | 29 | | |
| | | 30 | | protected KafkaAsyncResponseTransportOptions Options { get; } |
| | | 31 | | protected ILogger Logger { get; } |
| | | 32 | | |
| | | 33 | | protected abstract string Topic { get; } |
| | | 34 | | protected abstract string ConsumerGroup { get; } |
| | | 35 | | protected abstract KafkaSubscriberOptions SubscriberOptions { get; } |
| | | 36 | | protected abstract KafkaSubscriberRole SubscriberRole { get; } |
| | | 37 | | /// <summary>Handles the delivered message.</summary> |
| | | 38 | | protected abstract Task HandleMessageAsync(KafkaDelivery delivery, CancellationToken cancellationToken); |
| | | 39 | | |
| | | 40 | | /// <summary>Runs this background operation until cancellation is requested.</summary> |
| | | 41 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | 42 | | { |
| | 3 | 43 | | KafkaMessageDispatcher.ValidateOptions(Options, SubscriberOptions, SubscriberRole); |
| | | 44 | | |
| | 3 | 45 | | var failures = 0; |
| | 3 | 46 | | while (!stoppingToken.IsCancellationRequested) |
| | | 47 | | { |
| | | 48 | | try |
| | | 49 | | { |
| | 3 | 50 | | await RunSubscriberAsync(stoppingToken).ConfigureAwait(false); |
| | 3 | 51 | | return; |
| | | 52 | | } |
| | 2 | 53 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 54 | | { |
| | 1 | 55 | | return; |
| | | 56 | | } |
| | 2 | 57 | | catch (Exception ex) when (!stoppingToken.IsCancellationRequested) |
| | | 58 | | { |
| | 2 | 59 | | failures++; |
| | 2 | 60 | | var retryDelay = AsyncResponseRetry.Backoff( |
| | 2 | 61 | | failures, |
| | 2 | 62 | | Options.SubscriberRetryBaseDelay, |
| | 2 | 63 | | Options.SubscriberRetryMaxDelay); |
| | 2 | 64 | | Logger.LogWarning( |
| | 2 | 65 | | ex, |
| | 2 | 66 | | "Kafka subscriber failed for topic {Topic} ({Role}); retrying in {RetryDelay}.", |
| | 2 | 67 | | Topic, |
| | 2 | 68 | | SubscriberRole, |
| | 2 | 69 | | retryDelay); |
| | 2 | 70 | | await Task.Delay(retryDelay, stoppingToken).ConfigureAwait(false); |
| | | 71 | | } |
| | | 72 | | } |
| | 3 | 73 | | } |
| | | 74 | | |
| | | 75 | | private async Task RunSubscriberAsync(CancellationToken stoppingToken) |
| | | 76 | | { |
| | 3 | 77 | | if (Options.CreateTopics) |
| | 3 | 78 | | await EnsureTopicsAsync(stoppingToken).ConfigureAwait(false); |
| | | 79 | | |
| | 3 | 80 | | var consumer = _consumerFactory.Create(SubscriberRole); |
| | | 81 | | try |
| | | 82 | | { |
| | 3 | 83 | | consumer.Subscribe(Topic); |
| | 3 | 84 | | await using var dispatcher = KafkaMessageDispatcher.Create( |
| | 3 | 85 | | HandleMessageAsync, |
| | 3 | 86 | | consumer, |
| | 3 | 87 | | _producer, |
| | 3 | 88 | | Options, |
| | 3 | 89 | | SubscriberOptions, |
| | 3 | 90 | | Logger, |
| | 3 | 91 | | Topic, |
| | 3 | 92 | | ConsumerGroup, |
| | 3 | 93 | | SubscriberRole); |
| | | 94 | | |
| | 3 | 95 | | Logger.LogInformation( |
| | 3 | 96 | | "Kafka subscriber started. Topic: {Topic}. Group: {ConsumerGroup}. Role: {Role}. AckMode: {AckMode}.", |
| | 3 | 97 | | Topic, |
| | 3 | 98 | | ConsumerGroup, |
| | 3 | 99 | | SubscriberRole, |
| | 3 | 100 | | SubscriberOptions.AckMode); |
| | | 101 | | |
| | | 102 | | // Consume() blocks the calling thread, so the poll loop runs on a dedicated thread |
| | | 103 | | // instead of starving the thread pool; the dispatcher's async work is awaited from it. |
| | 3 | 104 | | await Task.Factory.StartNew( |
| | 3 | 105 | | () => RunPollLoop(consumer, dispatcher, stoppingToken), |
| | 3 | 106 | | stoppingToken, |
| | 3 | 107 | | TaskCreationOptions.LongRunning, |
| | 3 | 108 | | TaskScheduler.Default).ConfigureAwait(false); |
| | | 109 | | |
| | | 110 | | // Leaving the await-using scope drains the ACK-after-enqueue background queue before |
| | | 111 | | // the consumer commits its final stored offsets below. |
| | 3 | 112 | | } |
| | | 113 | | finally |
| | | 114 | | { |
| | 3 | 115 | | CloseQuietly(consumer); |
| | 3 | 116 | | consumer.Dispose(); |
| | | 117 | | } |
| | 3 | 118 | | } |
| | | 119 | | |
| | | 120 | | private void RunPollLoop( |
| | | 121 | | IKafkaConsumerClient consumer, |
| | | 122 | | KafkaMessageDispatcher dispatcher, |
| | | 123 | | CancellationToken stoppingToken) |
| | | 124 | | { |
| | 3 | 125 | | var paused = false; |
| | 3 | 126 | | while (!stoppingToken.IsCancellationRequested) |
| | | 127 | | { |
| | | 128 | | KafkaIncomingMessage? message; |
| | 3 | 129 | | if (!dispatcher.CanAcceptMore) |
| | | 130 | | { |
| | | 131 | | // Backpressure: stop fetching from the assigned partitions while the bounded |
| | | 132 | | // in-process queue is saturated. Keep calling Consume so the broker still sees the |
| | | 133 | | // consumer polling (max.poll.interval.ms) and rebalance callbacks keep firing. |
| | 2 | 134 | | if (!paused) |
| | | 135 | | { |
| | 2 | 136 | | consumer.PauseAssignment(); |
| | 2 | 137 | | paused = true; |
| | 2 | 138 | | Logger.LogDebug( |
| | 2 | 139 | | "Kafka subscriber for {Topic} paused its assignment: the in-process queue is full.", |
| | 2 | 140 | | Topic); |
| | | 141 | | } |
| | | 142 | | |
| | 3 | 143 | | message = consumer.Consume(SubscriberOptions.BackpressurePollDelay); |
| | | 144 | | } |
| | | 145 | | else |
| | | 146 | | { |
| | 3 | 147 | | if (paused) |
| | | 148 | | { |
| | 2 | 149 | | consumer.ResumeAssignment(); |
| | 2 | 150 | | paused = false; |
| | 3 | 151 | | Logger.LogDebug( |
| | 3 | 152 | | "Kafka subscriber for {Topic} resumed its assignment: in-process queue capacity freed.", |
| | 3 | 153 | | Topic); |
| | | 154 | | } |
| | | 155 | | |
| | 3 | 156 | | message = consumer.Consume(SubscriberOptions.PollTimeout); |
| | | 157 | | } |
| | | 158 | | |
| | 3 | 159 | | if (message is null) |
| | | 160 | | continue; |
| | | 161 | | |
| | | 162 | | KafkaDelivery delivery; |
| | | 163 | | try |
| | | 164 | | { |
| | 3 | 165 | | delivery = CreateDelivery(message); |
| | 3 | 166 | | } |
| | 2 | 167 | | catch (InvalidDataException ex) |
| | | 168 | | { |
| | | 169 | | // A foreign/malformed message can never be handled; dead-letter and commit it so |
| | | 170 | | // its partition advances instead of re-failing on every subscriber restart. |
| | 2 | 171 | | dispatcher.DiscardUnprocessableAsync(message, ex, stoppingToken).GetAwaiter().GetResult(); |
| | 3 | 172 | | continue; |
| | | 173 | | } |
| | | 174 | | |
| | 3 | 175 | | dispatcher.HandleAsync(delivery, stoppingToken).GetAwaiter().GetResult(); |
| | | 176 | | } |
| | 3 | 177 | | } |
| | | 178 | | |
| | | 179 | | private async Task EnsureTopicsAsync(CancellationToken cancellationToken) |
| | | 180 | | { |
| | 3 | 181 | | var topics = new List<string>(2) { Topic }; |
| | 3 | 182 | | if (Options.DeadLetterEnabled) |
| | 3 | 183 | | topics.Add(new KafkaTransportTopicSchema(Options).DeadLetterTopicFor(Topic)); |
| | | 184 | | |
| | 3 | 185 | | await _adminClient.EnsureTopicsAsync( |
| | 3 | 186 | | topics, |
| | 3 | 187 | | Options.TopicNumPartitions, |
| | 3 | 188 | | Options.TopicReplicationFactor, |
| | 3 | 189 | | cancellationToken).ConfigureAwait(false); |
| | 3 | 190 | | } |
| | | 191 | | |
| | | 192 | | private KafkaDelivery CreateDelivery(KafkaIncomingMessage message) |
| | | 193 | | { |
| | 3 | 194 | | var payload = message.Payload is { Length: > 0 } |
| | 3 | 195 | | ? Encoding.UTF8.GetString(message.Payload) |
| | 3 | 196 | | : null; |
| | 3 | 197 | | if (string.IsNullOrWhiteSpace(payload)) |
| | | 198 | | { |
| | 3 | 199 | | throw new InvalidDataException( |
| | 3 | 200 | | $"Kafka message {message.Topic}[{message.Partition}]@{message.Offset} does not contain a payload."); |
| | | 201 | | } |
| | | 202 | | |
| | 3 | 203 | | var correlationId = SubscriberRole is KafkaSubscriberRole.ResponseIngress |
| | 3 | 204 | | ? KafkaCorrelationIdExtractor.Extract(message.Headers, payload, Options) |
| | 3 | 205 | | : KafkaCorrelationIdExtractor.TryReadHeader(message.Headers, Options.CorrelationIdHeader); |
| | | 206 | | |
| | 3 | 207 | | return new KafkaDelivery( |
| | 3 | 208 | | message.Topic, |
| | 3 | 209 | | message.Partition, |
| | 3 | 210 | | message.Offset, |
| | 3 | 211 | | payload, |
| | 3 | 212 | | correlationId, |
| | 3 | 213 | | message.Headers); |
| | | 214 | | } |
| | | 215 | | |
| | | 216 | | private void CloseQuietly(IKafkaConsumerClient consumer) |
| | | 217 | | { |
| | | 218 | | try |
| | | 219 | | { |
| | | 220 | | // Commits stored offsets and leaves the group cleanly so partitions rebalance |
| | | 221 | | // immediately instead of waiting for the session timeout. |
| | 3 | 222 | | consumer.Close(); |
| | 3 | 223 | | } |
| | 2 | 224 | | catch (Exception ex) |
| | | 225 | | { |
| | 2 | 226 | | Logger.LogWarning( |
| | 2 | 227 | | ex, |
| | 2 | 228 | | "Kafka consumer for topic {Topic} ({Role}) failed to close cleanly; uncommitted offsets will be redelive |
| | 2 | 229 | | Topic, |
| | 2 | 230 | | SubscriberRole); |
| | 3 | 231 | | } |
| | 3 | 232 | | } |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | internal sealed class KafkaWorkerSubscriber : KafkaSubscriberService |
| | | 236 | | { |
| | | 237 | | private readonly IAsyncResponseIngress _ingress; |
| | | 238 | | private readonly KafkaTransportTopicSchema _topics; |
| | | 239 | | |
| | | 240 | | /// <summary>Runs the KafkaWorkerSubscriber operation.</summary> |
| | | 241 | | public KafkaWorkerSubscriber( |
| | | 242 | | IOptions<KafkaAsyncResponseTransportOptions> options, |
| | | 243 | | IKafkaConsumerClientFactory consumerFactory, |
| | | 244 | | IKafkaProducerClient producer, |
| | | 245 | | IKafkaAdminClient adminClient, |
| | | 246 | | IAsyncResponseIngress ingress, |
| | | 247 | | ILogger<KafkaWorkerSubscriber> logger) |
| | | 248 | | : base(options, consumerFactory, producer, adminClient, logger) |
| | | 249 | | { |
| | | 250 | | _ingress = ingress; |
| | | 251 | | _topics = new KafkaTransportTopicSchema(options.Value); |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | protected override string Topic => _topics.WorkerTopic; |
| | | 255 | | protected override string ConsumerGroup => Options.WorkerConsumerGroup; |
| | | 256 | | protected override KafkaSubscriberOptions SubscriberOptions => Options.WorkerSubscriber; |
| | | 257 | | protected override KafkaSubscriberRole SubscriberRole => KafkaSubscriberRole.Worker; |
| | | 258 | | |
| | | 259 | | /// <summary>Handles the delivered message.</summary> |
| | | 260 | | protected override Task HandleMessageAsync(KafkaDelivery delivery, CancellationToken cancellationToken) |
| | | 261 | | => _ingress.HandleWorkerMessageAsync(delivery.Payload); |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | internal sealed class KafkaResponseIngressSubscriber : KafkaSubscriberService |
| | | 265 | | { |
| | | 266 | | private readonly IAsyncResponseIngress _ingress; |
| | | 267 | | private readonly KafkaTransportTopicSchema _topics; |
| | | 268 | | |
| | | 269 | | /// <summary>Runs the KafkaResponseIngressSubscriber operation.</summary> |
| | | 270 | | public KafkaResponseIngressSubscriber( |
| | | 271 | | IOptions<KafkaAsyncResponseTransportOptions> options, |
| | | 272 | | IKafkaConsumerClientFactory consumerFactory, |
| | | 273 | | IKafkaProducerClient producer, |
| | | 274 | | IKafkaAdminClient adminClient, |
| | | 275 | | IAsyncResponseIngress ingress, |
| | | 276 | | ILogger<KafkaResponseIngressSubscriber> logger) |
| | | 277 | | : base(options, consumerFactory, producer, adminClient, logger) |
| | | 278 | | { |
| | | 279 | | _ingress = ingress; |
| | | 280 | | _topics = new KafkaTransportTopicSchema(options.Value); |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | protected override string Topic => _topics.ResponseTopic; |
| | | 284 | | protected override string ConsumerGroup => Options.ResponseConsumerGroup; |
| | | 285 | | protected override KafkaSubscriberOptions SubscriberOptions => Options.ResponseSubscriber; |
| | | 286 | | protected override KafkaSubscriberRole SubscriberRole => KafkaSubscriberRole.ResponseIngress; |
| | | 287 | | |
| | | 288 | | /// <summary>Handles the delivered message.</summary> |
| | | 289 | | protected override Task HandleMessageAsync(KafkaDelivery delivery, CancellationToken cancellationToken) |
| | | 290 | | => _ingress.HandleResponseMessageAsync(delivery.Payload, delivery.CorrelationId); |
| | | 291 | | } |