Bundle: redb-route / tests/redb.Route.Tests.S3 (tests.redb.Route.Tests.S3.txt), 12 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/tests/redb.Route.Tests.S3/S3ClientLogTests.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.S3/S3ClientLogTests.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Core; using redb.Route.S3; using redb.Route.Tests.Cluster; namespace redb.Route.Tests.S3; /// /// The "client created" log names the region and service URL the client talks to: a connection factory's, read from the /// client's own configuration, not the endpoint's defaults. /// public sealed class S3ClientLogTests { [Fact] public async Task ClientCreated_WithAConnectionFactory_LogsTheFactorysTarget() { var capture = new CapturingLoggerProvider(); using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(LogLevel.Debug)); await using var context = new RouteContext(loggerFactory: loggerFactory); context.AddComponent(new S3Component()); context.AddToRegistry("minio", new S3ConnectionFactory { ServiceUrl = "http://minio.internal:9000", Region = "eu-west-3", AccessKey = "ak", SecretKey = "sk", ForcePathStyle = true, }); var endpoint = (S3Endpoint)context.GetEndpoint("s3://invoices?connectionFactory=minio"); await endpoint.GetOrCreateClientAsync(); var created = capture.Entries.Single(e => e.Message.StartsWith("S3 client created", StringComparison.Ordinal)).Message; created.Should().Contain("minio.internal:9000").And.Contain("eu-west-3").And.Contain("minio"); created.Should().NotContain("us-east-1", "that is the endpoint's default region, not the client's"); } } Path: redb-route/tests/redb.Route.Tests.S3/S3ConnectionConfigTests.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.S3/S3ConnectionConfigTests.cs ---- using Amazon.Runtime; using redb.Route.Core; using redb.Route.S3; namespace redb.Route.Tests.S3; /// /// Connection options that were /// declared, documented and bound — but never reached the AWS SDK config. /// public sealed class S3ConnectionConfigTests { [Fact] public void Factory_SocketTimeout_ReachesSdkConfig() { var client = new S3ConnectionFactory { ServiceUrl = "http://localhost:9000", AccessKey = "k", SecretKey = "s", SocketTimeout = 12_345, }.Build(); client.Config.Timeout.Should().Be(TimeSpan.FromMilliseconds(12_345), "SocketTimeout must reach the SDK as the request timeout, not be a dead option"); } [Fact] public void Factory_ConnectionTimeout_MapsToConnectTimeout() { var client = new S3ConnectionFactory { ServiceUrl = "http://localhost:9000", AccessKey = "k", SecretKey = "s", ConnectionTimeout = 7_000, }.Build(); client.Config.ConnectTimeout.Should().Be(TimeSpan.FromMilliseconds(7_000)); } [Fact] public void Factory_RetryModeAdaptive_ReachesSdkConfig() { var client = new S3ConnectionFactory { ServiceUrl = "http://localhost:9000", AccessKey = "k", SecretKey = "s", RetryMode = "adaptive", }.Build(); client.Config.RetryMode.Should().Be(RequestRetryMode.Adaptive, "RetryMode must reach the SDK, not be a dead option"); } [Fact] public void Factory_TrustAllCertificates_InstallsHttpClientFactory() { var client = new S3ConnectionFactory { ServiceUrl = "https://localhost:9000", AccessKey = "k", SecretKey = "s", TrustAllCertificates = true, }.Build(); client.Config.HttpClientFactory.Should().NotBeNull( "TrustAllCertificates must set a factory with certificate validation turned off"); } [Fact] public async Task ConnectionFactoryTypo_FailsLoud_NeverFallsBackToUriParams() { // A typo in connectionFactory used to connect silently // with the URI credentials — a working configuration and a misconfiguration looked the same. await using var ctx = new RouteContext(); var component = new S3Component(); ctx.AddComponent(component); var endpoint = (S3Endpoint)ctx.GetEndpoint( "s3://bucket?connectionFactory=typo-name&serviceUrl=http://localhost:9000" + "&accessKey=k&secretKey=s"); var act = () => endpoint.GetOrCreateClientAsync(); await act.Should().ThrowAsync() .Where(e => e.Message.Contains("typo-name"), "a factory name that is set but not found must fail loudly"); } [Fact] public async Task EndpointOptions_Trio_ReachesSdkConfig() { var uri = EndpointUriParser.Parse( "s3://bucket?serviceUrl=http://localhost:9000&accessKey=k&secretKey=s" + "&socketTimeout=23456&retryMode=adaptive&trustAllCertificates=true"); var endpoint = (S3Endpoint)new S3Component().CreateEndpoint(uri); var client = await endpoint.GetOrCreateClientAsync(); client.Config.Timeout.Should().Be(TimeSpan.FromMilliseconds(23_456)); client.Config.RetryMode.Should().Be(RequestRetryMode.Adaptive); client.Config.HttpClientFactory.Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests.S3/S3ConsumerFailureTests.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.S3/S3ConsumerFailureTests.cs ---- using System.Collections.Concurrent; using Amazon.S3; using Amazon.S3.Model; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.S3; using Xunit.Abstractions; namespace redb.Route.Tests.S3; /// /// Failure semantics of the S3 polling consumer against MinIO (:9000) — /// findings S-1..S-4 of the S3 review: a failed exchange must never lose the object /// (S-1); the idempotent mark must be written after success, never at filter time — objects /// beyond MaxMessagesPerPoll and failed objects must be re-offered (S-2); exchanges must /// carry the endpoint's ScopeFactory so per-exchange DI scopes work (S-4). /// [Trait("Category", "Integration")] public sealed class S3ConsumerFailureTests : IAsyncLifetime { private const string ServiceUrl = "http://localhost:9000"; private const string AccessKey = "minioadmin"; private const string SecretKey = "minioadmin"; private const string Region = "us-east-1"; // Bucket per TFM: three test assemblies run in parallel against one MinIO. private static readonly string TestBucket = $"consumer-failure-net{Environment.Version.Major}"; private readonly ITestOutputHelper _output; private IAmazonS3? _rawClient; public S3ConsumerFailureTests(ITestOutputHelper output) => _output = output; public async Task InitializeAsync() { _rawClient = new AmazonS3Client(AccessKey, SecretKey, new AmazonS3Config { ServiceURL = ServiceUrl, ForcePathStyle = true, AuthenticationRegion = Region, }); try { await _rawClient.EnsureBucketExistsAsync(TestBucket); } catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.Conflict) { } } public Task DisposeAsync() { _rawClient?.Dispose(); return Task.CompletedTask; } // ═══════════════════════════════════════════════════════════════════ // S-1 — delete/move must not happen after failed processing // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task DeleteAfterRead_FailedProcessing_ObjectSurvives() { var prefix = $"fail-del-{Guid.NewGuid():N}/"; await SeedObject(prefix + "victim.txt"); // deleteAfterRead=true is the DEFAULT — the exact configuration every consumer runs with. var consumer = CreateConsumer( $"prefix={prefix}&delay=300&initialDelay=100&includeBody=false", new ThrowingProcessor()); await consumer.Start(); await Task.Delay(2000); await consumer.Stop(); (await ObjectExists(prefix + "victim.txt")).Should().BeTrue( "an object whose processing failed must not be deleted"); } [Fact] public async Task DeleteAfterRead_RollbackOnly_ObjectSurvives() { var prefix = $"rollback-del-{Guid.NewGuid():N}/"; await SeedObject(prefix + "victim.txt"); var processor = new RollbackOnlyProcessor(); var consumer = CreateConsumer( $"prefix={prefix}&delay=300&initialDelay=100&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 ObjectExists(prefix + "victim.txt")).Should().BeTrue( "a rollback-only exchange (.RollbackAll()) did not commit, so the object is not deleted"); } [Fact] public async Task MoveAfterRead_RollbackOnly_ObjectNotMoved() { var prefix = $"rollback-move-{Guid.NewGuid():N}/"; await SeedObject(prefix + "victim.txt"); var processor = new RollbackOnlyProcessor(); var consumer = CreateConsumer( $"prefix={prefix}&delay=300&initialDelay=100&includeBody=false" + $"&moveAfterRead=true&destinationBucket={TestBucket}&destinationBucketPrefix=moved/", 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 ObjectExists(prefix + "victim.txt")).Should().BeTrue( "a rollback-only exchange keeps the object where it is"); (await ObjectExists("moved/" + prefix + "victim.txt")).Should().BeFalse( "a rollback-only exchange is not moved to the destination bucket"); } // ═══════════════════════════════════════════════════════════════════ // S-2 — idempotent mark only after success, never at filter time // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Idempotent_BurstBeyondMaxMessagesPerPoll_AllObjectsProcessed() { var prefix = $"burst-{Guid.NewGuid():N}/"; for (var i = 0; i < 15; i++) await SeedObject($"{prefix}obj{i:D2}.txt"); var processor = new CountingProcessor(expected: 15); var consumer = CreateConsumer( $"prefix={prefix}&delay=400&initialDelay=100&maxMessagesPerPoll=10" + "&idempotent=true&deleteAfterRead=false&includeBody=false", processor); await consumer.Start(); var all = await Task.WhenAny(processor.AllSeen.Task, Task.Delay(15_000)) == processor.AllSeen.Task; await consumer.Stop(); all.Should().BeTrue( "objects over MaxMessagesPerPoll must not be marked \"seen\" at the filter stage"); processor.DistinctKeys.Should().Be(15); _output.WriteLine($"Processed {processor.DistinctKeys} distinct keys"); } [Fact] public async Task Idempotent_FailedObject_RetriedOnNextPoll() { var prefix = $"idem-retry-{Guid.NewGuid():N}/"; await SeedObject(prefix + "victim.txt"); var processor = new FailFirstProcessor(); var consumer = CreateConsumer( $"prefix={prefix}&delay=300&initialDelay=100&idempotent=true" + "&deleteAfterRead=false&includeBody=false", processor); await consumer.Start(); var ok = await Task.WhenAny(processor.FirstSuccess.Task, Task.Delay(8000)) == processor.FirstSuccess.Task; await consumer.Stop(); ok.Should().BeTrue("a failed object must not be marked \"seen\" and must be delivered again"); processor.TotalAttempts.Should().BeGreaterThanOrEqualTo(2); } // ═══════════════════════════════════════════════════════════════════ // S-4 — exchanges carry the endpoint's ScopeFactory // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_Exchange_CarriesServiceProviderScope() { var prefix = $"scope-{Guid.NewGuid():N}/"; await SeedObject(prefix + "one.txt"); var endpoint = CreateEndpoint( $"prefix={prefix}&delay=300&initialDelay=100&deleteAfterRead=false&includeBody=false"); await using var sp = new ServiceCollection().BuildServiceProvider(); endpoint.ScopeFactory = sp.GetRequiredService(); var processor = new ScopeProbeProcessor(); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); var seen = await Task.WhenAny(processor.Seen.Task, Task.Delay(8000)) == processor.Seen.Task; await consumer.Stop(); seen.Should().BeTrue(); processor.HadServiceProvider.Should().BeTrue( "the consumer's exchange must be created with the endpoint's ScopeFactory - otherwise per-exchange DI scopes are dead"); } // ═══════════════════════════════════════════════════════════════════ // Guard — success path still deletes // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task DeleteAfterRead_SuccessfulProcessing_ObjectDeleted() { var prefix = $"ok-del-{Guid.NewGuid():N}/"; await SeedObject(prefix + "victim.txt"); var consumer = CreateConsumer( $"prefix={prefix}&delay=300&initialDelay=100&includeBody=false", new NoOpProcessor()); await consumer.Start(); var deleted = await WaitUntilAsync(async () => !await ObjectExists(prefix + "victim.txt"), 6000); await consumer.Stop(); deleted.Should().BeTrue("a successfully processed object is deleted under DeleteAfterRead"); } // ═══════════════════════════════════════════════════════════════════ // Helpers // ═══════════════════════════════════════════════════════════════════ private S3Endpoint CreateEndpoint(string extraParams) { var qs = $"serviceUrl={ServiceUrl}&accessKey={AccessKey}&secretKey={SecretKey}" + $"®ion={Region}&forcePathStyle=true&{extraParams}"; var uri = EndpointUriParser.Parse($"s3://{TestBucket}?{qs}"); return (S3Endpoint)new S3Component().CreateEndpoint(uri); } private IConsumer CreateConsumer(string extraParams, IProcessor processor) => CreateEndpoint(extraParams).CreateConsumer(processor); private async Task SeedObject(string key) => await _rawClient!.PutObjectAsync(new PutObjectRequest { BucketName = TestBucket, Key = key, ContentBody = "payload", }); private async Task ObjectExists(string key) { try { await _rawClient!.GetObjectMetadataAsync(TestBucket, key); return true; } catch (AmazonS3Exception ex) when (ex.StatusCode == 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 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; } private sealed class CountingProcessor : IProcessor { private readonly int _expected; private readonly ConcurrentDictionary _keys = new(); internal CountingProcessor(int expected) => _expected = expected; internal TaskCompletionSource AllSeen { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); internal int DistinctKeys => _keys.Count; public Task Process(IExchange exchange, CancellationToken ct = default) { var key = exchange.In.GetHeader(S3Headers.Key) ?? "?"; _keys.TryAdd(key, true); if (_keys.Count >= _expected) AllSeen.TrySetResult(); return 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(S3Headers.Key) ?? "?"; var attempt = _attempts.AddOrUpdate(key, 1, (_, n) => n + 1); if (attempt == 1) throw new InvalidOperationException("simulated first-delivery failure"); FirstSuccess.TrySetResult(); return Task.CompletedTask; } } private sealed class ScopeProbeProcessor : IProcessor { internal TaskCompletionSource Seen { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); internal bool HadServiceProvider { get; private set; } public Task Process(IExchange exchange, CancellationToken ct = default) { HadServiceProvider = exchange.ServiceProvider is not null; Seen.TrySetResult(); return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests.S3/S3DoneFileKeysTests.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.S3/S3DoneFileKeysTests.cs ---- using redb.Route.Expressions; using redb.Route.S3; namespace redb.Route.Tests.S3; /// /// The file keys of the S3 consumer's doneFileName (findings register row 34 point 5): they read the object /// key; ${file:name} is the whole key, as it always was. An unknown key fails when the options are validated. /// public sealed class S3DoneFileKeysTests { [Theory] [InlineData("in/2026/order.csv", "${file:name}.done", "in/2026/order.csv.done")] [InlineData("in/2026/order.csv", "${file:name.noext}.done", "in/2026/order.done")] [InlineData("in/2026/order.csv", "${file:parent}/ready-${file:ext}", "in/2026/ready-csv")] [InlineData("in/2026/order.csv", "${FILE:NAME}.done", "in/2026/order.csv.done")] [InlineData("in.d/order", "${file:name.noext}-${file:ext}", "in.d/order-")] [InlineData("order.csv", "[${file:parent}][${file:size}][${file:path}]", "[][][]")] public void TheKeys_ReadTheObjectKey(string objectKey, string pattern, string expected) { FileLanguage.Substitute(pattern, new ObjectKeyFacts(objectKey), StringComparison.OrdinalIgnoreCase).Should().Be(expected); } [Fact] public void AnUnknownKey_FailsValidation() { var options = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", DoneFileName = "${file:nosuch}.done" }; var act = () => options.Validate(); act.Should().Throw() .WithMessage("doneFileName='${file:nosuch}.done': 'nosuch' is not a file key; the keys are name, *"); } [Fact] public void AKnownKey_PassesValidation() { var options = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", DoneFileName = "${FILE:NAME}.done" }; var act = () => options.Validate(); act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests.S3/S3DslTests.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.S3/S3DslTests.cs ---- using redb.Route.Core; using redb.Route.S3; using S3Dsl = redb.Route.S3.S3; namespace redb.Route.Tests.S3; public sealed class S3DslTests { [Fact] public void Bucket_GeneratesBasicUri() { string uri = S3Dsl.Bucket("my-bucket"); uri.Should().Be("s3://my-bucket"); } [Fact] public void Bucket_WithOperation_GeneratesOperationUri() { string uri = S3Dsl.Bucket("my-bucket", S3OperationType.CopyObject); uri.Should().Be("s3://CopyObject:my-bucket"); } [Fact] public void Builder_MinIOConfig_GeneratesFullUri() { string uri = S3Dsl.Bucket("test-bucket") .ServiceUrl("http://localhost:9000") .ForcePathStyle() .AccessKey("minioadmin") .SecretKey("minioadmin") .Region("us-east-1"); uri.Should().Contain("s3://test-bucket?"); uri.Should().Contain("serviceUrl=http"); uri.Should().Contain("forcePathStyle=true"); uri.Should().Contain("accessKey=minioadmin"); uri.Should().Contain("secretKey=minioadmin"); uri.Should().Contain("region=us-east-1"); } [Fact] public void Builder_ConsumerOptions_GeneratesUri() { string uri = S3Dsl.Bucket("data") .AccessKey("key").SecretKey("secret") .Prefix("incoming/") .Include("*.csv") .Exclude("*.tmp") .Delay(5000) .MaxMessagesPerPoll(50) .DeleteAfterRead() .SortBy(S3SortBy.LastModified) .MinAge(10_000) .Idempotent(); uri.Should().Contain("prefix=incoming"); uri.Should().Contain("include=%2A.csv"); uri.Should().Contain("exclude=%2A.tmp"); uri.Should().Contain("delay=5000"); uri.Should().Contain("maxMessagesPerPoll=50"); uri.Should().Contain("deleteAfterRead=true"); uri.Should().Contain("sortBy=LastModified"); uri.Should().Contain("minAge=10000"); uri.Should().Contain("idempotent=true"); } [Fact] public void Builder_MoveAfterRead_GeneratesUri() { string uri = S3Dsl.Bucket("source") .AccessKey("key").SecretKey("secret") .MoveAfterRead("archive-bucket", prefix: "processed/", suffix: "-done") .RemovePrefixOnMove(); uri.Should().Contain("moveAfterRead=true"); uri.Should().Contain("destinationBucket=archive-bucket"); uri.Should().Contain("destinationBucketPrefix=processed"); uri.Should().Contain("destinationBucketSuffix=-done"); uri.Should().Contain("removePrefixOnMove=true"); } [Fact] public void Builder_ProducerOptions_GeneratesUri() { string uri = S3Dsl.Bucket("uploads") .AccessKey("key").SecretKey("secret") .KeyName("data/${header.fileName}") .StorageClass("INTELLIGENT_TIERING") .ContentType("application/json") .MultiPartUpload() .PartSize(10_485_760) .CannedAcl(S3CannedAcl.PublicRead); uri.Should().Contain("keyName=data"); uri.Should().Contain("storageClass=INTELLIGENT_TIERING"); uri.Should().Contain("contentType=application%2Fjson"); uri.Should().Contain("multiPartUpload=true"); uri.Should().Contain("partSize=10485760"); uri.Should().Contain("cannedAcl=PublicRead"); } [Fact] public void Builder_Encryption_GeneratesUri() { string uri = S3Dsl.Bucket("secure") .AccessKey("key").SecretKey("secret") .UseKmsEncryption("my-kms-key-id"); uri.Should().Contain("serverSideEncryption=AwsKms"); uri.Should().Contain("kmsKeyId=my-kms-key-id"); } // Builder_StreamingUpload_GeneratesUri removed with the streaming-upload block (the options sweep): // the mode was never implemented; accumulate-then-write is the core Aggregate(...) EIP. [Fact] public void Builder_ImplicitStringConversion() { S3Builder builder = S3Dsl.Bucket("test").AccessKey("key").SecretKey("secret"); string uri = builder; uri.Should().StartWith("s3://test?"); } [Fact] public void Builder_ToString_EqualsImplicit() { var builder = S3Dsl.Bucket("test").AccessKey("key").SecretKey("secret"); builder.ToString().Should().Be((string)builder); } [Fact] public void Builder_StreamBody_SetsParam() { string uri = S3Dsl.Bucket("data") .AccessKey("key").SecretKey("secret") .StreamBody(); uri.Should().Contain("streamBody=true"); } [Fact] public void Builder_StreamBody_RoundTrip() { string uri = S3Dsl.Bucket("data") .AccessKey("key").SecretKey("secret") .StreamBody() .Build(); var parsed = EndpointUriParser.Parse(uri); parsed.RawParameters["streamBody"].Should().Be("true"); } } Path: redb-route/tests/redb.Route.Tests.S3/S3EndpointOptionsTests.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.S3/S3EndpointOptionsTests.cs ---- using redb.Route.Core; using redb.Route.S3; namespace redb.Route.Tests.S3; public sealed class S3EndpointOptionsTests { [Fact] public void Validate_NoCredentials_Throws() { var opts = new S3EndpointOptions { AccessKey = "", SecretKey = "" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*credentials*"); } [Fact] public void Validate_WithAccessKeyAndSecretKey_DoesNotThrow() { var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret" }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_DefaultCredentialsProvider_DoesNotThrow() { var opts = new S3EndpointOptions { UseDefaultCredentialsProvider = true }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_ProfileName_DoesNotThrow() { var opts = new S3EndpointOptions { ProfileName = "default" }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_ConnectionFactory_DoesNotThrow() { var opts = new S3EndpointOptions { ConnectionFactory = "myFactory" }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_MoveAfterRead_WithoutDestinationBucket_Throws() { var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", MoveAfterRead = true, DeleteAfterRead = false, DestinationBucket = "" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*DestinationBucket*"); } [Fact] public void Validate_MoveAndDeleteAfterRead_Throws() { var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", MoveAfterRead = true, DeleteAfterRead = true, DestinationBucket = "dest" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*MoveAfterRead*DeleteAfterRead*"); } [Fact] public void Validate_MoveAfterRead_WithTheDefaultDelete_Passes() { // s3://incoming?moveAfterRead=true&destinationBucket=archive: the move takes the place of the default delete. var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", MoveAfterRead = true, DestinationBucket = "archive" }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Uri_MoveAfterRead_WithoutDeleteAfterRead_CreatesTheEndpoint() { var component = new S3Component(); var act = () => component.CreateEndpoint(redb.Route.Core.EndpointUriParser.Parse( "s3://incoming?accessKey=key&secretKey=secret&moveAfterRead=true&destinationBucket=archive")); act.Should().NotThrow("the template's consumer started only with an explicit deleteAfterRead=false"); } [Fact] public void Validate_NegativeDelay_Throws() { var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", Delay = -1 }; var act = () => opts.Validate(); act.Should().Throw(); } [Fact] public void Validate_PartSizeTooSmall_Throws() { var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", PartSize = 1000 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*5 MB*"); } [Fact] public void Validate_KmsWithoutKeyId_Throws() { var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", ServerSideEncryption = S3ServerSideEncryption.AwsKms, KmsKeyId = "" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*KmsKeyId*"); } [Fact] public void Validate_CustomerKeyWithoutKey_Throws() { var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", ServerSideEncryption = S3ServerSideEncryption.CustomerKey, CustomerKeyId = "" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*CustomerKeyId*"); } [Fact] public void Validate_InvalidProxyPort_Throws() { var opts = new S3EndpointOptions { AccessKey = "key", SecretKey = "secret", ProxyPort = 99999 }; var act = () => opts.Validate(); act.Should().Throw(); } [Fact] public void BindFromUri_ParsesAllCoreProperties() { var opts = new S3EndpointOptions(); opts.BindFromUri(new Dictionary { ["serviceUrl"] = "http://localhost:9000", ["region"] = "eu-west-1", ["accessKey"] = "AK", ["secretKey"] = "SK", ["forcePathStyle"] = "true", ["delay"] = "5000", ["maxMessagesPerPoll"] = "20", ["deleteAfterRead"] = "false", ["prefix"] = "data/", ["include"] = "*.csv", ["sortBy"] = "LastModified", ["autoCreateBucket"] = "true", ["multiPartUpload"] = "true", ["partSize"] = "10485760", ["storageClass"] = "GLACIER", ["presignedUrlExpiration"] = "7200000", }); opts.ServiceUrl.Should().Be("http://localhost:9000"); opts.Region.Should().Be("eu-west-1"); opts.AccessKey.Should().Be("AK"); opts.SecretKey.Should().Be("SK"); opts.ForcePathStyle.Should().BeTrue(); opts.Delay.Should().Be(5000); opts.MaxMessagesPerPoll.Should().Be(20); opts.DeleteAfterRead.Should().BeFalse(); opts.Prefix.Should().Be("data/"); opts.Include.Should().Be("*.csv"); opts.SortBy.Should().Be(S3SortBy.LastModified); opts.AutoCreateBucket.Should().BeTrue(); opts.MultiPartUpload.Should().BeTrue(); opts.PartSize.Should().Be(10_485_760); opts.StorageClass.Should().Be("GLACIER"); opts.PresignedUrlExpiration.Should().Be(7_200_000); } [Fact] public void Defaults_AreCorrect() { var opts = new S3EndpointOptions(); opts.Region.Should().Be("us-east-1"); opts.Delay.Should().Be(60_000); opts.InitialDelay.Should().Be(1000); opts.MaxMessagesPerPoll.Should().Be(10); opts.DeleteAfterRead.Should().BeTrue(); opts.IncludeBody.Should().BeTrue(); opts.PartSize.Should().Be(26_214_400); opts.PresignedUrlExpiration.Should().Be(3_600_000); opts.CannedAcl.Should().Be(S3CannedAcl.Private); opts.RetryCount.Should().Be(3); opts.MaxConnections.Should().Be(50); } } Path: redb-route/tests/redb.Route.Tests.S3/S3HeadersTests.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.S3/S3HeadersTests.cs ---- using redb.Route.S3; namespace redb.Route.Tests.S3; public sealed class S3HeadersTests { [Fact] public void AllHeaders_HaveCorrectPrefix() { // All public const string fields should start with prefix "redbS3." var fields = typeof(S3Headers) .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) .Where(f => f.FieldType == typeof(string) && f.Name != "MetadataPrefix") .Select(f => (f.Name, Value: (string)f.GetValue(null)!)) .ToList(); fields.Should().NotBeEmpty(); foreach (var (name, value) in fields) { value.Should().StartWith("redbS3.", because: $"header {name} must have the S3 prefix"); } } [Fact] public void MetadataPrefix_EndsWithDot() { S3Headers.MetadataPrefix.Should().EndWith("."); } [Fact] public void IsRedbHeader_ReturnsTrueForKnownHeaders() { S3Headers.IsRedbHeader(S3Headers.BucketName).Should().BeTrue(); S3Headers.IsRedbHeader(S3Headers.Key).Should().BeTrue(); S3Headers.IsRedbHeader(S3Headers.ETag).Should().BeTrue(); } [Fact] public void IsRedbHeader_ReturnsFalseForUnknownHeaders() { S3Headers.IsRedbHeader("Content-Type").Should().BeFalse(); S3Headers.IsRedbHeader("unknown").Should().BeFalse(); } [Fact] public void HeaderValues_AreUnique() { var fields = typeof(S3Headers) .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) .Where(f => f.FieldType == typeof(string) && f.Name != "MetadataPrefix") .Select(f => (string)f.GetValue(null)!) .ToList(); fields.Should().OnlyHaveUniqueItems(); } } Path: redb-route/tests/redb.Route.Tests.S3/S3IntegrationTests.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.S3/S3IntegrationTests.cs ---- using System.Collections.Concurrent; using System.Text; using Amazon.S3; using Amazon.S3.Model; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.S3; using Xunit.Abstractions; namespace redb.Route.Tests.S3; /// /// Integration tests against the S3-compatible test store (RustFS, docker-compose.tests.yml service s3). /// Expects it at localhost:9000 (minioadmin/minioadmin). /// Start with: docker compose -f docker-compose.tests.yml up s3 -d /// [Trait("Category", "Integration")] public sealed class S3IntegrationTests : IAsyncLifetime { private const string ServiceUrl = "http://localhost:9000"; private const string AccessKey = "minioadmin"; private const string SecretKey = "minioadmin"; private const string Region = "us-east-1"; // Bucket per TFM: three test assemblies run in parallel against one MinIO, and // one assembly's DisposeAsync cleanup must not delete another's freshly seeded objects. private static readonly string TestBucket = $"integration-tests-net{Environment.Version.Major}"; private readonly ITestOutputHelper _output; private IAmazonS3? _rawClient; public S3IntegrationTests(ITestOutputHelper output) => _output = output; public async Task InitializeAsync() { _rawClient = CreateRawClient(); // Ensure test bucket exists try { await _rawClient.EnsureBucketExistsAsync(TestBucket); } catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.Conflict) { } } public async Task DisposeAsync() { if (_rawClient is not null) { // Cleanup all test-* prefixed objects await CleanupBucketAsync(TestBucket); _rawClient.Dispose(); } } // ───── Helpers ───── private static string UniquePrefix() => $"test-{Guid.NewGuid():N}/"; private static IAmazonS3 CreateRawClient() { var config = new AmazonS3Config { ServiceURL = ServiceUrl, ForcePathStyle = true, AuthenticationRegion = Region, }; return new AmazonS3Client(AccessKey, SecretKey, config); } private S3Endpoint CreateEndpoint(string bucket, string? extraParams = null) { var qs = $"serviceUrl={ServiceUrl}&accessKey={AccessKey}&secretKey={SecretKey}" + $"®ion={Region}&forcePathStyle=true"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"s3://{bucket}?{qs}"); return (S3Endpoint)new S3Component().CreateEndpoint(uri); } private S3Endpoint CreateEndpointWithOp(S3OperationType op, string bucket, string? extraParams = null) { var qs = $"serviceUrl={ServiceUrl}&accessKey={AccessKey}&secretKey={SecretKey}" + $"®ion={Region}&forcePathStyle=true"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"s3://{op}:{bucket}?{qs}"); return (S3Endpoint)new S3Component().CreateEndpoint(uri); } private async Task SeedObject(string bucket, string key, string content) { await _rawClient!.PutObjectAsync(new PutObjectRequest { BucketName = bucket, Key = key, ContentBody = content, }); } private async Task SeedObject(string bucket, string key, byte[] data) { await _rawClient!.PutObjectAsync(new PutObjectRequest { BucketName = bucket, Key = key, InputStream = new MemoryStream(data), }); } private async Task ReadObjectAsString(string bucket, string key) { var response = await _rawClient!.GetObjectAsync(bucket, key); using var reader = new StreamReader(response.ResponseStream, Encoding.UTF8); return await reader.ReadToEndAsync(); } private async Task ObjectExists(string bucket, string key) { try { await _rawClient!.GetObjectMetadataAsync(bucket, key); return true; } catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { return false; } } private async Task CleanupBucketAsync(string bucket) { try { var list = await _rawClient!.ListObjectsV2Async(new ListObjectsV2Request { BucketName = bucket, Prefix = "test-", // only cleanup test-* prefixed objects }); if (list.S3Objects is { Count: > 0 }) { await _rawClient.DeleteObjectsAsync(new DeleteObjectsRequest { BucketName = bucket, Objects = list.S3Objects.Select(o => new KeyVersion { Key = o.Key }).ToList(), }); } } catch (AmazonS3Exception) { // Bucket may not exist — ignore } } private async Task CleanupPrefixAsync(string bucket, string prefix) { var list = await _rawClient!.ListObjectsV2Async(new ListObjectsV2Request { BucketName = bucket, Prefix = prefix, }); if (list.S3Objects is { Count: > 0 }) { await _rawClient.DeleteObjectsAsync(new DeleteObjectsRequest { BucketName = bucket, Objects = list.S3Objects.Select(o => new KeyVersion { Key = o.Key }).ToList(), }); } } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — PutObject // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_PutObject_TextBody() { var prefix = UniquePrefix(); var key = $"{prefix}hello.txt"; _output.WriteLine($"Key: {key}"); var ep = CreateEndpoint(TestBucket, $"keyName={key}&autoCreateBucket=true"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("Hello S3!")); await producer.Process(exchange); await producer.Stop(); // Verify header set exchange.In.Headers[S3Headers.ProducedBucketName].Should().Be(TestBucket); exchange.In.Headers[S3Headers.ProducedKey].Should().Be(key); exchange.In.Headers[S3Headers.ETag].Should().NotBeNull(); // Verify via raw client var content = await ReadObjectAsString(TestBucket, key); content.Should().Be("Hello S3!"); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_PutObject_BinaryBody() { var prefix = UniquePrefix(); var key = $"{prefix}binary.bin"; var ep = CreateEndpoint(TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var data = new byte[] { 0x00, 0x01, 0xFF, 0xFE, 0x42, 0x43 }; var exchange = new Exchange(new Message { Body = data }); await producer.Process(exchange); await producer.Stop(); // Verify via raw client var response = await _rawClient!.GetObjectAsync(TestBucket, key); using var ms = new MemoryStream(); await response.ResponseStream.CopyToAsync(ms); ms.ToArray().Should().BeEquivalentTo(data); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_PutObject_StreamBody() { var prefix = UniquePrefix(); var key = $"{prefix}stream.dat"; var ep = CreateEndpoint(TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var data = Encoding.UTF8.GetBytes("Stream content test"); using var stream = new MemoryStream(data); var exchange = new Exchange(new Message { Body = stream }); await producer.Process(exchange); await producer.Stop(); var content = await ReadObjectAsString(TestBucket, key); content.Should().Be("Stream content test"); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_PutObject_WithContentType() { var prefix = UniquePrefix(); var key = $"{prefix}data.json"; var ep = CreateEndpoint(TestBucket, $"keyName={key}&contentType=application/json"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("{\"test\": true}")); await producer.Process(exchange); await producer.Stop(); var metadata = await _rawClient!.GetObjectMetadataAsync(TestBucket, key); metadata.Headers.ContentType.Should().Be("application/json"); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_PutObject_WithMetadata() { var prefix = UniquePrefix(); var key = $"{prefix}meta.txt"; var ep = CreateEndpoint(TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("metadata test")); exchange.In.Headers[$"{S3Headers.MetadataPrefix}author"] = "redb"; exchange.In.Headers[$"{S3Headers.MetadataPrefix}version"] = "1.0"; await producer.Process(exchange); await producer.Stop(); var metadata = await _rawClient!.GetObjectMetadataAsync(TestBucket, key); metadata.Metadata["author"].Should().Be("redb"); metadata.Metadata["version"].Should().Be("1.0"); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_PutObject_KeyFromHeader() { var prefix = UniquePrefix(); var ep = CreateEndpoint(TestBucket); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var key = $"{prefix}header-key.txt"; var exchange = new Exchange(new Message("key from header")); exchange.In.Headers[S3Headers.Key] = key; await producer.Process(exchange); await producer.Stop(); var content = await ReadObjectAsString(TestBucket, key); content.Should().Be("key from header"); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — GetObject // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_GetObject_ReturnsBody() { var prefix = UniquePrefix(); var key = $"{prefix}get-test.txt"; await SeedObject(TestBucket, key, "get object content"); var ep = CreateEndpointWithOp(S3OperationType.GetObject, TestBucket, $"keyName={key}&includeBody=true"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); var body = (byte[])exchange.In.Body!; Encoding.UTF8.GetString(body).Should().Be("get object content"); exchange.In.Headers[S3Headers.ContentType].Should().NotBeNull(); exchange.In.Headers[S3Headers.ETag].Should().NotBeNull(); exchange.In.Headers[S3Headers.Key].Should().Be(key); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_GetObject_ReturnsStream_WhenIncludeBodyFalse() { var prefix = UniquePrefix(); var key = $"{prefix}stream-get.txt"; await SeedObject(TestBucket, key, "stream body"); var ep = CreateEndpointWithOp(S3OperationType.GetObject, TestBucket, $"keyName={key}&includeBody=false"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); exchange.In.Body.Should().BeAssignableTo(); using var stream = (Stream)exchange.In.Body!; using var reader = new StreamReader(stream); var content = await reader.ReadToEndAsync(); content.Should().Be("stream body"); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — DeleteObject // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_DeleteObject_RemovesObject() { var prefix = UniquePrefix(); var key = $"{prefix}delete-me.txt"; await SeedObject(TestBucket, key, "to be deleted"); var ep = CreateEndpointWithOp(S3OperationType.DeleteObject, TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); (await ObjectExists(TestBucket, key)).Should().BeFalse(); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — CopyObject // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_CopyObject_CopiesKey() { var prefix = UniquePrefix(); var srcKey = $"{prefix}copy-src.txt"; var dstKey = $"{prefix}copy-dst.txt"; await SeedObject(TestBucket, srcKey, "copy me"); var ep = CreateEndpointWithOp(S3OperationType.CopyObject, TestBucket, $"keyName={srcKey}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); exchange.In.Headers[S3Headers.DestinationBucket] = TestBucket; exchange.In.Headers[S3Headers.DestinationKey] = dstKey; await producer.Process(exchange); await producer.Stop(); var content = await ReadObjectAsString(TestBucket, dstKey); content.Should().Be("copy me"); (await ObjectExists(TestBucket, srcKey)).Should().BeTrue("source should remain"); exchange.In.Headers[S3Headers.ProducedBucketName].Should().Be(TestBucket, "the produced object is the copy"); exchange.In.Headers[S3Headers.ProducedKey].Should().Be(dstKey); exchange.In.Headers[S3Headers.ETag].Should().NotBeNull(); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — ListObjects // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_ListObjects_ReturnsObjectInfoList() { var prefix = UniquePrefix(); await SeedObject(TestBucket, $"{prefix}a.txt", "aaa"); await SeedObject(TestBucket, $"{prefix}b.txt", "bbb"); await SeedObject(TestBucket, $"{prefix}c.txt", "ccc"); var ep = CreateEndpointWithOp(S3OperationType.ListObjects, TestBucket, $"prefix={prefix}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); var list = (List)exchange.In.Body!; list.Should().HaveCount(3); list.Select(o => o.Key).Should().BeEquivalentTo( [$"{prefix}a.txt", $"{prefix}b.txt", $"{prefix}c.txt"]); list.Should().AllSatisfy(o => { o.Size.Should().BeGreaterThan(0); o.ETag.Should().NotBeNullOrEmpty(); }); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — HeadObject // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_HeadObject_ReturnsMetadata() { var prefix = UniquePrefix(); var key = $"{prefix}head-test.txt"; await SeedObject(TestBucket, key, "head test"); var ep = CreateEndpointWithOp(S3OperationType.HeadObject, TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); exchange.In.Headers[S3Headers.ContentLength].Should().NotBeNull(); ((long)exchange.In.Headers[S3Headers.ContentLength]!).Should().BeGreaterThan(0); exchange.In.Headers[S3Headers.ETag].Should().NotBeNull(); exchange.In.Headers[S3Headers.LastModified].Should().NotBeNull(); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — Presigned URLs // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_CreateDownloadLink_ReturnsUrl() { var prefix = UniquePrefix(); var key = $"{prefix}download-link.txt"; await SeedObject(TestBucket, key, "download via link"); var ep = CreateEndpointWithOp(S3OperationType.CreateDownloadLink, TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); var url = (string)exchange.In.Body!; url.Should().Contain(TestBucket); url.Should().Contain(Uri.EscapeDataString(key).Replace("%2F", "/")); exchange.In.Headers[S3Headers.PresignedUrl].Should().Be(url); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_CreateUploadLink_ReturnsUrl() { var prefix = UniquePrefix(); var key = $"{prefix}upload-link.txt"; var ep = CreateEndpointWithOp(S3OperationType.CreateUploadLink, TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); var url = (string)exchange.In.Body!; url.Should().Contain(TestBucket); exchange.In.Headers[S3Headers.PresignedUrl].Should().Be(url); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — Tagging // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_PutAndGetObjectTagging_Roundtrip() { var prefix = UniquePrefix(); var key = $"{prefix}tagged.txt"; await SeedObject(TestBucket, key, "tagged object"); // Put tags var putEp = CreateEndpointWithOp(S3OperationType.PutObjectTagging, TestBucket, $"keyName={key}"); var putProducer = (S3Producer)putEp.CreateProducer(); await putProducer.Start(); var tags = new Dictionary { { "env", "test" }, { "team", "redb" } }; var putExchange = new Exchange(new Message { Body = tags }); await putProducer.Process(putExchange); await putProducer.Stop(); // Get tags var getEp = CreateEndpointWithOp(S3OperationType.GetObjectTagging, TestBucket, $"keyName={key}"); var getProducer = (S3Producer)getEp.CreateProducer(); await getProducer.Start(); var getExchange = new Exchange(new Message()); await getProducer.Process(getExchange); await getProducer.Stop(); var result = (Dictionary)getExchange.In.Body!; result.Should().ContainKey("env").WhoseValue.Should().Be("test"); result.Should().ContainKey("team").WhoseValue.Should().Be("redb"); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — Bucket Operations // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_CreateAndDeleteBucket() { var bucket = $"test-bucket-{Guid.NewGuid():N}"; // Create var createEp = CreateEndpointWithOp(S3OperationType.CreateBucket, bucket); var createProducer = (S3Producer)createEp.CreateProducer(); await createProducer.Start(); await createProducer.Process(new Exchange(new Message())); await createProducer.Stop(); // Verify exists via raw client var list = await _rawClient!.ListBucketsAsync(); list.Buckets.Should().Contain(b => b.BucketName == bucket); // Delete var deleteEp = CreateEndpointWithOp(S3OperationType.DeleteBucket, bucket); var deleteProducer = (S3Producer)deleteEp.CreateProducer(); await deleteProducer.Start(); await deleteProducer.Process(new Exchange(new Message())); await deleteProducer.Stop(); // Verify gone var list2 = await _rawClient.ListBucketsAsync(); list2.Buckets.Should().NotContain(b => b.BucketName == bucket); } [Fact] public async Task Producer_ListBuckets_ReturnsAll() { var ep = CreateEndpointWithOp(S3OperationType.ListBuckets, TestBucket); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); var buckets = exchange.In.Body as System.Collections.IList; buckets.Should().NotBeNull(); buckets!.Count.Should().BeGreaterThan(0); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — MultiPartUpload // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_MultiPartUpload_LargeFile() { var prefix = UniquePrefix(); var key = $"{prefix}multipart.dat"; // 6 MB > 5 MB part size → triggers multipart var ep = CreateEndpoint(TestBucket, $"keyName={key}&multiPartUpload=true&partSize=5242880"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var data = new byte[6 * 1024 * 1024]; // 6 MB Random.Shared.NextBytes(data); var exchange = new Exchange(new Message { Body = data }); await producer.Process(exchange); await producer.Stop(); // Verify uploaded correctly var response = await _rawClient!.GetObjectAsync(TestBucket, key); using var ms = new MemoryStream(); await response.ResponseStream.CopyToAsync(ms); // Ordered byte compare: BeEquivalentTo on megabytes runs for tens of seconds, for minutes on a slow Linux stand. ms.Length.Should().Be(data.Length); ms.ToArray().AsSpan().SequenceEqual(data).Should().BeTrue("the object reads back as the uploaded bytes"); exchange.In.Headers[S3Headers.ProducedBucketName].Should().Be(TestBucket, "a multipart upload reports as a single PUT does"); exchange.In.Headers[S3Headers.ProducedKey].Should().Be(key); exchange.In.Headers[S3Headers.ETag].Should().NotBeNull(); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — Operation Override via Header // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_OperationOverrideViaHeader() { var prefix = UniquePrefix(); var key = $"{prefix}override-op.txt"; await SeedObject(TestBucket, key, "check me"); // Default op is PutObject, but we override via header var ep = CreateEndpoint(TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); exchange.In.Headers[S3Headers.Operation] = "HeadObject"; await producer.Process(exchange); await producer.Stop(); exchange.In.Headers[S3Headers.ContentLength].Should().NotBeNull(); ((long)exchange.In.Headers[S3Headers.ContentLength]!).Should().BeGreaterThan(0); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — DeleteObjects (batch) // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_DeleteObjects_BatchDelete() { var prefix = UniquePrefix(); var keys = new List(); for (int i = 0; i < 3; i++) { var k = $"{prefix}batch-{i}.txt"; await SeedObject(TestBucket, k, $"batch {i}"); keys.Add(k); } var ep = CreateEndpointWithOp(S3OperationType.DeleteObjects, TestBucket); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); exchange.In.Headers[S3Headers.KeysToDelete] = keys; await producer.Process(exchange); await producer.Stop(); var deletedKeys = (List)exchange.In.Body!; deletedKeys.Should().BeEquivalentTo(keys); foreach (var k in keys) (await ObjectExists(TestBucket, k)).Should().BeFalse(); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — Basic polling // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_PollsAndReceivesObjects() { var prefix = UniquePrefix(); await SeedObject(TestBucket, $"{prefix}data1.txt", "content 1"); await SeedObject(TestBucket, $"{prefix}data2.txt", "content 2"); _output.WriteLine($"Prefix: {prefix}"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&deleteAfterRead=false&delay=500&initialDelay=100&maxMessagesPerPoll=10&includeBody=true"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 2) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(30_000)); await consumer.Stop(); received.Should().HaveCountGreaterThanOrEqualTo(2); var keys = received.Select(r => (string)r.In.Headers[S3Headers.Key]!).ToList(); keys.Should().Contain($"{prefix}data1.txt"); keys.Should().Contain($"{prefix}data2.txt"); // Verify body is downloaded var bodies = received.Select(r => Encoding.UTF8.GetString((byte[])r.In.Body!)).ToList(); bodies.Should().Contain("content 1"); bodies.Should().Contain("content 2"); // Verify headers set var first = received.First(); first.In.Headers[S3Headers.BucketName].Should().Be(TestBucket); first.In.Headers[S3Headers.ETag].Should().NotBeNull(); first.In.Headers[S3Headers.ContentLength].Should().NotBeNull(); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — DeleteAfterRead // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_DeleteAfterRead_RemovesObjects() { var prefix = UniquePrefix(); var key = $"{prefix}deletable.txt"; await SeedObject(TestBucket, key, "delete me after read"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&deleteAfterRead=true&delay=500&initialDelay=100"); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(30_000)); await consumer.Stop(); (await ObjectExists(TestBucket, key)).Should().BeFalse(); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — MoveAfterRead // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_MoveAfterRead_MovesToDestination() { var prefix = UniquePrefix(); var key = $"{prefix}movable.txt"; await SeedObject(TestBucket, key, "move me"); var destPrefix = $"{prefix}archive/"; var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&deleteAfterRead=false&moveAfterRead=true" + $"&destinationBucket={TestBucket}&destinationBucketPrefix={destPrefix}" + $"&delay=500&initialDelay=100"); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(30_000)); await consumer.Stop(); // Source should be gone (await ObjectExists(TestBucket, key)).Should().BeFalse(); // Destination should exist (prefix + original key) var destKey = $"{destPrefix}{key}"; (await ObjectExists(TestBucket, destKey)).Should().BeTrue(); var content = await ReadObjectAsString(TestBucket, destKey); content.Should().Be("move me"); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — Include/Exclude filters // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_IncludeFilter_OnlyMatchingObjects() { var prefix = UniquePrefix(); await SeedObject(TestBucket, $"{prefix}report.csv", "csv data"); await SeedObject(TestBucket, $"{prefix}readme.txt", "txt data"); await SeedObject(TestBucket, $"{prefix}data.csv", "csv data 2"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&include=*.csv&deleteAfterRead=false&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 2) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(30_000)); await consumer.Stop(); received.Should().HaveCount(2); received.Select(r => (string)r.In.Headers[S3Headers.Key]!) .Should().AllSatisfy(k => k.Should().EndWith(".csv")); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Consumer_ExcludeFilter_SkipsMatchingObjects() { var prefix = UniquePrefix(); await SeedObject(TestBucket, $"{prefix}keep.txt", "keep"); await SeedObject(TestBucket, $"{prefix}skip.log", "skip"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&exclude=*.log&deleteAfterRead=false&delay=500&initialDelay=100&idempotent=true"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(30_000)); // Wait a bit for potential second poll to make sure .log is not processed await Task.Delay(1500); await consumer.Stop(); received.Should().HaveCount(1); ((string)received.First().In.Headers[S3Headers.Key]!).Should().EndWith("keep.txt"); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — MaxMessagesPerPoll // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_MaxMessagesPerPoll_LimitsPerCycle() { var prefix = UniquePrefix(); for (int i = 0; i < 5; i++) await SeedObject(TestBucket, $"{prefix}file-{i}.txt", $"content {i}"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&maxMessagesPerPoll=2&deleteAfterRead=false&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 2) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(15_000)); // Stop quickly after first poll batch await Task.Delay(200); await consumer.Stop(); // First poll should have at most 2 received.Count.Should().BeGreaterThanOrEqualTo(2); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — Idempotent // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_Idempotent_NoReprocessing() { var prefix = UniquePrefix(); await SeedObject(TestBucket, $"{prefix}stable.txt", "idempotent data"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&idempotent=true&deleteAfterRead=false&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); // Wait for a couple more poll cycles await Task.Delay(2000); await consumer.Stop(); // Should still be only 1 — idempotent prevents reprocessing received.Should().HaveCount(1); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — SortBy // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_SortByKey_OrderedOutput() { var prefix = UniquePrefix(); // Seed in reverse order await SeedObject(TestBucket, $"{prefix}c.txt", "c"); await SeedObject(TestBucket, $"{prefix}a.txt", "a"); await SeedObject(TestBucket, $"{prefix}b.txt", "b"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&sortBy=Key&deleteAfterRead=false&delay=500&initialDelay=100&maxMessagesPerPoll=10"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 3) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(30_000)); await consumer.Stop(); received.Should().HaveCount(3); // Note: ConcurrentBag doesn't guarantee order, but the processor receives them in order // We can at least verify all 3 keys are present var keys = received.Select(r => (string)r.In.Headers[S3Headers.Key]!).ToList(); keys.Should().Contain($"{prefix}a.txt"); keys.Should().Contain($"{prefix}b.txt"); keys.Should().Contain($"{prefix}c.txt"); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — SendEmptyMessageWhenIdle // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_SendEmptyMessageWhenIdle_HeartbeatsOnEmptyBucket() { var prefix = UniquePrefix(); // No objects seeded — bucket/prefix is empty var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&sendEmptyMessageWhenIdle=true&deleteAfterRead=false&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCountGreaterThanOrEqualTo(1); // Empty message should have null body received.First().In.Body.Should().BeNull(); } // ═══════════════════════════════════════════════════════════════════ // ROUNDTRIP — Producer + Consumer // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Roundtrip_ProducerUpload_ConsumerDownload() { var prefix = UniquePrefix(); var key = $"{prefix}roundtrip.txt"; var content = "Full roundtrip test — producer to consumer!"; _output.WriteLine($"Roundtrip key: {key}"); // Upload via producer var putEp = CreateEndpoint(TestBucket, $"keyName={key}"); var producer = (S3Producer)putEp.CreateProducer(); await producer.Start(); var putExchange = new Exchange(new Message(content)); putExchange.In.Headers[$"{S3Headers.MetadataPrefix}source"] = "integration-test"; await producer.Process(putExchange); await producer.Stop(); // Consume via consumer var getEp = CreateEndpoint(TestBucket, $"prefix={prefix}&deleteAfterRead=true&delay=500&initialDelay=100&includeBody=true"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)getEp.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(30_000)); await consumer.Stop(); received.Should().HaveCount(1); var rx = received.First(); Encoding.UTF8.GetString((byte[])rx.In.Body!).Should().Be(content); rx.In.Headers[S3Headers.Key].Should().Be(key); rx.In.Headers[S3Headers.BucketName].Should().Be(TestBucket); rx.In.Headers[S3Headers.ETag].Should().NotBeNull(); // Verify deleted after read (await ObjectExists(TestBucket, key)).Should().BeFalse(); } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — Bucket Override via Header // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_BucketOverrideViaHeader() { var prefix = UniquePrefix(); var key = $"{prefix}bucket-override.txt"; // Create a second bucket var altBucket = $"test-alt-{Guid.NewGuid():N}"; try { await _rawClient!.EnsureBucketExistsAsync(altBucket); } catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.Conflict) { } try { var ep = CreateEndpoint(TestBucket, $"keyName={key}"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("in alt bucket")); exchange.In.Headers[S3Headers.OverrideBucketName] = altBucket; await producer.Process(exchange); await producer.Stop(); // Should be in alt bucket, not the default (await ObjectExists(altBucket, key)).Should().BeTrue(); (await ObjectExists(TestBucket, key)).Should().BeFalse(); var content = await ReadObjectAsString(altBucket, key); content.Should().Be("in alt bucket"); } finally { // Cleanup alt bucket await CleanupPrefixAsync(altBucket, prefix); await _rawClient!.DeleteBucketAsync(altBucket); } } // ═══════════════════════════════════════════════════════════════════ // PRODUCER — StreamBody (GetObject) // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Producer_GetObject_StreamBody_ReturnsStream() { var prefix = UniquePrefix(); var key = $"{prefix}stream-body.txt"; await SeedObject(TestBucket, key, "stream body data"); var ep = CreateEndpointWithOp(S3OperationType.GetObject, TestBucket, $"keyName={key}&streamBody=true"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); exchange.In.Body.Should().BeAssignableTo(); using var stream = (Stream)exchange.In.Body!; using var reader = new StreamReader(stream, Encoding.UTF8); var content = await reader.ReadToEndAsync(); content.Should().Be("stream body data"); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_GetObject_StreamBody_BinaryPreserved() { var prefix = UniquePrefix(); var key = $"{prefix}stream-binary.bin"; var data = new byte[] { 0x00, 0x01, 0xFF, 0xFE, 0x42 }; await SeedObject(TestBucket, key, data); var ep = CreateEndpointWithOp(S3OperationType.GetObject, TestBucket, $"keyName={key}&streamBody=true"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); using var stream = (Stream)exchange.In.Body!; using var ms = new MemoryStream(); await stream.CopyToAsync(ms); ms.ToArray().Should().BeEquivalentTo(data); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Producer_GetObject_StreamBody_HeadersStillSet() { var prefix = UniquePrefix(); var key = $"{prefix}stream-headers.txt"; await SeedObject(TestBucket, key, "check headers"); var ep = CreateEndpointWithOp(S3OperationType.GetObject, TestBucket, $"keyName={key}&streamBody=true"); var producer = (S3Producer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message()); await producer.Process(exchange); await producer.Stop(); exchange.In.Headers[S3Headers.Key].Should().Be(key); exchange.In.Headers[S3Headers.ETag].Should().NotBeNull(); exchange.In.Headers[S3Headers.ContentType].Should().NotBeNull(); // Cleanup the stream if (exchange.In.Body is Stream s) await s.DisposeAsync(); await CleanupPrefixAsync(TestBucket, prefix); } // ═══════════════════════════════════════════════════════════════════ // CONSUMER — StreamBody // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Consumer_StreamBody_ReceivesStream() { var prefix = UniquePrefix(); await SeedObject(TestBucket, $"{prefix}streamed.txt", "consumer stream data"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&streamBody=true&deleteAfterRead=true&delay=500&initialDelay=100"); Type? bodyType = null; string? bodyContent = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.ArgAt(0); bodyType = ex.In.Body?.GetType(); if (ex.In.Body is Stream stream) { using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true); bodyContent = await reader.ReadToEndAsync(); } tcs.TrySetResult(); }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(30_000)); await consumer.Stop(); bodyType.Should().NotBeNull(); bodyType!.Should().BeAssignableTo(typeof(Stream)); bodyContent.Should().Be("consumer stream data"); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Consumer_StreamBody_HeadersPopulated() { var prefix = UniquePrefix(); await SeedObject(TestBucket, $"{prefix}hdr.txt", "header check"); var ep = CreateEndpoint(TestBucket, $"prefix={prefix}&streamBody=true&deleteAfterRead=true&delay=500&initialDelay=100"); string? key = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { var ex = ci.ArgAt(0); key = (string?)ex.In.Headers[S3Headers.Key]; tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (S3Consumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(30_000)); await consumer.Stop(); key.Should().Be($"{prefix}hdr.txt"); await CleanupPrefixAsync(TestBucket, prefix); } [Fact] public async Task Roundtrip_StreamBody_ProducerUpload_ConsumerStream() { var prefix = UniquePrefix(); var key = $"{prefix}roundtrip-stream.txt"; var content = "Roundtrip streaming test!"; // Upload via producer var putEp = CreateEndpoint(TestBucket, $"keyName={key}"); var producer = (S3Producer)putEp.CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(content))); await producer.Stop(); // Consume via consumer with StreamBody var getEp = CreateEndpoint(TestBucket, $"prefix={prefix}&streamBody=true&deleteAfterRead=true&delay=500&initialDelay=100"); string? received = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.ArgAt(0); if (ex.In.Body is Stream stream) { using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true); received = await reader.ReadToEndAsync(); } tcs.TrySetResult(); }); var consumer = (S3Consumer)getEp.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(30_000)); await consumer.Stop(); received.Should().Be(content); } } Path: redb-route/tests/redb.Route.Tests.S3/S3SharedIdempotencyTests.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.S3/S3SharedIdempotencyTests.cs ---- using System.Collections.Concurrent; using Amazon.S3; using Amazon.S3.Model; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using redb.Route.S3; using Xunit.Abstractions; namespace redb.Route.Tests.S3; /// /// The S3 polling consumer can use a NAMED /// from the context registry — deduplication survives consumer restarts and, with a /// persistent repository, process restarts and scale-out. /// [Trait("Category", "Integration")] public sealed class S3SharedIdempotencyTests : IAsyncLifetime { private const string ServiceUrl = "http://localhost:9000"; private const string AccessKey = "minioadmin"; private const string SecretKey = "minioadmin"; private const string Region = "us-east-1"; private static readonly string TestBucket = $"shared-idem-net{Environment.Version.Major}"; private readonly ITestOutputHelper _output; private IAmazonS3? _rawClient; public S3SharedIdempotencyTests(ITestOutputHelper output) => _output = output; public async Task InitializeAsync() { _rawClient = new AmazonS3Client(AccessKey, SecretKey, new AmazonS3Config { ServiceURL = ServiceUrl, ForcePathStyle = true, AuthenticationRegion = Region, }); try { await _rawClient.EnsureBucketExistsAsync(TestBucket); } catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.Conflict) { } } public Task DisposeAsync() { _rawClient?.Dispose(); return Task.CompletedTask; } [Fact] public async Task NamedRepository_DeduplicationSurvivesConsumerRestart() { var prefix = $"restart-{Guid.NewGuid():N}/"; await _rawClient!.PutObjectAsync(new PutObjectRequest { BucketName = TestBucket, Key = prefix + "obj.txt", ContentBody = "once", }); await using var ctx = new RouteContext(); ctx.AddComponent(new S3Component()); ctx.AddIdempotentRepository("shared", new InMemoryIdempotentRepository()); var endpoint = (S3Endpoint)ctx.GetEndpoint( $"s3://{TestBucket}?serviceUrl={ServiceUrl}&accessKey={AccessKey}&secretKey={SecretKey}" + $"®ion={Region}&forcePathStyle=true&prefix={prefix}&delay=300&initialDelay=100" + "&idempotentRepository=shared&includeBody=false&deleteAfterRead=false"); var received = new ConcurrentBag(); var first = endpoint.CreateConsumer(new CollectingProcessor(received)); await first.Start(); var deadline = DateTime.UtcNow.AddSeconds(8); while (received.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(150); await first.Stop(); var second = endpoint.CreateConsumer(new CollectingProcessor(received)); await second.Start(); await Task.Delay(1200); await second.Stop(); received.Should().HaveCount(1, "a named repository must survive a consumer restart"); } [Fact] public void UnknownRepositoryName_FailsLoud() { var ctx = new RouteContext(); try { ctx.AddComponent(new S3Component()); var endpoint = (S3Endpoint)ctx.GetEndpoint( $"s3://{TestBucket}?serviceUrl={ServiceUrl}&accessKey={AccessKey}&secretKey={SecretKey}" + $"®ion={Region}&forcePathStyle=true&idempotentRepository=typo-name&delay=300"); var consumer = endpoint.CreateConsumer(new CollectingProcessor(new ConcurrentBag())); var act = () => consumer.Start(); act.Should().ThrowAsync() .Where(e => e.Message.Contains("typo-name")).GetAwaiter().GetResult(); } finally { ctx.DisposeAsync().AsTask().GetAwaiter().GetResult(); } } private sealed class CollectingProcessor : IProcessor { private readonly ConcurrentBag _received; internal CollectingProcessor(ConcurrentBag received) => _received = received; public Task Process(IExchange exchange, CancellationToken ct = default) { _received.Add(exchange.In.GetHeader(S3Headers.Key) ?? "?"); return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests.S3/S3TelemetrySmokeTests.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.S3/S3TelemetrySmokeTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.S3; using redb.Route.Telemetry; using redb.Route.Tests.Shared; using Xunit.Abstractions; namespace redb.Route.Tests.S3; /// /// Smoke test for the P1 transport span opened by . /// Requires the S3 test store (docker-compose.tests.yml service s3) on localhost:9000. /// [Trait("Category", "Integration")] public sealed class S3TelemetrySmokeTests { private readonly ITestOutputHelper _output; public S3TelemetrySmokeTests(ITestOutputHelper output) => _output = output; [Fact] public async Task S3Producer_EmitsTransportSpanWithS3Tags() { const string Bucket = "integration-tests"; var qs = "serviceUrl=http://localhost:9000&accessKey=minioadmin&secretKey=minioadmin" + "®ion=us-east-1&forcePathStyle=true"; var uri = EndpointUriParser.Parse($"s3://{Bucket}?{qs}"); var endpoint = (S3Endpoint)new S3Component().CreateEndpoint(uri); var producer = endpoint.CreateProducer(); await producer.Start(); using var capture = new SpanCapture(); // this test's spans only var ex = new Exchange(new Message("hello")); ex.In.Headers[S3Headers.Key] = $"smoke-{Guid.NewGuid():N}.txt"; try { await producer.Process(ex); } catch (Exception ioex) { _output.WriteLine($"S3 Put failed (acceptable for smoke if bucket missing): {ioex.GetType().Name}: {ioex.Message}"); } finally { await producer.Stop(); } var activities = capture.Spans; activities.Should().NotBeEmpty("S3Producer.Process must open a transport span even on failure"); var activity = activities.First(); activity.Source.Name.Should().Be(RouteActivitySource.SourceName); activity.Kind.Should().Be(ActivityKind.Client); activity.GetTagItem("redb.system").Should().Be("s3"); activity.GetTagItem("messaging.destination.name").Should().Be(Bucket); activity.GetTagItem("redb.route.endpoint").Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests.S3/S3TraceTests.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.S3/S3TraceTests.cs ---- using System.Diagnostics; using Amazon.S3; using Amazon.S3.Model; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.S3; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.S3; /// /// A polled object carries no trace context: the consumer opens a root span per routed object, never a child of the /// activity the poll loop inherited from whoever started it, and none for an empty poll. A failed route marks it red. /// The producer marks a failed call red. EnableTelemetry=false opens none of these spans. Each test polls its /// own key prefix and reads only the spans of that endpoint. Requires MinIO at localhost:9000. /// [Trait("Category", "Integration")] public sealed class S3TraceTests : IAsyncLifetime { private const string ServiceUrl = "http://localhost:9000"; private const string AccessKey = "minioadmin"; private const string SecretKey = "minioadmin"; private const string Region = "us-east-1"; private static readonly string Bucket = $"trace-net{Environment.Version.Major}"; private static readonly TimeSpan Wait = TimeSpan.FromSeconds(15); private readonly string _prefix = $"trace-{Guid.NewGuid():N}/"; private IAmazonS3 _raw = null!; public async Task InitializeAsync() { _raw = new AmazonS3Client(AccessKey, SecretKey, new AmazonS3Config { ServiceURL = ServiceUrl, ForcePathStyle = true, AuthenticationRegion = Region }); try { await _raw.EnsureBucketExistsAsync(Bucket); } catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.Conflict) { } } public Task DisposeAsync() { _raw.Dispose(); return Task.CompletedTask; } private string Uri(string extra) => $"s3://{Bucket}?serviceUrl={ServiceUrl}&accessKey={AccessKey}&secretKey={SecretKey}®ion={Region}" + $"&forcePathStyle=true&prefix={_prefix}&{extra}"; private string ConsumerUri => Uri("delay=200&initialDelay=50&includeBody=false&deleteAfterRead=true"); private RouteTelemetryProbe Spans(ActivityKind kind) => new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_prefix, StringComparison.Ordinal) == true); private Task Seed(string name) => _raw.PutObjectAsync(new PutObjectRequest { BucketName = Bucket, Key = _prefix + name, ContentBody = "payload" }); private async Task StartConsumer(Action step, bool telemetry = true) { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new S3Component()); ctx.AddRoutes(r => r.From(ConsumerUri).Process(step)); using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start()) await ctx.Start(); return ctx; } private static async Task Until(Func done) { var deadline = DateTime.UtcNow + Wait; while (!done() && DateTime.UtcNow < deadline) await Task.Delay(100); } [Fact] public async Task Each_object_opens_a_root_span_even_under_an_ambient_activity() { await Seed("a.txt"); await Seed("b.txt"); using var probe = Spans(ActivityKind.Consumer); await using (await StartConsumer(_ => { })) await Until(() => probe.Activities.Count >= 2); probe.Activities.Should().HaveCount(2, "one span per routed object"); probe.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId), "an object carries no context, so its span starts a trace rather than joining the host's"); } [Fact] public async Task An_empty_poll_opens_no_span() { using var probe = Spans(ActivityKind.Consumer); await using (await StartConsumer(_ => { })) await Task.Delay(1500); // several polls of an empty prefix probe.Activities.Should().BeEmpty(); } [Fact] public async Task A_failed_route_marks_the_span_red() { await Seed("fail.txt"); using var probe = Spans(ActivityKind.Consumer); await using (await StartConsumer(_ => throw new InvalidOperationException("route failed"))) await Until(() => probe.Activities.Count >= 1); probe.Activities.Should().NotBeEmpty(); probe.Activities.Should().OnlyContain(a => a.Status == ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span() { await Seed("off.txt"); using var probe = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_prefix, StringComparison.Ordinal) == true); var routed = new TaskCompletionSource(); await using (await StartConsumer(_ => routed.TrySetResult(), telemetry: false)) (await Task.WhenAny(routed.Task, Task.Delay(Wait))).Should().Be(routed.Task); probe.Activities.Should().BeEmpty(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task A_failed_call_marks_the_producer_span_red_and_tracing_off_opens_none(bool telemetry) { using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start(); using var probe = new RouteTelemetryProbe(a => a.Kind == ActivityKind.Client && a.TraceId == outer.TraceId); await using var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new S3Component()); await ctx.Start(); using var template = new ProducerTemplate(ctx); template.Start(); var exchange = new Exchange(new Message(null)); exchange.In.Headers[S3Headers.Operation] = "GetObject"; exchange.In.Headers[S3Headers.Key] = _prefix + "missing.txt"; var uri = $"s3://{Bucket}?serviceUrl={ServiceUrl}&accessKey={AccessKey}&secretKey={SecretKey}®ion={Region}" + "&forcePathStyle=true"; var act = () => template.SendAsync(uri, exchange); await act.Should().ThrowAsync(); if (telemetry) probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); else probe.Activities.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.S3/redb.Route.Tests.S3.csproj 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.S3/redb.Route.Tests.S3.csproj ----