|
| 1 | +using Confluent.Kafka; |
| 2 | +using Confluent.Kafka.Admin; |
| 3 | +using EnterpriseIntegration.Channels; |
| 4 | +using EnterpriseIntegration.Message; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | + |
| 7 | +namespace EnterpriseIntegration.Kafka; |
| 8 | + |
| 9 | +public class KafkaChannel : IMessagingChannel, IDisposable |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Kafka is a highly distributed system, creating a subscription takes time to be synchronized across all nodes. |
| 13 | + /// </summary> |
| 14 | + private const int KafkaSubscriptionDelayInMs = 3_000; |
| 15 | + |
| 16 | + private readonly CancellationTokenSource _cancellationTokenSource = new(); |
| 17 | + |
| 18 | + private readonly Lazy<IProducer<string, byte[]>> _producer; |
| 19 | + |
| 20 | + private readonly Lazy<IConsumer<string, byte[]>> _consumer; |
| 21 | + |
| 22 | + private readonly KafkaChannelSettings _settings; |
| 23 | + |
| 24 | + private readonly IMessageMapper<ConsumeResult<string, byte[]>, KafkaMessage> _mapper; |
| 25 | + |
| 26 | + private readonly ILogger<KafkaChannel> _logger; |
| 27 | + |
| 28 | + private readonly Task? _topicCreationTask; |
| 29 | + |
| 30 | + private bool _topicCreated = true; |
| 31 | + |
| 32 | + public ChannelId ChannelId { get; } |
| 33 | + |
| 34 | + public KafkaChannel(ChannelId id, IKafkaConnectionProvider connectionProvider, KafkaChannelSettings settings, IMessageMapper<ConsumeResult<string, byte[]>, KafkaMessage> mapper, ILogger<KafkaChannel> logger) |
| 35 | + { |
| 36 | + ChannelId = id; |
| 37 | + _settings = settings; |
| 38 | + _mapper = mapper; |
| 39 | + _logger = logger; |
| 40 | + _producer = new Lazy<IProducer<string, byte[]>>(connectionProvider.CreateProducer); |
| 41 | + _consumer = new Lazy<IConsumer<string, byte[]>>(connectionProvider.CreateConsumer); |
| 42 | + |
| 43 | + if (settings.EnsureCreated) |
| 44 | + { |
| 45 | + _topicCreated = false; |
| 46 | + _topicCreationTask = EnsureTopicCreationAsync(connectionProvider); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private async Task EnsureTopicCreationAsync(IKafkaConnectionProvider connectionProvider) |
| 51 | + { |
| 52 | + using var adminClient = connectionProvider.CreateAdminClient(); |
| 53 | + |
| 54 | + var metaData = adminClient.GetMetadata(TimeSpan.FromSeconds(30)); |
| 55 | + if (!metaData.Topics.Any(t => t.Topic.Equals(_settings.TopicName, StringComparison.OrdinalIgnoreCase))) |
| 56 | + { |
| 57 | + await adminClient.CreateTopicsAsync(new List<TopicSpecification> { new TopicSpecification { Name = _settings.TopicName, NumPartitions = 1, ReplicationFactor = 1, } }); |
| 58 | + _topicCreated = true; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + public async Task Send(IMessage message) |
| 63 | + { |
| 64 | + if (!_topicCreated && _topicCreationTask != null) |
| 65 | + { |
| 66 | + await _topicCreationTask; |
| 67 | + } |
| 68 | + |
| 69 | + _logger.LogInformation("Produce Message(id:{id}) for Channel:{channelId} to topic:{topic}", message.MessageHeaders.Id, ChannelId, _settings.TopicName); |
| 70 | + await _producer.Value.ProduceAsync(_settings.TopicName, await _mapper.Map(message)); |
| 71 | + } |
| 72 | + |
| 73 | + /// <summary> |
| 74 | + /// Reads messages from a kafka topic. |
| 75 | + /// </summary> |
| 76 | + /// <typeparam name="T"></typeparam> |
| 77 | + /// <param name="subscriber"></param> |
| 78 | + /// <returns></returns> |
| 79 | + public async Task Subscribe<T>(Func<IMessage<T>, Task> subscriber) |
| 80 | + { |
| 81 | + if (!_topicCreated && _topicCreationTask != null) |
| 82 | + { |
| 83 | + await _topicCreationTask; |
| 84 | + } |
| 85 | + |
| 86 | + _logger.LogInformation("Created subscription for channel:{channelId} on topic:{topic}", ChannelId, _settings.TopicName); |
| 87 | + _consumer.Value.Subscribe(_settings.TopicName); |
| 88 | + ThreadPool.QueueUserWorkItem(async _ => await ContinuousConsume(subscriber)); |
| 89 | + await Task.Delay(KafkaSubscriptionDelayInMs); |
| 90 | + } |
| 91 | + |
| 92 | + public void Dispose() |
| 93 | + { |
| 94 | + GC.SuppressFinalize(this); |
| 95 | + if (_consumer.IsValueCreated) |
| 96 | + { |
| 97 | + _consumer.Value.Unsubscribe(); |
| 98 | + _consumer.Value.Close(); |
| 99 | + _consumer.Value.Dispose(); |
| 100 | + } |
| 101 | + |
| 102 | + if (_producer.IsValueCreated) |
| 103 | + { |
| 104 | + _producer.Value.Dispose(); |
| 105 | + } |
| 106 | + |
| 107 | + _cancellationTokenSource.Cancel(); |
| 108 | + } |
| 109 | + |
| 110 | + private async Task ContinuousConsume<T>(Func<IMessage<T>, Task> subscriber) |
| 111 | + { |
| 112 | + while (!_cancellationTokenSource.Token.IsCancellationRequested) |
| 113 | + { |
| 114 | + try |
| 115 | + { |
| 116 | + _logger.LogInformation("Consumer starting."); |
| 117 | + IMessage<T> message = await _mapper.Map<T>(_consumer.Value.Consume(_cancellationTokenSource.Token)); |
| 118 | + _logger.LogInformation("Received Message(id:{id}) for Channel:{channelId} from topic:{topic}", message.MessageHeaders.Id, ChannelId, _settings.TopicName); |
| 119 | + |
| 120 | + await subscriber(message); |
| 121 | + _logger.LogInformation("Processed Message(id:{id})", message.MessageHeaders.Id); |
| 122 | + } |
| 123 | + catch (ObjectDisposedException) |
| 124 | + { |
| 125 | + if (!_cancellationTokenSource.Token.IsCancellationRequested) |
| 126 | + { |
| 127 | + return; |
| 128 | + } |
| 129 | + |
| 130 | + throw; |
| 131 | + } |
| 132 | + catch (OperationCanceledException) |
| 133 | + { |
| 134 | + if (!_cancellationTokenSource.Token.IsCancellationRequested) |
| 135 | + { |
| 136 | + return; |
| 137 | + } |
| 138 | + |
| 139 | + throw; |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | +} |
0 commit comments