Path: redb-route/redb.Route.S3/S3Component.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.S3/S3Component.cs
----
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.S3;
///
/// S3/MinIO transport component for redb.Route.
/// Scheme: s3.
///
/// URI format (consumer): s3://bucket-name?region=us-east-1&accessKey=KEY&secretKey=SECRET&prefix=data/
///
///
/// URI format (producer): s3://bucket-name?region=us-east-1&accessKey=KEY&secretKey=SECRET&keyName=folder/file.txt
///
///
/// URI format (operation): s3:CopyObject:bucket-name?region=us-east-1&accessKey=KEY&secretKey=SECRET
///
///
/// Provides enterprise-grade object storage integration compatible with AWS S3 and MinIO:
/// polling consumer with prefix filtering, idempotency, move/delete-after-read;
/// multi-operation producer with multipart upload, SSE, presigned URLs, versioning,
/// tagging, ACL management, and more.
///
///
public sealed class S3Component : ComponentBase
{
///
public override string Scheme => "s3";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new S3EndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new S3Endpoint(uri, this, options);
}
}
///
/// S3 endpoint. Creates either a consumer (for polling a bucket)
/// or a producer (for uploading/managing objects).
///
/// The path part of the URI is parsed as [OPERATION:]bucket-name.
/// When an operation prefix is present (e.g. s3:CopyObject:my-bucket),
/// the producer dispatches that specific operation.
/// When no operation is specified, the default is for producer.
///
///
public sealed class S3Endpoint : EndpointBase, IDisposable
{
private IAmazonS3? _client;
private readonly SemaphoreSlim _clientLock = new(1, 1);
/// Parsed S3 operation type (default: PutObject for producer).
public S3OperationType OperationType { get; }
/// Bucket name parsed from the URI path.
public string BucketName { get; }
/// Logger from the parent component.
internal ILogger? Logger { get; }
/// Typed options (exposed for consumer/producer).
internal S3EndpointOptions EndpointOptions => Options;
/// Creates an S3 endpoint.
public S3Endpoint(EndpointUri uri, S3Component component, S3EndpointOptions options)
: base(uri, component, options)
{
Logger = component.Logger;
(OperationType, BucketName) = ParsePath(uri.Path);
}
///
public override IProducer CreateProducer() => new S3Producer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new S3Consumer(this, processor, Options);
}
/// Gets or creates a shared client.
internal async Task GetOrCreateClientAsync(CancellationToken ct = default)
{
if (_client is not null)
return _client;
await _clientLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_client is not null)
return _client;
_client = BuildClient();
var (region, serviceUrl) = S3ClientConfigSupport.Target(_client.Config);
Logger?.LogInformation("S3 client created: Region={Region}, ServiceUrl={ServiceUrl}, Bucket={Bucket}, ConnectionFactory={ConnectionFactory}",
region, serviceUrl, BucketName, string.IsNullOrEmpty(Options.ConnectionFactory) ? "-" : Options.ConnectionFactory);
return _client;
}
finally
{
_clientLock.Release();
}
}
///
public override async Task Stop(CancellationToken ct = default)
{
if (_client is not null)
{
try { _client.Dispose(); }
catch (Exception ex) { Logger?.LogWarning(ex, "Error disposing S3 client"); }
_client = null;
}
Logger?.LogInformation("S3 endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger));
await Task.CompletedTask.ConfigureAwait(false);
}
///
public void Dispose()
{
_client?.Dispose();
_client = null;
_clientLock.Dispose();
}
// ── Helpers ──
private IAmazonS3 BuildClient()
{
// 1. Named factory from registry — a set-but-unknown name fails loud, never a
// silent fallback to URI parameters.
if (!string.IsNullOrEmpty(Options.ConnectionFactory))
{
var context = (Component as S3Component)?.Context;
var registryFactory = context.GetRequiredFromRegistry(Options.ConnectionFactory);
Logger?.LogDebug("S3: using ConnectionFactory '{Name}' from registry", Options.ConnectionFactory);
return registryFactory.Build();
}
// 2. Build from URI parameters
var config = new AmazonS3Config { ForcePathStyle = Options.ForcePathStyle };
S3ClientConfigSupport.Apply(config,
Options.ConnectionTimeout, Options.SocketTimeout, Options.MaxConnections,
Options.RetryCount, Options.RetryMode, Options.TrustAllCertificates);
if (!string.IsNullOrEmpty(Options.ServiceUrl))
{
config.ServiceURL = Options.ServiceUrl;
config.AuthenticationRegion = Options.Region;
}
else
{
config.RegionEndpoint = RegionEndpoint.GetBySystemName(Options.Region);
}
if (!string.IsNullOrEmpty(Options.ProxyHost) && Options.ProxyPort > 0)
{
config.ProxyHost = Options.ProxyHost;
config.ProxyPort = Options.ProxyPort;
}
var credentials = ResolveCredentials();
return new AmazonS3Client(credentials, config);
}
private AWSCredentials ResolveCredentials()
{
if (Options.UseDefaultCredentialsProvider)
// SDK v4: the non-deprecated default-chain resolver (env -> profile -> IMDS etc.)
return Amazon.Runtime.Credentials.DefaultAWSCredentialsIdentityResolver.GetCredentials();
if (!string.IsNullOrEmpty(Options.ProfileName))
{
var chain = new Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain();
if (chain.TryGetAWSCredentials(Options.ProfileName, out var profileCreds))
return profileCreds;
throw new InvalidOperationException($"AWS profile '{Options.ProfileName}' not found.");
}
if (!string.IsNullOrEmpty(Options.SessionToken))
return new SessionAWSCredentials(Options.AccessKey, Options.SecretKey, Options.SessionToken);
return new BasicAWSCredentials(Options.AccessKey, Options.SecretKey);
}
///
/// Parses the URI path. Supports:
///
/// - bucket-name → (PutObject, "bucket-name")
/// - CopyObject:bucket-name → (CopyObject, "bucket-name")
///
///
private static (S3OperationType Op, string Bucket) ParsePath(string path)
{
// Strip leading slashes
path = path.TrimStart('/');
if (string.IsNullOrEmpty(path))
throw new ArgumentException("S3 URI must include a bucket name in the path.");
// Try to parse "OPERATION:bucket" or "OPERATION/bucket"
var colonIndex = path.IndexOf(':');
if (colonIndex > 0)
{
var opStr = path[..colonIndex];
var bucket = path[(colonIndex + 1)..];
if (Enum.TryParse(opStr, ignoreCase: true, out var op) && !string.IsNullOrEmpty(bucket))
return (op, bucket);
}
// No operation prefix → just bucket name, default to PutObject
return (S3OperationType.PutObject, path);
}
}