Path: redb-route/redb.Route.Firebase/Storage/FirebaseStorageConsumer.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.Firebase/Storage/FirebaseStorageConsumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Google.Cloud.Storage.V1;
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.Firebase;
///
/// Firebase Storage consumer — polls a bucket for objects using ListObjectsAsync.
/// Extends for graceful two-CTS shutdown.
/// Supports prefix/include/exclude filtering, idempotency, delete-after-read,
/// and move-after-read (copy + delete).
///
internal sealed class FirebaseStorageConsumer : DrainableConsumer
{
private readonly FirebaseStorageEndpoint _endpoint;
private readonly FirebaseStorageEndpointOptions _options;
private StorageClient? _client;
private const int MaxIdempotentEntries = 10_000;
private ConcurrentDictionary? _currentIdempotentRepo;
private ConcurrentDictionary? _previousIdempotentRepo;
private readonly bool _idempotent;
// 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;
private readonly Regex? _includeRegex;
private readonly Regex? _excludeRegex;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"fbstorage://{_endpoint.BucketName}";
internal FirebaseStorageConsumer(FirebaseStorageEndpoint endpoint, IProcessor processor,
FirebaseStorageEndpointOptions options) : base(processor)
{
_endpoint = endpoint;
_options = options;
if (options.Idempotent)
{
_idempotent = true;
_currentIdempotentRepo = 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.CreateBucketAsync(_endpoint.RequireProjectId(), _endpoint.BucketName,
cancellationToken: ct).ConfigureAwait(false);
}
catch (Google.GoogleApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.Conflict)
{
// already exists
}
}
}
///
protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
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, "Firebase Storage consumer poll error on bucket {Bucket}",
_endpoint.BucketName);
_endpoint.RecordError(ex);
}
try
{
await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (pollCt.IsCancellationRequested)
{
break;
}
}
}
private async Task PollBucketAsync(CancellationToken ct)
{
var prefix = _options.Prefix ?? _endpoint.ObjectPrefix;
var objects = _client!.ListObjectsAsync(_endpoint.BucketName, prefix);
var processed = 0;
// Double-buffer eviction: when current fills up, rotate to previous
// and start fresh — retains up to 2×MaxIdempotentEntries of history.
if (_idempotent && _currentIdempotentRepo!.Count > MaxIdempotentEntries)
{
_previousIdempotentRepo = _currentIdempotentRepo;
_currentIdempotentRepo = new ConcurrentDictionary();
}
await foreach (var obj in objects.ConfigureAwait(false))
{
if (ct.IsCancellationRequested || processed >= _options.MaxMessagesPerPoll)
break;
// Filter by include/exclude
if (_includeRegex is not null && !_includeRegex.IsMatch(obj.Name))
continue;
if (_excludeRegex is not null && _excludeRegex.IsMatch(obj.Name))
continue;
// Idempotency: check only — the "seen" mark is written after a SUCCESSFUL
// exchange, so a failed object is offered again on the next poll.
if (_idempotent
&& (_currentIdempotentRepo!.ContainsKey(obj.Name)
|| _previousIdempotentRepo?.ContainsKey(obj.Name) == true))
continue;
if (_sharedRepo is not null
&& await _sharedRepo.Contains(SharedKey(obj.Name), ct).ConfigureAwait(false))
continue;
// Named repo: two-phase claim (Add → process → Confirm / Remove), same as the
// route-level EIP — a concurrent consumer cannot take the same object twice.
if (_sharedRepo is not null
&& !await _sharedRepo.Add(SharedKey(obj.Name), ct).ConfigureAwait(false))
continue;
bool success;
try
{
var exchange = await CreateExchange(obj, ct).ConfigureAwait(false);
success = await ProcessExchangeAsync(exchange, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
// Download/exchange creation failed — the object was never delivered:
// no post-processing, no idempotent mark, retry on the next poll.
Logger?.LogError(ex, "Firebase Storage: error reading object {Object}", obj.Name);
_endpoint.RecordError(ex);
await ReleaseSharedClaimAsync(obj.Name, ct).ConfigureAwait(false);
processed++;
continue;
}
try
{
if (success)
{
if (_idempotent)
_currentIdempotentRepo!.TryAdd(obj.Name, true);
if (_sharedRepo is not null)
await _sharedRepo.Confirm(SharedKey(obj.Name), ct).ConfigureAwait(false);
await PostProcessObject(obj, ct).ConfigureAwait(false);
}
else
{
await ReleaseSharedClaimAsync(obj.Name, ct).ConfigureAwait(false);
if (_options.MoveFailed is not null)
await MoveObjectAsync(obj, _options.MoveFailed, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Logger?.LogError(ex, "Firebase Storage: post-processing failed for {Object}", obj.Name);
_endpoint.RecordError(ex);
}
processed++;
}
}
///
/// Runs the exchange through the processor, inside the root span of the object (an object carries no trace
/// context), and reports whether it succeeded. A processing failure must not delete/move the object (data loss):
/// leaves a failure
/// that escaped the pipeline on the exchange too, so an unhandled exchange.Exception is the failure either way.
/// A rollback-only exchange (.RollbackAll()) is a failure as well
/// (): the object stays, or goes to moveFailed.
///
private async Task ProcessExchangeAsync(Exchange exchange, CancellationToken ct)
{
using var span = RouteTelemetryExtensions.StartConsumerSpan