Path: redb-route/tests/redb.Route.Tests.Firebase/Integration/StorageConsumerFailureTests.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/tests/redb.Route.Tests.Firebase/Integration/StorageConsumerFailureTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using Google.Cloud.Storage.V1;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Firebase;
using Xunit.Abstractions;
namespace redb.Route.Tests.Firebase.Integration;
///
/// Failure semantics of the Storage polling consumer against fake-gcs-server
/// (docker-compose.tests.yml, container firebase-gcs on :4443).
/// An exchange that failed processing must
/// never lose the object — no delete, no move to the success pocket, no idempotent
/// "seen" mark; with MoveFailed set the object is quarantined instead.
///
[Trait("Category", "Integration")]
[Collection("FirebaseEnvSensitive")]
public sealed class StorageConsumerFailureTests : IAsyncLifetime
{
private const string ProjectId = "demo-redb";
private const string GcsEndpoint = "http://localhost:4443/storage/v1/";
private const string GcsBaseUri = "http://localhost:4443";
private const string TestBucket = "consumer-failure-bucket";
private readonly ITestOutputHelper _output;
private StorageClient? _rawGcs;
private FirebaseCredentialProvider? _prodProvider;
private string? _prevOldEmuVar;
private string? _prevNewEmuVar;
public StorageConsumerFailureTests(ITestOutputHelper output) => _output = output;
public async Task InitializeAsync()
{
// STORAGE_EMULATOR_HOST satisfies Validate() AND routes the production provider
// to fake-gcs (the SDK uses the value verbatim as base URI — full path required).
_prevOldEmuVar = Environment.GetEnvironmentVariable("FIREBASE_STORAGE_EMULATOR_HOST");
_prevNewEmuVar = Environment.GetEnvironmentVariable("STORAGE_EMULATOR_HOST");
Environment.SetEnvironmentVariable("STORAGE_EMULATOR_HOST", GcsEndpoint);
_rawGcs = new StorageClientBuilder
{
BaseUri = GcsEndpoint,
UnauthenticatedAccess = true,
}.Build();
_prodProvider = new FirebaseCredentialProvider();
try
{
await _rawGcs.CreateBucketAsync(ProjectId, TestBucket);
}
catch (Google.GoogleApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.Conflict)
{
// already exists
}
}
public Task DisposeAsync()
{
Environment.SetEnvironmentVariable("FIREBASE_STORAGE_EMULATOR_HOST", _prevOldEmuVar);
Environment.SetEnvironmentVariable("STORAGE_EMULATOR_HOST", _prevNewEmuVar);
_prodProvider?.Dispose();
_rawGcs?.Dispose();
return Task.CompletedTask;
}
// ═══════════════════════════════════════════════════════════════════
// Delete/move must not happen after failed processing
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task DeleteAfterRead_FailedProcessing_ObjectSurvives()
{
var prefix = $"fail-del-{Guid.NewGuid():N}/";
var name = await SeedObjectAsync(prefix, "victim.txt");
var consumer = CreateConsumer(
$"prefix={prefix}&delay=300&initialDelay=100&deleteAfterRead=true&includeBody=false",
new ThrowingProcessor());
await consumer.Start();
await Task.Delay(2000);
await consumer.Stop();
var exists = await ObjectExistsAsync(name);
exists.Should().BeTrue("an object whose processing failed must not be deleted");
}
[Fact]
public async Task MoveAfterRead_FailedProcessing_ObjectNotMoved()
{
var prefix = $"fail-move-{Guid.NewGuid():N}/";
var name = await SeedObjectAsync(prefix, "victim.txt");
var consumer = CreateConsumer(
$"prefix={prefix}&delay=300&initialDelay=100&moveAfterRead=processed/&includeBody=false",
new ThrowingProcessor());
await consumer.Start();
await Task.Delay(2000);
await consumer.Stop();
(await ObjectExistsAsync(name)).Should().BeTrue(
"an object whose processing failed must stay in place");
(await ObjectExistsAsync("processed/" + name)).Should().BeFalse(
"an object whose processing failed must not land in the success pocket");
}
[Fact]
public async Task MoveFailed_FailedProcessing_ObjectQuarantined()
{
var prefix = $"quarantine-{Guid.NewGuid():N}/";
var name = await SeedObjectAsync(prefix, "victim.txt");
var consumer = CreateConsumer(
$"prefix={prefix}&delay=300&initialDelay=100&moveFailed=failed/&includeBody=false",
new ThrowingProcessor());
await consumer.Start();
var quarantined = await WaitUntilAsync(() => ObjectExistsAsync("failed/" + name), 6000);
await consumer.Stop();
quarantined.Should().BeTrue("an object whose processing failed must go to the MoveFailed pocket");
(await ObjectExistsAsync(name)).Should().BeFalse(
"after quarantine the source object must leave the polling prefix");
}
[Fact]
public async Task DeleteAfterRead_RollbackOnly_ObjectSurvives()
{
var prefix = $"rollback-del-{Guid.NewGuid():N}/";
var name = await SeedObjectAsync(prefix, "victim.txt");
var processor = new RollbackOnlyProcessor();
var consumer = CreateConsumer(
$"prefix={prefix}&delay=300&initialDelay=100&deleteAfterRead=true&includeBody=false",
processor);
await consumer.Start();
var seen = await WaitUntilAsync(() => Task.FromResult(processor.Attempts >= 2), 6000);
await consumer.Stop();
seen.Should().BeTrue("a rolled-back object is offered again on the next poll");
(await ObjectExistsAsync(name)).Should().BeTrue(
"a rollback-only exchange (.RollbackAll()) did not commit, so the object is not deleted");
}
[Fact]
public async Task MoveFailed_RollbackOnly_ObjectQuarantined()
{
var prefix = $"rollback-quarantine-{Guid.NewGuid():N}/";
var name = await SeedObjectAsync(prefix, "victim.txt");
var consumer = CreateConsumer(
$"prefix={prefix}&delay=300&initialDelay=100&moveAfterRead=processed/&moveFailed=failed/&includeBody=false",
new RollbackOnlyProcessor());
await consumer.Start();
var quarantined = await WaitUntilAsync(() => ObjectExistsAsync("failed/" + name), 6000);
await consumer.Stop();
quarantined.Should().BeTrue("a rollback-only exchange is a failure, so the object goes to moveFailed");
(await ObjectExistsAsync("processed/" + name)).Should().BeFalse(
"a rollback-only exchange never reaches the moveAfterRead destination");
}
// ═══════════════════════════════════════════════════════════════════
// Idempotent mark only after success
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task Idempotent_FailedObject_RetriedOnNextPoll()
{
var prefix = $"idem-retry-{Guid.NewGuid():N}/";
await SeedObjectAsync(prefix, "victim.txt");
var processor = new FailFirstProcessor();
var consumer = CreateConsumer(
$"prefix={prefix}&delay=300&initialDelay=100&idempotent=true&includeBody=false",
processor);
await consumer.Start();
var succeeded = await Task.WhenAny(processor.FirstSuccess.Task, Task.Delay(8000))
== processor.FirstSuccess.Task;
await consumer.Stop();
succeeded.Should().BeTrue(
"a failed object must not be marked \"seen\" and must be delivered again");
processor.TotalAttempts.Should().BeGreaterThanOrEqualTo(2);
}
// ═══════════════════════════════════════════════════════════════════
// Guard — success path keeps working
// ═══════════════════════════════════════════════════════════════════
[Fact]
public async Task DeleteAfterRead_SuccessfulProcessing_ObjectDeleted()
{
var prefix = $"ok-del-{Guid.NewGuid():N}/";
var name = await SeedObjectAsync(prefix, "victim.txt");
var consumer = CreateConsumer(
$"prefix={prefix}&delay=300&initialDelay=100&deleteAfterRead=true&includeBody=false",
new NoOpProcessor());
await consumer.Start();
var deleted = await WaitUntilAsync(async () => !await ObjectExistsAsync(name), 6000);
await consumer.Stop();
deleted.Should().BeTrue("a successfully processed object is deleted under DeleteAfterRead");
}
// ═══════════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════════
private async Task SeedObjectAsync(string prefix, string fileName)
{
var name = prefix + fileName;
using var data = new MemoryStream(Encoding.UTF8.GetBytes("payload"));
await _rawGcs!.UploadObjectAsync(TestBucket, name, "text/plain", data);
return name;
}
private async Task ObjectExistsAsync(string name)
{
try
{
await _rawGcs!.GetObjectAsync(TestBucket, name);
return true;
}
catch (Google.GoogleApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
{
return false;
}
}
private static async Task WaitUntilAsync(Func> condition, int timeoutMs)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < deadline)
{
if (await condition()) return true;
await Task.Delay(200);
}
return await condition();
}
private IConsumer CreateConsumer(string queryParams, IProcessor processor)
{
// Production credential provider — the consumer connects the same way a real host does.
var component = new FirebaseStorageComponent { CredentialProvider = _prodProvider! };
var uri = EndpointUriParser.Parse($"fbstorage://{TestBucket}?{queryParams}");
var endpoint = (FirebaseStorageEndpoint)component.CreateEndpoint(uri);
return endpoint.CreateConsumer(processor);
}
private sealed class ThrowingProcessor : IProcessor
{
public Task Process(IExchange exchange, CancellationToken ct = default)
=> throw new InvalidOperationException("simulated processing failure");
}
/// Marks every exchange rollback-only without an exception, as .RollbackAll() does.
private sealed class RollbackOnlyProcessor : IProcessor
{
private int _attempts;
internal int Attempts => Volatile.Read(ref _attempts);
public Task Process(IExchange exchange, CancellationToken ct = default)
{
Interlocked.Increment(ref _attempts);
exchange.MarkRollbackOnly();
return Task.CompletedTask;
}
}
private sealed class NoOpProcessor : IProcessor
{
public Task Process(IExchange exchange, CancellationToken ct = default)
=> Task.CompletedTask;
}
/// Fails the first delivery of every object, succeeds afterwards.
private sealed class FailFirstProcessor : IProcessor
{
private readonly ConcurrentDictionary _attempts = new();
private int _total;
internal TaskCompletionSource FirstSuccess { get; } =
new(TaskCreationOptions.RunContinuationsAsynchronously);
internal int TotalAttempts => Volatile.Read(ref _total);
public Task Process(IExchange exchange, CancellationToken ct = default)
{
Interlocked.Increment(ref _total);
var key = exchange.In.GetHeader(FirebaseStorageHeaders.ObjectName) ?? "?";
var attempt = _attempts.AddOrUpdate(key, 1, (_, n) => n + 1);
if (attempt == 1)
throw new InvalidOperationException("simulated first-delivery failure");
FirstSuccess.TrySetResult();
return Task.CompletedTask;
}
}
}