| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Buffers; |
| | | 6 | | using System.Collections.Concurrent; |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using System.IO.Pipelines; |
| | | 9 | | using System.Linq; |
| | | 10 | | using System.Net; |
| | | 11 | | using System.Text.RegularExpressions; |
| | | 12 | | using System.Threading; |
| | | 13 | | using System.Threading.Tasks; |
| | | 14 | | using Confluent.Kafka; |
| | | 15 | | using CoreWCF.Configuration; |
| | | 16 | | using CoreWCF.Queue.Common; |
| | | 17 | | using CoreWCF.Runtime; |
| | | 18 | | using Microsoft.Extensions.Logging; |
| | | 19 | | |
| | | 20 | | namespace CoreWCF.Channels; |
| | | 21 | | |
| | | 22 | | internal sealed class KafkaTransportPump : QueueTransportPump, IDisposable |
| | | 23 | | { |
| | | 24 | | private readonly ILogger<KafkaTransportPump> _logger; |
| | | 25 | | private readonly KafkaDeliverySemantics _kafkaDeliverySemantics; |
| | 1251 | 26 | | private IConsumer<byte[], byte[]> Consumer { get; set; } |
| | 1197 | 27 | | private ConsumerConfig ConsumerConfig { get; set; } |
| | 10 | 28 | | internal IProducer<Null, byte[]> Producer { get; private set; } |
| | 175 | 29 | | private string Topic { get; } |
| | 896 | 30 | | internal KafkaTransportBindingElement TransportBindingElement { get; } |
| | | 31 | | private CountdownEvent _receiveContextCountdownEvent; |
| | 44 | 32 | | private readonly object _disposeLock = new(); |
| | | 33 | | private readonly Uri _baseAddress; |
| | | 34 | | private CancellationTokenSource _cts; |
| | | 35 | | private AsyncManualResetEvent _mres; |
| | | 36 | | private bool _isStarted; |
| | | 37 | | private bool _isRegexSubscription; |
| | | 38 | | private readonly TimeSpan _closeTimeout; |
| | 929 | 39 | | internal TopicPartitionOffsetTracker OffsetTracker { get; private set; } |
| | | 40 | | |
| | 1 | 41 | | private static readonly (bool? EnableAutoCommit, bool? EnableAutoOffsetStore) s_atMostOnceConfigValues = (false, nul |
| | 1 | 42 | | private static readonly (bool? EnableAutoCommit, bool? EnableAutoOffsetStore) s_atLeastOncePerMessageCommitConfigVal |
| | 1 | 43 | | private static readonly (bool? EnableAutoCommit, bool? EnableAutoOffsetStore) s_atLeastOnceBatchCommitConfigValues = |
| | 1 | 44 | | private static readonly Regex s_topicNameRegex = |
| | 1 | 45 | | new(@"^[a-zA-Z0-9\.\-_\*\^]{1,255}$", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100)); |
| | | 46 | | |
| | 44 | 47 | | public KafkaTransportPump(KafkaTransportBindingElement transportBindingElement, |
| | 44 | 48 | | ILogger<KafkaTransportPump> logger, |
| | 44 | 49 | | IServiceDispatcher serviceDispatcher, KafkaDeliverySemantics kafkaDeliverySemantics) |
| | | 50 | | { |
| | 44 | 51 | | _logger = logger; |
| | 44 | 52 | | _kafkaDeliverySemantics = kafkaDeliverySemantics; |
| | 44 | 53 | | Topic = WebUtility.UrlDecode(serviceDispatcher.BaseAddress.PathAndQuery.TrimStart('/')); |
| | 44 | 54 | | _isRegexSubscription = Topic.StartsWith("^"); |
| | | 55 | | |
| | 44 | 56 | | if (string.IsNullOrEmpty(Topic) || !s_topicNameRegex.IsMatch(Topic)) |
| | | 57 | | { |
| | 0 | 58 | | throw new NotSupportedException(string.Format(SR.InvalidTopicName, Topic)); |
| | | 59 | | } |
| | | 60 | | |
| | 44 | 61 | | if (transportBindingElement.ErrorHandlingStrategy == KafkaErrorHandlingStrategy.DeadLetterQueue) |
| | | 62 | | { |
| | 2 | 63 | | if (string.IsNullOrEmpty(transportBindingElement.DeadLetterQueueTopic)) |
| | | 64 | | { |
| | 0 | 65 | | throw new NotSupportedException(SR.InvalidDeadLetterQueueTopicName); |
| | | 66 | | } |
| | | 67 | | |
| | 2 | 68 | | if (!s_topicNameRegex.IsMatch(transportBindingElement.DeadLetterQueueTopic)) |
| | | 69 | | { |
| | 0 | 70 | | throw new NotSupportedException(string.Format(SR.InvalidTopicName, Topic)); |
| | | 71 | | } |
| | | 72 | | } |
| | 44 | 73 | | TransportBindingElement = (KafkaTransportBindingElement)transportBindingElement.Clone(); |
| | 44 | 74 | | _baseAddress = serviceDispatcher.BaseAddress; |
| | 44 | 75 | | _closeTimeout = serviceDispatcher.Binding.CloseTimeout; |
| | 44 | 76 | | } |
| | | 77 | | |
| | | 78 | | public override Task StartPumpAsync(QueueTransportContext queueTransportContext, CancellationToken token) |
| | | 79 | | { |
| | 43 | 80 | | _cts = CancellationTokenSource.CreateLinkedTokenSource(token); |
| | 43 | 81 | | _mres = new(); |
| | 43 | 82 | | _mres.Reset(); |
| | 43 | 83 | | _receiveContextCountdownEvent = new(1); |
| | | 84 | | |
| | 43 | 85 | | _isStarted = true; |
| | | 86 | | |
| | 43 | 87 | | ConsumerConfig = new(); |
| | 420 | 88 | | foreach (var property in TransportBindingElement.Config) |
| | | 89 | | { |
| | 167 | 90 | | ConsumerConfig.Set(property.Key, property.Value); |
| | | 91 | | } |
| | 43 | 92 | | ConsumerConfig.BootstrapServers = _baseAddress.Authority; |
| | 43 | 93 | | var (enableAutoCommit, enableAutoOffsetStore) = GetCommitStrategyConfigValues(ConsumerConfig, _kafkaDeliverySema |
| | 43 | 94 | | ConsumerConfig.EnableAutoCommit = enableAutoCommit; |
| | 43 | 95 | | ConsumerConfig.EnableAutoOffsetStore = enableAutoOffsetStore; |
| | 43 | 96 | | Consumer = new ConsumerBuilder<byte[], byte[]>(ConsumerConfig) |
| | 43 | 97 | | .SetKeyDeserializer(Deserializers.ByteArray) |
| | 43 | 98 | | .SetValueDeserializer(Deserializers.ByteArray) |
| | 43 | 99 | | .SetLogHandler(OnLog) |
| | 43 | 100 | | .SetErrorHandler(OnError) |
| | 43 | 101 | | .Build(); |
| | 43 | 102 | | OffsetTracker = _kafkaDeliverySemantics == KafkaDeliverySemantics.AtLeastOnce |
| | 43 | 103 | | ? new TopicPartitionOffsetTracker(Consumer, ConsumerConfig, _logger) |
| | 43 | 104 | | : null; |
| | | 105 | | |
| | 43 | 106 | | Consumer.Subscribe(Topic); |
| | | 107 | | |
| | 43 | 108 | | if (TransportBindingElement.ErrorHandlingStrategy == KafkaErrorHandlingStrategy.DeadLetterQueue) |
| | | 109 | | { |
| | 2 | 110 | | ProducerConfig producerConfig = new(); |
| | 16 | 111 | | foreach (var property in TransportBindingElement.Config) |
| | | 112 | | { |
| | 6 | 113 | | producerConfig.Set(property.Key, property.Value); |
| | | 114 | | } |
| | 2 | 115 | | producerConfig.BootstrapServers = _baseAddress.Authority; |
| | 2 | 116 | | producerConfig.Acks = Acks.All; |
| | 2 | 117 | | Producer = new ProducerBuilder<Null, byte[]>(producerConfig) |
| | 2 | 118 | | .SetKeySerializer(Serializers.Null) |
| | 2 | 119 | | .SetValueSerializer(Serializers.ByteArray) |
| | 2 | 120 | | .Build(); |
| | | 121 | | } |
| | | 122 | | |
| | 43 | 123 | | Task.Run(async () => |
| | 43 | 124 | | { |
| | 755 | 125 | | while (!_cts.Token.IsCancellationRequested) |
| | 43 | 126 | | { |
| | 43 | 127 | | try |
| | 43 | 128 | | { |
| | 755 | 129 | | var consumeResult = Consumer.Consume(_cts.Token); |
| | 712 | 130 | | if (ConsumerConfig.EnablePartitionEof == true && consumeResult.IsPartitionEOF) |
| | 43 | 131 | | { |
| | 0 | 132 | | continue; |
| | 43 | 133 | | } |
| | 43 | 134 | | |
| | 712 | 135 | | _logger.LogInformation("Received message from kafka at {topicPartitionOffset}", consumeResult.TopicP |
| | 712 | 136 | | if (_kafkaDeliverySemantics == KafkaDeliverySemantics.AtMostOnce) |
| | 43 | 137 | | { |
| | 269 | 138 | | Consumer.Commit(consumeResult); |
| | 43 | 139 | | } |
| | 443 | 140 | | else if (_kafkaDeliverySemantics == KafkaDeliverySemantics.AtLeastOnce) |
| | 43 | 141 | | { |
| | 443 | 142 | | OffsetTracker.Received(consumeResult); |
| | 43 | 143 | | } |
| | 43 | 144 | | |
| | 712 | 145 | | await OnConsumeMessage(consumeResult, queueTransportContext); |
| | 43 | 146 | | |
| | 712 | 147 | | } |
| | 43 | 148 | | catch (OperationCanceledException) |
| | 43 | 149 | | { |
| | 43 | 150 | | break; |
| | 43 | 151 | | } |
| | 0 | 152 | | catch (ConsumeException e) |
| | 43 | 153 | | { |
| | 0 | 154 | | if (e.Error.IsFatal) |
| | 43 | 155 | | { |
| | 0 | 156 | | _logger.LogCritical("Exit consume loop {code} {error}", e.Error.Code, e.Error.Reason); |
| | 0 | 157 | | break; |
| | 43 | 158 | | } |
| | 43 | 159 | | |
| | 0 | 160 | | _logger.LogError(e, "Consume error {code} {error}", e.Error.Code, e.Error.Reason); |
| | 0 | 161 | | } |
| | 0 | 162 | | catch (Exception e) |
| | 43 | 163 | | { |
| | 0 | 164 | | _logger.LogCritical(e, "Unexpected error in consume loop; continuing"); |
| | 43 | 165 | | try |
| | 43 | 166 | | { |
| | 0 | 167 | | await Task.Delay(TimeSpan.FromMilliseconds(100), _cts.Token); |
| | 0 | 168 | | } |
| | 0 | 169 | | catch (OperationCanceledException) |
| | 43 | 170 | | { |
| | 0 | 171 | | break; |
| | 43 | 172 | | } |
| | 43 | 173 | | } |
| | 43 | 174 | | } |
| | 43 | 175 | | _mres.Set(); |
| | 43 | 176 | | }, _cts.Token); |
| | 43 | 177 | | return Task.CompletedTask; |
| | 43 | 178 | | } |
| | | 179 | | |
| | | 180 | | public override async Task StopPumpAsync(CancellationToken token) |
| | | 181 | | { |
| | 43 | 182 | | if (!_isStarted) |
| | | 183 | | { |
| | 0 | 184 | | return; |
| | | 185 | | } |
| | | 186 | | |
| | 43 | 187 | | _cts.Cancel(); |
| | 43 | 188 | | await _mres.WaitAsync(token); |
| | 43 | 189 | | _cts.Dispose(); |
| | | 190 | | |
| | 43 | 191 | | if (ConsumerConfig.EnableAutoCommit == true) |
| | | 192 | | { |
| | | 193 | | // When EnableAutoCommit is true, offset are either manually stored locally or automatically (if EnableAutoO |
| | | 194 | | // Then a background librdkafka thread will commit them at AutoCommitIntervalMs frequency which defaults to |
| | | 195 | | // Thus we should give AutoCommitIntervalMs time before closing the consumer |
| | 7 | 196 | | await Task.Delay(TimeSpan.FromMilliseconds(ConsumerConfig.AutoCommitIntervalMs ?? 5000)); |
| | | 197 | | } |
| | | 198 | | |
| | 43 | 199 | | _receiveContextCountdownEvent.Signal(); |
| | 43 | 200 | | using CancellationTokenSource closeCts = new (_closeTimeout); |
| | | 201 | | try |
| | | 202 | | { |
| | 43 | 203 | | _receiveContextCountdownEvent.Wait(closeCts.Token); |
| | 43 | 204 | | } |
| | 0 | 205 | | catch (OperationCanceledException e) |
| | | 206 | | { |
| | | 207 | | // no-op |
| | | 208 | | // Consumer.Close and Producer.Flush will allow to gracefully handle that service stops |
| | 0 | 209 | | } |
| | | 210 | | |
| | 43 | 211 | | _receiveContextCountdownEvent.Dispose(); |
| | 43 | 212 | | if (TransportBindingElement.ErrorHandlingStrategy == KafkaErrorHandlingStrategy.DeadLetterQueue) |
| | | 213 | | { |
| | 2 | 214 | | Producer.Flush(closeCts.Token); |
| | | 215 | | } |
| | | 216 | | |
| | 43 | 217 | | Consumer.Close(); |
| | 43 | 218 | | } |
| | | 219 | | |
| | | 220 | | private static (bool? EnableAutoCommit, bool? EnableAutoOffsetStore) GetCommitStrategyConfigValues(ConsumerConfig co |
| | 43 | 221 | | (kafkaDeliverySemantics, consumerConfig) switch |
| | 43 | 222 | | { |
| | 43 | 223 | | // KafkaBinding |
| | 33 | 224 | | (KafkaDeliverySemantics.AtMostOnce, { EnableAutoCommit: null, EnableAutoOffsetStore: null }) => s_atMostOnce |
| | 7 | 225 | | (KafkaDeliverySemantics.AtLeastOnce, { EnableAutoCommit: null, EnableAutoOffsetStore: null } ) => s_atLeastO |
| | 43 | 226 | | // CustomBinding |
| | 0 | 227 | | (KafkaDeliverySemantics.AtMostOnce, { EnableAutoCommit: false, EnableAutoOffsetStore: null }) => s_atMostOnc |
| | 0 | 228 | | (KafkaDeliverySemantics.AtLeastOnce, { EnableAutoCommit: true, EnableAutoOffsetStore: false } ) => s_atLeast |
| | 3 | 229 | | (KafkaDeliverySemantics.AtLeastOnce, { EnableAutoCommit: false, EnableAutoOffsetStore: null }) => s_atLeastO |
| | 0 | 230 | | _ => throw new NotSupportedException(string.Format(SR.InvalidKafkaConfiguration, kafkaDeliverySemantics, con |
| | 43 | 231 | | }; |
| | | 232 | | |
| | | 233 | | private void OnLog(IConsumer<byte[], byte[]> consumer, LogMessage logMessage) |
| | | 234 | | { |
| | | 235 | | const string format = "{0}:{1}"; |
| | 2921 | 236 | | switch (logMessage.Level) |
| | | 237 | | { |
| | | 238 | | case SyslogLevel.Debug: |
| | 2921 | 239 | | _logger.LogDebug(format, logMessage.Name, logMessage.Message); |
| | 2921 | 240 | | break; |
| | | 241 | | case SyslogLevel.Notice: |
| | | 242 | | case SyslogLevel.Info: |
| | 0 | 243 | | _logger.LogInformation(format, logMessage.Name, logMessage.Message); |
| | 0 | 244 | | break; |
| | | 245 | | case SyslogLevel.Warning: |
| | 0 | 246 | | _logger.LogWarning(format, logMessage.Name, logMessage.Message); |
| | 0 | 247 | | break; |
| | | 248 | | case SyslogLevel.Error: |
| | 0 | 249 | | _logger.LogError(format, logMessage.Name, logMessage.Message); |
| | 0 | 250 | | break; |
| | | 251 | | case SyslogLevel.Alert: |
| | | 252 | | case SyslogLevel.Critical: |
| | | 253 | | case SyslogLevel.Emergency: |
| | 0 | 254 | | _logger.LogCritical(format, logMessage.Name, logMessage.Message); |
| | 0 | 255 | | break; |
| | | 256 | | default: |
| | 0 | 257 | | throw new ArgumentOutOfRangeException(nameof(logMessage.Level)); |
| | | 258 | | } |
| | | 259 | | } |
| | | 260 | | |
| | | 261 | | private void OnError(IConsumer<byte[], byte[]> consumer, Error error) |
| | | 262 | | { |
| | 0 | 263 | | if (error.IsFatal) |
| | | 264 | | { |
| | 0 | 265 | | _cts.Cancel(); |
| | | 266 | | } |
| | 0 | 267 | | } |
| | | 268 | | |
| | | 269 | | private Task OnConsumeMessage(ConsumeResult<byte[], byte[]> consumeResult, |
| | | 270 | | QueueTransportContext queueTransportContext) |
| | | 271 | | { |
| | 713 | 272 | | var receiveContext = new KafkaReceiveContext(consumeResult, this); |
| | 713 | 273 | | var context = new KafkaMessageContext |
| | 713 | 274 | | { |
| | 713 | 275 | | IsRegexSubscription = _isRegexSubscription, |
| | 713 | 276 | | ReceiveContext = receiveContext, |
| | 713 | 277 | | QueueTransportContext = queueTransportContext, |
| | 713 | 278 | | LocalAddress = new EndpointAddress(queueTransportContext.ServiceDispatcher.BaseAddress), |
| | 713 | 279 | | QueueMessageReader = PipeReader.Create(new ReadOnlySequence<byte>(consumeResult.Message.Value ?? Array.Empty |
| | 713 | 280 | | Properties = |
| | 713 | 281 | | { |
| | 713 | 282 | | [KafkaMessageProperty.Name] = new KafkaMessageProperty(consumeResult) |
| | 713 | 283 | | } |
| | 713 | 284 | | }; |
| | | 285 | | |
| | 713 | 286 | | return queueTransportContext.QueueMessageDispatcher(context); |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | internal void IncrementReceiveContextCount() |
| | | 290 | | { |
| | 713 | 291 | | _receiveContextCountdownEvent.AddCount(); |
| | 713 | 292 | | } |
| | | 293 | | |
| | | 294 | | internal void DecrementReceiveContextCount() |
| | | 295 | | { |
| | 713 | 296 | | _receiveContextCountdownEvent.Signal(); |
| | 713 | 297 | | } |
| | | 298 | | |
| | | 299 | | public void Dispose() |
| | | 300 | | { |
| | 44 | 301 | | lock (_disposeLock) |
| | | 302 | | { |
| | 44 | 303 | | if (TransportBindingElement.ErrorHandlingStrategy == KafkaErrorHandlingStrategy.DeadLetterQueue) |
| | | 304 | | { |
| | 2 | 305 | | Producer?.Dispose(); |
| | 2 | 306 | | Producer = null; |
| | | 307 | | } |
| | 44 | 308 | | Consumer?.Dispose(); |
| | 44 | 309 | | Consumer = null; |
| | 44 | 310 | | _cts?.Dispose(); |
| | 44 | 311 | | _mres?.Dispose(); |
| | 43 | 312 | | } |
| | 44 | 313 | | } |
| | | 314 | | |
| | | 315 | | internal class TopicPartitionOffsetTracker |
| | | 316 | | { |
| | 10 | 317 | | private readonly ConcurrentDictionary<TopicPartition, SortedDictionary<ConsumeResult<byte[], byte[]>, bool>> _to |
| | | 318 | | private readonly IConsumer<byte[], byte[]> _consumer; |
| | | 319 | | private readonly ConsumerConfig _config; |
| | | 320 | | private readonly ILogger<KafkaTransportPump> _logger; |
| | | 321 | | |
| | 10 | 322 | | public TopicPartitionOffsetTracker(IConsumer<byte[], byte[]> consumer, ConsumerConfig config, ILogger<KafkaTrans |
| | | 323 | | { |
| | 10 | 324 | | _consumer = consumer; |
| | 10 | 325 | | _config = config; |
| | 10 | 326 | | _logger = logger; |
| | 10 | 327 | | } |
| | | 328 | | |
| | | 329 | | public void Received(ConsumeResult<byte[], byte[]> consumeResult) |
| | | 330 | | { |
| | 443 | 331 | | SortedDictionary<ConsumeResult<byte[], byte[]>, bool> sortedDictionary = |
| | 443 | 332 | | _topicPartitions.GetOrAdd(consumeResult.TopicPartition, new SortedDictionary<ConsumeResult<byte[], byte[ |
| | 443 | 333 | | lock (sortedDictionary) |
| | | 334 | | { |
| | 443 | 335 | | sortedDictionary.Add(consumeResult, false); |
| | 443 | 336 | | } |
| | 443 | 337 | | } |
| | | 338 | | |
| | | 339 | | public void MarkAsProcessed(ConsumeResult<byte[], byte[]> consumeResult) |
| | | 340 | | { |
| | 443 | 341 | | ConsumeResult<byte[], byte[]> highestConsumeResult = null; |
| | 443 | 342 | | SortedDictionary<ConsumeResult<byte[], byte[]>, bool> sortedDictionary = _topicPartitions[consumeResult.Topi |
| | 443 | 343 | | lock (sortedDictionary) |
| | | 344 | | { |
| | 443 | 345 | | sortedDictionary[consumeResult] = true; |
| | | 346 | | KeyValuePair<ConsumeResult<byte[], byte[]>, bool> first; |
| | 886 | 347 | | while (sortedDictionary.Count > 0 && (first = sortedDictionary.First()).Value) |
| | | 348 | | { |
| | 443 | 349 | | highestConsumeResult = first.Key; |
| | 443 | 350 | | sortedDictionary.Remove(first.Key); |
| | | 351 | | } |
| | | 352 | | |
| | 443 | 353 | | if (highestConsumeResult != null) |
| | | 354 | | { |
| | 397 | 355 | | if (_config.EnableAutoCommit == false) |
| | | 356 | | { |
| | 102 | 357 | | _consumer.Commit(highestConsumeResult); |
| | 102 | 358 | | _logger.LogDebug("Commit {topicPartitionOffset}", |
| | 102 | 359 | | highestConsumeResult.TopicPartitionOffset); |
| | | 360 | | } |
| | 295 | 361 | | else if (_config.EnableAutoOffsetStore == false) |
| | | 362 | | { |
| | 295 | 363 | | _consumer.StoreOffset(highestConsumeResult); |
| | 295 | 364 | | _logger.LogDebug("StoreOffsets {topicPartitionOffset}", |
| | 295 | 365 | | highestConsumeResult.TopicPartitionOffset); |
| | | 366 | | } |
| | | 367 | | } |
| | 341 | 368 | | } |
| | 443 | 369 | | } |
| | | 370 | | |
| | | 371 | | private class ConsumeResultComparer : IComparer<ConsumeResult<byte[], byte[]>> |
| | | 372 | | { |
| | 444 | 373 | | public static ConsumeResultComparer Default { get; } = new(); |
| | | 374 | | |
| | | 375 | | public int Compare(ConsumeResult<byte[], byte[]> x, ConsumeResult<byte[], byte[]> y) |
| | | 376 | | { |
| | 1586 | 377 | | Fx.AssertAndThrow(x.TopicPartition == y.TopicPartition, "ConsumeResult instances must be from the same T |
| | 1586 | 378 | | return x.Offset.Value.CompareTo(y.Offset.Value); |
| | | 379 | | } |
| | | 380 | | } |
| | | 381 | | } |
| | | 382 | | } |