Path: redb-route/redb.Route.S3/S3Consumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.S3/S3Consumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.Telemetry;
namespace redb.Route.S3;
///
/// S3 consumer — polls a bucket for objects using ListObjectsV2.
/// Extends for graceful two-CTS shutdown.
///
/// Supports prefix/include/exclude filtering, sort order, min/max age,
/// idempotency, max-messages-per-poll, delete-after-read, move-after-read
/// with destination bucket/prefix/suffix, and done-file markers.
/// Inspired by Apache Camel aws2-s3 consumer patterns.
///
///
internal sealed class S3Consumer : DrainableConsumer
{
private readonly S3Endpoint _endpoint;
private readonly S3EndpointOptions _options;
private IAmazonS3? _client;
private long _processedCount;
// In-memory idempotent repository with double-buffer eviction (S-6): when current fills
// up it rotates to previous and starts fresh — retains up to 2×MaxIdempotentEntries of
// history instead of growing without bound.
private const int MaxIdempotentEntries = 10_000;
private ConcurrentDictionary? _idempotentRepo;
private ConcurrentDictionary? _previousIdempotentRepo;
// Named repository: the shared IIdempotentRepository contract of the route-level
// IdempotentConsumer EIP — dedup survives consumer restarts (and process restarts with
// a persistent implementation).
private IIdempotentRepository? _sharedRepo;
// Include/Exclude patterns compiled from glob
private readonly Regex? _includeRegex;
private readonly Regex? _excludeRegex;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"s3://{_endpoint.BucketName}";
/// Number of objects processed since start.
internal long ProcessedCount => Interlocked.Read(ref _processedCount);
internal S3Consumer(S3Endpoint endpoint, IProcessor processor, S3EndpointOptions options)
: base(processor)
{
_endpoint = endpoint;
_options = options;
if (options.Idempotent)
_idempotentRepo = new ConcurrentDictionary();
if (!string.IsNullOrEmpty(options.Include))
_includeRegex = GlobToRegex(options.Include);
if (!string.IsNullOrEmpty(options.Exclude))
_excludeRegex = GlobToRegex(options.Exclude);
}
///
protected override async Task OnStarting(CancellationToken ct)
{
_client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
if (!string.IsNullOrEmpty(_options.IdempotentRepository))
{
var context = (_endpoint.Component as ComponentBase)?.Context
?? throw new InvalidOperationException(
$"IdempotentRepository '{_options.IdempotentRepository}' requires a route context " +
"(register the repository with context.AddIdempotentRepository(name, ...)).");
_sharedRepo = context.GetIdempotentRepositoryProvider().Get(_options.IdempotentRepository);
}
if (_options.AutoCreateBucket)
{
try
{
await _client.EnsureBucketExistsAsync(_endpoint.BucketName).ConfigureAwait(false);
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.Conflict)
{
// Already exists
}
}
}
///
protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
// Initial delay
if (_options.InitialDelay > 0)
await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false);
while (!pollCt.IsCancellationRequested)
{
try
{
await PollBucketAsync(processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (pollCt.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Logger?.LogError(ex, "S3 consumer poll error on bucket {Bucket}", _endpoint.BucketName);
_endpoint.RecordError(ex); // with its details, or LastErrorMessage stays empty
}
// Wait between polls
try
{
await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
}
// ═══════════════════════════════════════════════════════════════════
// POLLING
// ═══════════════════════════════════════════════════════════════════
private async Task PollBucketAsync(CancellationToken ct)
{
// If fileName is specified, handle single-file mode
if (!string.IsNullOrEmpty(_options.FileName))
{
await PollSingleFileAsync(ct).ConfigureAwait(false);
return;
}
// Without sorting the listing streams page by page with an early exit at
// MaxMessagesPerPoll — a big bucket no longer costs O(N) memory per poll (S-7).
if (_options.SortBy == S3SortBy.None)
{
await PollStreamingAsync(ct).ConfigureAwait(false);
return;
}
var request = new ListObjectsV2Request
{
BucketName = _endpoint.BucketName,
Prefix = _options.Prefix,
Delimiter = _options.Delimiter,
};
var allObjects = new List();
string? continuationToken = null;
// Paginate through listing — SortBy honestly needs the full list in memory.
do
{
request.ContinuationToken = continuationToken;
var response = await _client!.ListObjectsV2Async(request, ct).ConfigureAwait(false);
foreach (var obj in response.S3Objects ?? [])
{
// Skip folder markers
if (!_options.IncludeFolders && obj.Key.EndsWith('/'))
continue;
allObjects.Add(obj);
}
continuationToken = response.IsTruncated == true ? response.NextContinuationToken : null;
} while (continuationToken != null);
// Apply filters
var eligible = FilterObjects(allObjects);
// Sort
eligible = SortObjects(eligible);
// Apply max-messages-per-poll
if (_options.MaxMessagesPerPoll > 0)
eligible = eligible.Take(_options.MaxMessagesPerPoll).ToList();
if (eligible.Count == 0)
{
if (_options.SendEmptyMessageWhenIdle)
{
var emptyExchange = CreateExchange(null);
await ProcessWithTracking(emptyExchange, ct).ConfigureAwait(false);
}
return;
}
// Process each object
foreach (var obj in eligible)
{
if (ct.IsCancellationRequested)
break;
await ProcessObjectAsync(obj, ct).ConfigureAwait(false);
}
}
///
/// Streaming poll for the unsorted case (S-7): pages are processed as they arrive and the
/// loop exits as soon as MaxMessagesPerPoll eligible objects were handled.
///
private async Task PollStreamingAsync(CancellationToken ct)
{
var request = new ListObjectsV2Request
{
BucketName = _endpoint.BucketName,
Prefix = _options.Prefix,
Delimiter = _options.Delimiter,
};
var processed = 0;
var anyEligible = false;
var now = DateTime.UtcNow;
string? continuationToken = null;
do
{
request.ContinuationToken = continuationToken;
var response = await _client!.ListObjectsV2Async(request, ct).ConfigureAwait(false);
foreach (var obj in response.S3Objects ?? [])
{
if (ct.IsCancellationRequested)
return;
if (!_options.IncludeFolders && obj.Key.EndsWith('/'))
continue;
if (!PassesFilters(obj, now))
continue;
anyEligible = true;
await ProcessObjectAsync(obj, ct).ConfigureAwait(false);
if (_options.MaxMessagesPerPoll > 0 && ++processed >= _options.MaxMessagesPerPoll)
return;
}
continuationToken = response.IsTruncated == true ? response.NextContinuationToken : null;
} while (continuationToken != null);
if (!anyEligible && _options.SendEmptyMessageWhenIdle)
{
var emptyExchange = CreateExchange(null);
await ProcessWithTracking(emptyExchange, ct).ConfigureAwait(false);
}
}
private async Task PollSingleFileAsync(CancellationToken ct)
{
try
{
var metadata = await _client!.GetObjectMetadataAsync(_endpoint.BucketName, _options.FileName, ct)
.ConfigureAwait(false);
var pseudoObj = new S3Object
{
BucketName = _endpoint.BucketName,
Key = _options.FileName,
Size = metadata.ContentLength,
LastModified = metadata.LastModified,
ETag = metadata.ETag,
};
// Idempotency: check only — the mark is written after success in ProcessObjectAsync (S-2)
if (IsAlreadySeen(pseudoObj))
return;
await ProcessObjectAsync(pseudoObj, ct).ConfigureAwait(false);
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// File doesn't exist yet — skip
}
}
private async Task ProcessObjectAsync(S3Object obj, CancellationToken ct)
{
// Named repo: two-phase claim BEFORE the download — Add is atomic, so a
// concurrent consumer cannot take the same object twice; released on any failure.
if (_sharedRepo is not null
&& !await _sharedRepo.Add(BuildIdempotentKey(obj), ct).ConfigureAwait(false))
return;
try
{
await ProcessObjectCoreAsync(obj, ct).ConfigureAwait(false);
}
catch
{
await ReleaseSharedClaimAsync(obj, ct).ConfigureAwait(false);
throw;
}
}
private async Task ProcessObjectCoreAsync(S3Object obj, CancellationToken ct)
{
// Done file check
if (!string.IsNullOrEmpty(_options.DoneFileName))
{
var doneKey = ResolveDoneFileName(obj.Key);
try
{
await _client!.GetObjectMetadataAsync(_endpoint.BucketName, doneKey, ct).ConfigureAwait(false);
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
Logger?.LogDebug("S3: Skipping {Key} — done file {DoneKey} not found", obj.Key, doneKey);
// Release the claim: the object must be re-offered once the done file appears.
await ReleaseSharedClaimAsync(obj, ct).ConfigureAwait(false);
return;
}
}
// Download object. IncludeBody=false (and IgnoreBody) mean "no content download" —
// no GET is issued at all; previously a raw ResponseStream leaked into the body (S-8).
object? body = null;
GetObjectResponse? getResponse = null;
if (!_options.IgnoreBody && (_options.StreamBody || _options.IncludeBody))
{
var getRequest = new GetObjectRequest
{
BucketName = _endpoint.BucketName,
Key = obj.Key,
};
getResponse = await _client!.GetObjectAsync(getRequest, ct).ConfigureAwait(false);
if (_options.StreamBody)
{
// Ownership: the stream goes into the exchange; Exchange.DisposeAsync closes
// it, which releases the HTTP connection. The response object must NOT be
// disposed here — that would close the stream we just handed over (S-8).
body = getResponse.ResponseStream;
}
else
{
try
{
using var ms = new MemoryStream();
await getResponse.ResponseStream.CopyToAsync(ms, ct).ConfigureAwait(false);
body = ms.ToArray(); // BytesIn is counted by the core around the routed consumer
}
catch
{
getResponse.Dispose();
throw;
}
}
}
// Create exchange
var exchange = CreateExchange(body);
SetConsumerHeaders(exchange, obj, getResponse);
// Buffered path: the response is fully read and its headers copied — release the
// connection now instead of leaking it until GC (S-8).
if (getResponse is not null && !_options.StreamBody)
getResponse.Dispose();
// Process (MessagesIn is counted by the core StatisticsProcessor - ownership audit)
var success = await ProcessExchangeAsync(exchange, obj.Key, ct).ConfigureAwait(false);
Interlocked.Increment(ref _processedCount);
if (success)
{
// Idempotent mark only AFTER success (S-2): a failed object and objects beyond
// MaxMessagesPerPoll must be offered again on the next poll.
MarkSeen(obj);
if (_sharedRepo is not null)
await _sharedRepo.Confirm(BuildIdempotentKey(obj), ct).ConfigureAwait(false);
await PostProcessAsync(obj, ct).ConfigureAwait(false);
}
else
{
await ReleaseSharedClaimAsync(obj, ct).ConfigureAwait(false);
}
}
/// Releases the two-phase claim so a failed object is offered again.
private async Task ReleaseSharedClaimAsync(S3Object obj, CancellationToken ct)
{
if (_sharedRepo is null) return;
try
{
await _sharedRepo.Remove(BuildIdempotentKey(obj), ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Logger?.LogWarning(ex,
"S3: releasing idempotent claim for {Key} failed — the object stays marked until manual cleanup",
obj.Key);
}
}
///
/// Runs the exchange through the processor with inflight tracking and reports whether it
/// succeeded. A processing failure must not delete/move the object (S-1), so unlike
/// the outcome is observed here:
/// a raw throw (no error handler took the exchange), an unhandled exchange.Exception
/// set by the pipeline and a rollback-only exchange (.RollbackAll()) all count as failure
/// (), as in Camel aws2-s3, which deletes or
/// moves the object only when the exchange commits.
///
private async Task ProcessExchangeAsync(IExchange exchange, string key, CancellationToken ct)
{
// An object carries no trace context: its span is a root, never a child of the activity the poll runs under.
using var span = RouteTelemetryExtensions.StartConsumerSpan