Skip to content

Async consumer #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions src/kafka-net/Common/AsyncCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,22 @@ public class AsyncCollection<T>
{
private readonly object _lock = new object();
private readonly AsyncManualResetEvent _dataAvailableEvent = new AsyncManualResetEvent();
private readonly ConcurrentBag<T> _bag = new ConcurrentBag<T>();
private readonly IProducerConsumerCollection<T> _collection;
private long _dataInBufferCount = 0;

public int Count
public AsyncCollection()
{
_collection = new ConcurrentBag<T>();
}

public AsyncCollection(IProducerConsumerCollection<T> collection)
{
_collection = collection;
}

public int Count
{
get { return _bag.Count + (int)Interlocked.Read(ref _dataInBufferCount); }
get { return _collection.Count + (int)Interlocked.Read(ref _dataInBufferCount); }
}

public bool IsCompleted { get; private set; }
Expand All @@ -37,7 +47,7 @@ public void Add(T data)
throw new ObjectDisposedException("AsyncCollection has been marked as complete. No new documents can be added.");
}

_bag.Add(data);
_collection.TryAdd(data);
TriggerDataAvailability();
}

Expand Down Expand Up @@ -88,7 +98,7 @@ public async Task<List<T>> TakeAsync(int count, TimeSpan timeout, CancellationTo
public void DrainAndApply(Action<T> appliedFunc)
{
T data;
while (_bag.TryTake(out data))
while (_collection.TryTake(out data))
{
appliedFunc(data);
}
Expand All @@ -99,7 +109,7 @@ public void DrainAndApply(Action<T> appliedFunc)
public IEnumerable<T> Drain()
{
T data;
while (_bag.TryTake(out data))
while (_collection.TryTake(out data))
{
yield return data;
}
Expand All @@ -111,19 +121,19 @@ public bool TryTake(out T data)
{
try
{
return _bag.TryTake(out data);
return _collection.TryTake(out data);
}
finally
{
if (_bag.IsEmpty) TriggerDataAvailability();
if (_collection.Count == 0) TriggerDataAvailability();
}
}

private void TriggerDataAvailability()
{
lock (_lock)
{
if (_bag.IsEmpty)
if (_collection.Count == 0)
{
_dataAvailableEvent.Reset();
}
Expand Down
80 changes: 69 additions & 11 deletions src/kafka-net/Consumer.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using KafkaNet.Common;
using KafkaNet.Model;
using KafkaNet.Protocol;

Expand All @@ -18,7 +20,8 @@ namespace KafkaNet
public class Consumer : IMetadataQueries, IDisposable
{
private readonly ConsumerOptions _options;
private readonly BlockingCollection<Message> _fetchResponseQueue;
private readonly AsyncCollection<Message> _fetchResponseCollection;
private readonly SemaphoreSlim _boundedCapacitySemaphore;
private readonly CancellationTokenSource _disposeToken = new CancellationTokenSource();
private readonly ConcurrentDictionary<int, Task> _partitionPollingIndex = new ConcurrentDictionary<int, Task>();
private readonly ConcurrentDictionary<int, long> _partitionOffsetIndex = new ConcurrentDictionary<int, long>();
Expand All @@ -31,9 +34,10 @@ public class Consumer : IMetadataQueries, IDisposable
public Consumer(ConsumerOptions options, params OffsetPosition[] positions)
{
_options = options;
_fetchResponseQueue = new BlockingCollection<Message>(_options.ConsumerBufferSize);
_fetchResponseCollection = new AsyncCollection<Message>(new ConcurrentQueue<Message>());
_boundedCapacitySemaphore = new SemaphoreSlim(_options.ConsumerBufferSize, _options.ConsumerBufferSize);
_metadataQueries = new MetadataQueries(_options.Router);

SetOffsetPosition(positions);
}

Expand All @@ -50,7 +54,60 @@ public IEnumerable<Message> Consume(CancellationToken? cancellationToken = null)
{
_options.Log.DebugFormat("Consumer: Beginning consumption of topic: {0}", _options.Topic);
EnsurePartitionPollingThreads();
return _fetchResponseQueue.GetConsumingEnumerable(cancellationToken ?? CancellationToken.None);
// need a separate method with yield, otherwise EnsurePartitionPollingThreads() is not called until enumeration, e.g. ToArray()
return DoConsume(cancellationToken);
}

private IEnumerable<Message> DoConsume(CancellationToken? cancellationToken = null)
{
while (true)
{
try
{
// blocking wait for data
_fetchResponseCollection.OnHasDataAvailable(cancellationToken ?? CancellationToken.None).Wait();
}
catch (AggregateException e)
{
if (e.InnerException is TaskCanceledException)
{
throw new OperationCanceledException();
}
throw;
}
Message data;
// do not call OnHasDataAvailable if data is available
while (_fetchResponseCollection.TryTake(out data))
{
_boundedCapacitySemaphore.Release();
yield return data;
}
}
}


public async Task<Message> ConsumeNextAsync()
{
return await ConsumeNextAsync(new TimeSpan(int.MaxValue), CancellationToken.None);
}

/// <summary>
/// Pull a next message for consumption asynchronously
/// </summary>
public async Task<Message> ConsumeNextAsync(TimeSpan timeout, CancellationToken token)
{
// this will only iterlocked.increment/decrement(_ensureOneThread) and compare to 1 on each call
EnsurePartitionPollingThreads();

if (_fetchResponseCollection.IsCompleted)
{
var tcs = new TaskCompletionSource<Message>();
tcs.SetCanceled();
return await tcs.Task;
}
var result = (await _fetchResponseCollection.TakeAsync(1, timeout, token)).Single();
_boundedCapacitySemaphore.Release();
return result;
}

/// <summary>
Expand Down Expand Up @@ -139,11 +196,11 @@ private Task ConsumeTopicPartitionAsync(string topic, int partitionId)
var fetches = new List<Fetch> { fetch };

var fetchRequest = new FetchRequest
{
MaxWaitTime = (int)Math.Min((long)int.MaxValue, _options.MaxWaitTimeForMinimumBytes.TotalMilliseconds),
MinBytes = _options.MinimumBytes,
Fetches = fetches
};
{
MaxWaitTime = (int)Math.Min((long)int.MaxValue, _options.MaxWaitTimeForMinimumBytes.TotalMilliseconds),
MinBytes = _options.MinimumBytes,
Fetches = fetches
};

//make request and post to queue
var route = _options.Router.SelectBrokerRoute(topic, partitionId);
Expand All @@ -160,7 +217,8 @@ private Task ConsumeTopicPartitionAsync(string topic, int partitionId)

foreach (var message in response.Messages)
{
_fetchResponseQueue.Add(message, _disposeToken.Token);
await _boundedCapacitySemaphore.WaitAsync(_disposeToken.Token);
_fetchResponseCollection.Add(message);

if (_disposeToken.IsCancellationRequested) return;
}
Expand All @@ -174,7 +232,7 @@ private Task ConsumeTopicPartitionAsync(string topic, int partitionId)
}

//no message received from server wait a while before we try another long poll
Thread.Sleep(_options.BackoffInterval);
await Task.Delay(_options.BackoffInterval);
}
catch (BufferUnderRunException ex)
{
Expand Down
38 changes: 38 additions & 0 deletions src/kafka-tests/Integration/ProducerConsumerIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,44 @@ public void ConsumerShouldConsumeInSameOrderAsProduced()
}
}


[Test]
public void AsyncConsumerShouldConsumeInSameOrderAsProduced()
{
var expected = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" };
var testId = Guid.NewGuid().ToString();

using (var router = new BrokerRouter(new KafkaOptions(IntegrationConfig.IntegrationUri)))
using (var producer = new Producer(router))
{

var offsets = producer.GetTopicOffsetAsync(IntegrationConfig.IntegrationTopic).Result;

using (var consumer = new Consumer(new ConsumerOptions(IntegrationConfig.IntegrationTopic, router),
offsets.Select(x => new OffsetPosition(x.PartitionId, x.Offsets.Max())).ToArray()))
{

for (int i = 0; i < 20; i++)
{
producer.SendMessageAsync(IntegrationConfig.IntegrationTopic, new[] { new Message(i.ToString(), testId) }).Wait();
}
List<Message> results = new List<Message>();

for (int i = 0; i < 20; i++)
{
results.Add(consumer.ConsumeNextAsync().Result);
}

//ensure the produced messages arrived
Console.WriteLine("Message order: {0}", string.Join(", ", results.Select(x => x.Value.ToUtf8String()).ToList()));

Assert.That(results.Count, Is.EqualTo(20));
Assert.That(results.Select(x => x.Value.ToUtf8String()).ToList(), Is.EqualTo(expected), "Expected the message list in the correct order.");
Assert.That(results.Any(x => x.Key.ToUtf8String() != testId), Is.False);
}
}
}

[Test]
public void ConsumerShouldBeAbleToSeekBackToEarlierOffset()
{
Expand Down