forked from gigya/Orleans.KafkaStreamProvider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KafkaQueueAdapterReceiver.cs
216 lines (183 loc) · 9.32 KB
/
KafkaQueueAdapterReceiver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using KafkaNet.Interfaces;
using KafkaNet.Protocol;
using Metrics;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
namespace Orleans.KafkaStreamProvider.KafkaQueue
{
public class KafkaQueueAdapterReceiver : IQueueAdapterReceiver
{
private Task _currentCommitTask;
private readonly IManualConsumer _consumer;
private readonly IKafkaBatchFactory _factory;
private readonly Logger _logger;
private readonly KafkaStreamProviderOptions _options;
// Metrics
private static readonly Meter MeterConsumedMessagesPerSecond = Metric.Context("KafkaStreamProvider").Meter("Consumed Messages Per Second", Unit.Events);
private static readonly Histogram HistogramConsumedMessagesPerFetch = Metric.Context("KafkaStreamProvider").Histogram("Consumed Messages Per Fetch", Unit.Custom("Messages"));
private static readonly Counter CounterActiveReceivers = Metric.Context("KafkaStreamProvider").Counter("Active Receivers", Unit.Custom("Receivers"));
private static readonly Timer TimerTimeToGetMessageFromKafka = Metric.Context("KafkaStreamProvider").Timer("Time To Get Message From Kafka", Unit.Custom("Fetches"));
private static readonly Timer TimerTimeToCommitOffset = Metric.Context("KafkaStreamProvider").Timer("Time To Commit Offset", Unit.Custom("Commits"));
private readonly Counter _counterCurrentOffset;
public QueueId Id { get; }
private long _currentOffset;
public long CurrentOffset
{
get { return _currentOffset; }
private set
{
_currentOffset = value;
_counterCurrentOffset?.Increment(value - _currentOffset);
}
}
public KafkaQueueAdapterReceiver(QueueId queueId, IManualConsumer consumer, KafkaStreamProviderOptions options,
IKafkaBatchFactory factory, Logger logger)
{
// input checks
if (queueId == null) throw new ArgumentNullException(nameof(queueId));
if (consumer == null) throw new ArgumentNullException(nameof(consumer));
if (factory == null) throw new ArgumentNullException(nameof(factory));
if (options == null) throw new ArgumentNullException(nameof(options));
if (logger == null) throw new ArgumentNullException(nameof(logger));
_counterCurrentOffset = Metric.Context("KafkaStreamProvider").Counter($"CurrentOffset queueId:({queueId.GetNumericId()})", unit: Unit.Custom("Log"));
_options = options;
Id = queueId;
_consumer = consumer;
_factory = factory;
_logger = logger;
}
public async Task Initialize(TimeSpan timeout)
{
bool shouldCreate = false;
try
{
if (_options.ShouldInitWithLastOffset)
{
CurrentOffset = await _consumer.FetchLastOffset();
_logger.Verbose("KafkaQueueAdapterReceiver - Initialized with latest offset. Offset is {0}", CurrentOffset);
}
else
{
CurrentOffset = await _consumer.FetchOffset(_options.ConsumerGroupName);
_logger.Verbose("KafkaQueueAdapterReceiver - Initialized with ConsumerGroupOffset offset. ConsumerGroup is {0} Offset is {1}", _options.ConsumerGroupName, CurrentOffset);
}
}
catch (KafkaApplicationException ex)
{
// This is the error kafka returns when the consumer group doesn't exist
if (ex.ErrorCode == (int)ErrorResponseCode.UnknownTopicOrPartition)
{
shouldCreate = true;
}
else
{
throw;
}
}
if (shouldCreate)
{
CurrentOffset = await _consumer.FetchLastOffset();
await _consumer.UpdateOrCreateOffset(_options.ConsumerGroupName, CurrentOffset);
_logger.Verbose("KafkaQueueAdapterReceiver - Offset was not found for ConsumerGroup {0}, saved the latest offset for the ConsumerGroup. Offset is {1}", _options.ConsumerGroupName, CurrentOffset);
}
CounterActiveReceivers.Increment();
}
public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount)
{
try
{
Task<IEnumerable<Message>> fetchingTask;
IList<IBatchContainer> batches = new List<IBatchContainer>();
using (TimerTimeToGetMessageFromKafka.NewContext(Id.ToString()))
{
fetchingTask = _consumer.FetchMessages(maxCount, CurrentOffset);
await Task.WhenAny(fetchingTask, Task.Delay(_options.ReceiveWaitTimeInMs));
}
// Checking that the task completed successfully
if (!fetchingTask.IsCompleted)
{
_logger.Warn((int)KafkaErrorCodes.KafkaStreamProviderBase,
"KafkaQueueAdapterReceiver - Fetching operation was not completed, tried to fetch {0} messages from offest {1}",
maxCount, CurrentOffset);
return batches;
}
if (fetchingTask.IsFaulted && fetchingTask.Exception != null)
{
_logger.Warn((int)KafkaErrorCodes.KafkaStreamProviderBase,
"KafkaQueueAdapterReceiver - Fetching messages from kafka failed, tried to fetch {0} messages from offest {1}",
maxCount, CurrentOffset);
throw fetchingTask.Exception;
}
if (fetchingTask.Result == null)
{
return batches;
}
var messages = fetchingTask.Result.ToList();
batches = messages.Select(m => _factory.FromKafkaMessage(m, m.Meta.Offset)).ToList();
// No batches, we are done here..
if (batches.Count <= 0) return batches;
_logger.Verbose("KafkaQueueAdapterReceiver - Pulled {0} messages for queue number {1}", batches.Count, Id.GetNumericId());
CurrentOffset += batches.Count;
// Taking a bit of metrics
MeterConsumedMessagesPerSecond.Mark(Id.ToString(), 1);
HistogramConsumedMessagesPerFetch.Update(batches.Count, Id.ToString());
return batches;
}
catch (BufferUnderRunException)
{
// This case the next message in the queue is too big for us to read, so we skip it
_logger.Error((int)KafkaErrorCodes.KafkaStreamProviderBase, $"KafkaQueueAdapterReceiver - A message in the Kafka queue was too big to pull, skipping over it. offset was {CurrentOffset}");
CurrentOffset++;
return new List<IBatchContainer>();
}
}
private async Task CommitOffset(long offsetToCommit)
{
Task commitTask;
using (TimerTimeToCommitOffset.NewContext())
{
commitTask = _consumer.UpdateOrCreateOffset(_options.ConsumerGroupName, offsetToCommit);
await Task.WhenAny(commitTask, Task.Delay(_options.ReceiveWaitTimeInMs));
}
if (!commitTask.IsCompleted)
{
var innerException = commitTask.IsFaulted
? (Exception)commitTask.Exception
: new TimeoutException("Commit operation timed out");
var newException = new KafkaStreamProviderException("Commit offset operation has failed", innerException);
_logger.Error((int)KafkaErrorCodes.KafkaApplicationError, String.Format(
"KafkaQueueAdapterReceiver - Commit offset operation has failed. ConsumerGroup is {0}, offset is {1}",
_options.ConsumerGroupName, offsetToCommit), newException);
throw new KafkaStreamProviderException();
}
_logger.Verbose(
"KafkaQueueAdapterReceiver - Commited an offset to the ConsumerGroup. ConsumerGroup is {0}, offset is {1}",
_options.ConsumerGroupName, offsetToCommit);
}
public async Task Shutdown(TimeSpan timeout)
{
if (_currentCommitTask != null)
{
await Task.WhenAny(_currentCommitTask, Task.Delay(timeout));
_currentCommitTask = null;
_logger.Verbose("KafkaQueueAdapterReceiver - The receiver had finished a commit and was shutted down");
}
CounterActiveReceivers.Decrement();
}
public async Task MessagesDeliveredAsync(IList<IBatchContainer> messages)
{
// Finding the highest offset
if (messages.Any())
{
var highestOffset = messages.Max(b => (b.SequenceToken as EventSequenceToken).SequenceNumber);
// We increment the highest offest since the offest commit represents the next message to be handled.
await CommitOffset(highestOffset + 1);
}
}
}
}