Bundle: redb-route / redb.Route.S3 (redb.Route.S3.txt), 17 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/redb.Route.S3/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.S3;
///
/// Extension methods for registering the S3 transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that
/// s3:// URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteS3();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteS3(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.S3/Fluent/S3Dsl.Build.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/Fluent/S3Dsl.Build.cs
----
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.S3;
/// URI assembly of .
public sealed partial class S3Builder
{
// ═══════════════════════════════════════════════════════════════════
// BUILD
// ═══════════════════════════════════════════════════════════════════
/// Builds the S3 endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("s3://");
// Operation prefix: "s3://PutObject:bucket-name"
if (_operation.HasValue)
{
sb.Append(_operation.Value);
sb.Append(':');
}
sb.Append(_bucketName);
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (!string.IsNullOrEmpty(value)) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolExplicit(string key, bool? value)
{
if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant());
}
// Connection / Credentials
AppendIf("serviceUrl", _serviceUrl);
AppendIf("region", _region);
AppendIf("accessKey", _accessKey);
AppendIf("secretKey", _secretKey);
AppendIf("sessionToken", _sessionToken);
AppendIf("profileName", _profileName);
AppendBool("forcePathStyle", _forcePathStyle);
AppendBool("useDefaultCredentialsProvider", _useDefaultCredentialsProvider);
AppendIf("connectionFactory", _connectionFactory);
AppendIf("proxyHost", _proxyHost);
AppendIf("proxyPort", _proxyPort);
AppendIf("connectionTimeout", _connectionTimeout);
AppendIf("socketTimeout", _socketTimeout);
AppendIf("maxConnections", _maxConnections);
AppendIf("retryCount", _retryCount);
AppendIf("retryMode", _retryMode);
AppendBool("trustAllCertificates", _trustAllCertificates);
// Common
AppendBool("autoCreateBucket", _autoCreateBucket);
AppendIf("prefix", _prefix);
AppendIf("delimiter", _delimiter);
AppendBoolExplicit("includeBody", _includeBody);
AppendBool("streamBody", _streamBody);
AppendBool("ignoreBody", _ignoreBody);
AppendBool("includeFolders", _includeFolders);
// Consumer
AppendIf("delay", _delay);
AppendIf("initialDelay", _initialDelay);
AppendIf("maxMessagesPerPoll", _maxMessagesPerPoll);
AppendBoolExplicit("deleteAfterRead", _deleteAfterRead);
AppendBool("moveAfterRead", _moveAfterRead);
AppendIf("destinationBucket", _destinationBucket);
AppendIf("destinationBucketPrefix", _destinationBucketPrefix);
AppendIf("destinationBucketSuffix", _destinationBucketSuffix);
AppendBool("removePrefixOnMove", _removePrefixOnMove);
AppendIf("fileName", _fileName);
AppendIf("include", _include);
AppendIf("exclude", _exclude);
AppendBool("sendEmptyMessageWhenIdle", _sendEmptyMessageWhenIdle);
AppendIf("doneFileName", _doneFileName);
AppendIf("sortBy", _sortBy);
AppendIf("minAge", _minAge);
AppendIf("maxAge", _maxAge);
AppendBool("idempotent", _idempotent);
AppendIf("idempotentRepository", _idempotentRepository);
// Producer
AppendIf("keyName", _keyName);
AppendIf("storageClass", _storageClass);
AppendIf("contentType", _contentType);
AppendIf("contentDisposition", _contentDisposition);
AppendIf("contentEncoding", _contentEncoding);
AppendIf("cacheControl", _cacheControl);
AppendIf("cannedAcl", _cannedAcl);
AppendBool("multiPartUpload", _multiPartUpload);
AppendIf("partSize", _partSize);
AppendBool("conditionalWrite", _conditionalWrite);
// SSE
AppendIf("serverSideEncryption", _serverSideEncryption);
AppendIf("kmsKeyId", _kmsKeyId);
AppendIf("customerAlgorithm", _customerAlgorithm);
AppendIf("customerKeyId", _customerKeyId);
AppendIf("customerKeyMD5", _customerKeyMD5);
// Presigned
AppendIf("presignedUrlExpiration", _presignedUrlExpiration);
// Streaming Upload
// Metadata
AppendIf("metadata", _metadata);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(S3Builder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.S3/Fluent/S3Dsl.Endpoints.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/Fluent/S3Dsl.Endpoints.cs
----
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.S3;
/// Consumer, producer, encryption, presigned-URL and streaming-upload verbs of .
public sealed partial class S3Builder
{
// ═══════════════════════════════════════════════════════════════════
// CONSUMER
// ═══════════════════════════════════════════════════════════════════
/// Polling delay in milliseconds between scans. Default 60000.
public S3Builder Delay(int ms) { _delay = ms.ToString(); return this; }
/// Polling delay from an expression.
public S3Builder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; }
/// Initial delay before first poll in milliseconds. Default 1000.
public S3Builder InitialDelay(int ms) { _initialDelay = ms.ToString(); return this; }
/// Initial delay from an expression.
public S3Builder InitialDelay(IExpression ms) { _initialDelay = ms.ToTemplateString(); return this; }
/// Max objects per poll. 0 = unlimited. Default 10.
public S3Builder MaxMessagesPerPoll(int max) { _maxMessagesPerPoll = max.ToString(); return this; }
/// Max objects per poll from an expression.
public S3Builder MaxMessagesPerPoll(IExpression max) { _maxMessagesPerPoll = max.ToTemplateString(); return this; }
/// Delete objects from S3 after successful consumption. Default true.
public S3Builder DeleteAfterRead(bool delete = true) { _deleteAfterRead = delete; return this; }
/// Move objects to destination bucket after consumption instead of deleting.
public S3Builder MoveAfterRead(string destinationBucket, string? prefix = null, string? suffix = null)
{
_moveAfterRead = true;
_destinationBucket = destinationBucket;
_destinationBucketPrefix = prefix;
_destinationBucketSuffix = suffix;
return this;
}
/// Remove source prefix from key when moving objects.
public S3Builder RemovePrefixOnMove() { _removePrefixOnMove = true; return this; }
/// Consume only a specific object by key name.
public S3Builder FileName(string name) { _fileName = name; return this; }
/// Glob pattern to include (e.g. "*.csv", "data/*.json").
public S3Builder Include(string pattern) { _include = pattern; return this; }
/// Glob pattern to exclude (e.g. "*.tmp").
public S3Builder Exclude(string pattern) { _exclude = pattern; return this; }
/// Send empty exchange when poll returns no objects (heartbeat).
public S3Builder SendEmptyMessageWhenIdle() { _sendEmptyMessageWhenIdle = true; return this; }
/// Done file marker pattern (e.g. "${file:name}.done").
public S3Builder DoneFileName(string pattern) { _doneFileName = pattern; return this; }
/// Done file marker from an expression.
public S3Builder DoneFileName(IExpression pattern) { _doneFileName = pattern.ToTemplateString(); return this; }
/// Sort order: None, Key, KeyDesc, LastModified, LastModifiedDesc, Size, SizeDesc.
public S3Builder SortBy(S3SortBy sort) { _sortBy = sort.ToString(); return this; }
/// Minimum object age in milliseconds before consumption.
public S3Builder MinAge(long ms) { _minAge = ms.ToString(); return this; }
/// Minimum object age from an expression.
public S3Builder MinAge(IExpression ms) { _minAge = ms.ToTemplateString(); return this; }
/// Maximum object age in milliseconds. 0 = no limit.
public S3Builder MaxAge(long ms) { _maxAge = ms.ToString(); return this; }
/// Maximum object age from an expression.
public S3Builder MaxAge(IExpression ms) { _maxAge = ms.ToTemplateString(); return this; }
/// Enable idempotent consumer (key = object Key + ETag + Size).
public S3Builder Idempotent() { _idempotent = true; return this; }
/// Named IIdempotentRepository from the context registry (survives restarts).
public S3Builder IdempotentRepository(string name) { _idempotentRepository = name; return this; }
// ═══════════════════════════════════════════════════════════════════
// PRODUCER
// ═══════════════════════════════════════════════════════════════════
/// Dynamic object key name for upload. Supports expressions.
public S3Builder KeyName(string name) { _keyName = name; return this; }
/// Dynamic object key from an expression (e.g. Header("fileName")).
public S3Builder KeyName(IExpression name) { _keyName = name.ToTemplateString(); return this; }
/// S3 storage class (STANDARD, GLACIER, INTELLIGENT_TIERING, etc.).
public S3Builder StorageClass(string storageClass) { _storageClass = storageClass; return this; }
/// Content-Type for uploaded objects. Empty = auto-detect.
public S3Builder ContentType(string contentType) { _contentType = contentType; return this; }
/// Content-Disposition for uploaded objects.
public S3Builder ContentDisposition(string disposition) { _contentDisposition = disposition; return this; }
/// Content-Encoding for uploaded objects (e.g. "gzip").
public S3Builder ContentEncoding(string encoding) { _contentEncoding = encoding; return this; }
/// Cache-Control header for uploaded objects.
public S3Builder CacheControl(string cacheControl) { _cacheControl = cacheControl; return this; }
/// Canned ACL for uploaded objects.
public S3Builder CannedAcl(S3CannedAcl acl) { _cannedAcl = acl.ToString(); return this; }
/// Enable multipart upload for large files.
public S3Builder MultiPartUpload() { _multiPartUpload = true; return this; }
/// Part size in bytes for multipart upload. Minimum 5 MB. Default 25 MB.
public S3Builder PartSize(long bytes) { _partSize = bytes.ToString(); return this; }
/// Conditional write — fail if object already exists.
public S3Builder ConditionalWrite() { _conditionalWrite = true; return this; }
// ═══════════════════════════════════════════════════════════════════
// ENCRYPTION (convenience methods)
// ═══════════════════════════════════════════════════════════════════
/// Enable SSE-S3 encryption (AES-256, managed by AWS).
public S3Builder UseAes256Encryption()
{
_serverSideEncryption = S3ServerSideEncryption.Aes256.ToString(); return this;
}
/// Enable SSE-KMS encryption with the given AWS KMS key ID.
public S3Builder UseKmsEncryption(string kmsKeyId)
{
_serverSideEncryption = S3ServerSideEncryption.AwsKms.ToString();
_kmsKeyId = kmsKeyId;
return this;
}
/// Enable SSE-C encryption with customer-provided key material.
public S3Builder UseCustomerEncryption(string algorithm, string keyId, string? keyMD5 = null)
{
_serverSideEncryption = S3ServerSideEncryption.CustomerKey.ToString();
_customerAlgorithm = algorithm;
_customerKeyId = keyId;
_customerKeyMD5 = keyMD5;
return this;
}
// ═══════════════════════════════════════════════════════════════════
// PRESIGNED URL
// ═══════════════════════════════════════════════════════════════════
/// Presigned URL expiration in milliseconds. Default 3600000 (1h).
public S3Builder PresignedUrlExpiration(long ms) { _presignedUrlExpiration = ms.ToString(); return this; }
// Streaming Upload verbs removed in the options sweep: the mode was never
// implemented, and accumulate-then-write belongs to the core Aggregate(...) EIP.
// ═══════════════════════════════════════════════════════════════════
// METADATA
// ═══════════════════════════════════════════════════════════════════
/// User metadata as comma-separated key=value pairs (e.g. "author=redb,env=prod").
public S3Builder Metadata(string kvPairs) { _metadata = kvPairs; return this; }
}
Path: redb-route/redb.Route.S3/Fluent/S3Dsl.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/Fluent/S3Dsl.cs
----
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.S3;
///
/// Fluent API for S3/MinIO endpoints.
///
/// // Consumer: poll bucket for new CSV files
/// .From(S3.Bucket("my-bucket")
/// .ServiceUrl("http://localhost:9000").ForcePathStyle()
/// .AccessKey("minioadmin").SecretKey("minioadmin")
/// .Prefix("incoming/").Include("*.csv")
/// .DeleteAfterRead().Delay(30_000))
///
/// // Producer: upload to S3 with SSE-KMS
/// .To(S3.Bucket("my-bucket")
/// .Region("eu-west-1").AccessKey("KEY").SecretKey("SECRET")
/// .KeyName(Expression.Header("fileName"))
/// .MultiPartUpload().PartSize(10_485_760)
/// .UseKmsEncryption("my-key-id")
/// .StorageClass("INTELLIGENT_TIERING"))
///
/// // Presigned URL generation
/// .To(S3.Bucket("my-bucket", S3OperationType.CreateDownloadLink)
/// .AccessKey("KEY").SecretKey("SECRET")
/// .PresignedUrlExpiration(7_200_000))
///
///
public static class S3
{
/// Creates an S3 endpoint for the given bucket name.
public static S3Builder Bucket(string bucketName)
=> new(bucketName, null);
/// Creates an S3 endpoint for a bucket with a specific producer operation.
public static S3Builder Bucket(string bucketName, S3OperationType operation)
=> new(bucketName, operation);
}
///
/// Fluent builder for S3 endpoint URIs. Maps to all properties.
///
public sealed partial class S3Builder
{
private readonly string _bucketName;
private readonly S3OperationType? _operation;
// Connection / Credentials
private string? _serviceUrl;
private string? _region;
private string? _accessKey;
private string? _secretKey;
private string? _sessionToken;
private string? _profileName;
private bool _forcePathStyle;
private bool _useDefaultCredentialsProvider;
private string? _connectionFactory;
private string? _proxyHost;
private string? _proxyPort;
private string? _connectionTimeout;
private string? _socketTimeout;
private string? _maxConnections;
private string? _retryCount;
private string? _retryMode;
private bool _trustAllCertificates;
// Common
private bool _autoCreateBucket;
private string? _prefix;
private string? _delimiter;
private bool? _includeBody;
private bool _streamBody;
private bool _ignoreBody;
private bool _includeFolders;
// Consumer
private string? _delay;
private string? _initialDelay;
private string? _maxMessagesPerPoll;
private bool? _deleteAfterRead;
private bool _moveAfterRead;
private string? _destinationBucket;
private string? _destinationBucketPrefix;
private string? _destinationBucketSuffix;
private bool _removePrefixOnMove;
private string? _fileName;
private string? _include;
private string? _exclude;
private bool _sendEmptyMessageWhenIdle;
private string? _doneFileName;
private string? _sortBy;
private string? _minAge;
private string? _maxAge;
private bool _idempotent;
private string? _idempotentRepository;
// Producer
private string? _keyName;
private string? _storageClass;
private string? _contentType;
private string? _contentDisposition;
private string? _contentEncoding;
private string? _cacheControl;
private string? _cannedAcl;
private bool _multiPartUpload;
private string? _partSize;
private bool _conditionalWrite;
// SSE
private string? _serverSideEncryption;
private string? _kmsKeyId;
private string? _customerAlgorithm;
private string? _customerKeyId;
private string? _customerKeyMD5;
// Presigned
private string? _presignedUrlExpiration;
// Streaming Upload
// Metadata
private string? _metadata;
internal S3Builder(string bucketName, S3OperationType? operation)
{
ArgumentException.ThrowIfNullOrWhiteSpace(bucketName);
_bucketName = bucketName;
_operation = operation;
}
// ═══════════════════════════════════════════════════════════════════
// CONNECTION / CREDENTIALS
// ═══════════════════════════════════════════════════════════════════
/// Custom service URL for S3-compatible storage (MinIO, Ceph, etc.).
public S3Builder ServiceUrl(string url) { _serviceUrl = url; return this; }
/// Custom service URL from an expression.
public S3Builder ServiceUrl(IExpression url) { _serviceUrl = url.ToTemplateString(); return this; }
/// AWS region (e.g. "us-east-1"). Default "us-east-1".
public S3Builder Region(string region) { _region = region; return this; }
/// AWS region from an expression.
public S3Builder Region(IExpression region) { _region = region.ToTemplateString(); return this; }
/// AWS access key ID.
public S3Builder AccessKey(string key) { _accessKey = key; return this; }
/// AWS access key from an expression.
public S3Builder AccessKey(IExpression key) { _accessKey = key.ToTemplateString(); return this; }
/// AWS secret access key.
public S3Builder SecretKey(string key) { _secretKey = key; return this; }
/// AWS secret key from an expression.
public S3Builder SecretKey(IExpression key) { _secretKey = key.ToTemplateString(); return this; }
/// AWS session token for temporary credentials (STS).
public S3Builder SessionToken(string token) { _sessionToken = token; return this; }
/// Session token from an expression.
public S3Builder SessionToken(IExpression token) { _sessionToken = token.ToTemplateString(); return this; }
/// AWS named profile from ~/.aws/credentials.
public S3Builder ProfileName(string profile) { _profileName = profile; return this; }
/// Use path-style URLs. Required for MinIO and most S3-compatible stores.
public S3Builder ForcePathStyle() { _forcePathStyle = true; return this; }
/// Use the default AWS credentials provider chain.
public S3Builder UseDefaultCredentials() { _useDefaultCredentialsProvider = true; return this; }
/// Named connection factory reference from DI.
public S3Builder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// HTTP proxy configuration.
public S3Builder Proxy(string host, int port)
{
_proxyHost = host; _proxyPort = port.ToString(); return this;
}
/// HTTP proxy with host from expression.
public S3Builder Proxy(IExpression host, int port)
{
_proxyHost = host.ToTemplateString(); _proxyPort = port.ToString(); return this;
}
/// Connection timeout in milliseconds. Default 30000.
public S3Builder ConnectionTimeout(int ms) { _connectionTimeout = ms.ToString(); return this; }
/// Connection timeout from an expression.
public S3Builder ConnectionTimeout(IExpression ms) { _connectionTimeout = ms.ToTemplateString(); return this; }
/// Socket/read timeout in milliseconds. Default 60000.
public S3Builder SocketTimeout(int ms) { _socketTimeout = ms.ToString(); return this; }
/// Socket timeout from an expression.
public S3Builder SocketTimeout(IExpression ms) { _socketTimeout = ms.ToTemplateString(); return this; }
/// Max connections in the SDK pool. Default 50.
public S3Builder MaxConnections(int count) { _maxConnections = count.ToString(); return this; }
/// Retry count for failed requests. Default 3.
public S3Builder RetryCount(int count) { _retryCount = count.ToString(); return this; }
/// Retry mode: "standard" or "adaptive".
public S3Builder RetryMode(string mode) { _retryMode = mode; return this; }
/// Trust all SSL certificates (for self-signed certs).
public S3Builder TrustAllCertificates() { _trustAllCertificates = true; return this; }
// ═══════════════════════════════════════════════════════════════════
// COMMON
// ═══════════════════════════════════════════════════════════════════
/// Auto-create the bucket if it doesn't exist.
public S3Builder AutoCreateBucket() { _autoCreateBucket = true; return this; }
/// Prefix filter for object listing.
public S3Builder Prefix(string prefix) { _prefix = prefix; return this; }
/// Delimiter for ListObjectsV2 key grouping (typically "/").
public S3Builder Delimiter(string delimiter) { _delimiter = delimiter; return this; }
/// Download object body into exchange. Default true.
public S3Builder IncludeBody(bool include = true) { _includeBody = include; return this; }
/// Set exchange body to S3 response Stream instead of byte[].
public S3Builder StreamBody() { _streamBody = true; return this; }
/// Ignore object body completely (metadata mode).
public S3Builder IgnoreBody() { _ignoreBody = true; return this; }
/// Include folder/directory markers in consumer results.
public S3Builder IncludeFolders() { _includeFolders = true; return this; }
}
Path: redb-route/redb.Route.S3/README.md
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/README.md
----
# redb.Route.S3
> Documentation and articles:
S3/MinIO transport for the **redb.Route** ESB framework.
Polling consumer with prefix filtering, glob patterns, idempotency, done-file markers, move/delete after read.
Multi-operation producer with multipart upload, server-side encryption (SSE-S3, SSE-KMS, SSE-C), presigned URLs,
tagging, versioning, ACL management, streaming upload, and Glacier restore.
Compatible with **AWS S3** and **MinIO** (via `ForcePathStyle`).
[](https://www.nuget.org/packages/redb.Route.S3)
[](../../LICENSE)
| | |
|---|---|
| **Scheme** | `s3` |
| **NuGet** | `redb.Route.S3` |
| **Dependency** | AWSSDK.S3 4.0.20.3 |
| **Namespace** | `redb.Route.S3` |
---
## Quick Start
```csharp
services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteS3();
// Poll MinIO bucket for new CSV files
route.AddRoutes(r => r
.From(S3.Bucket("incoming")
.ServiceUrl("http://localhost:9000").ForcePathStyle()
.AccessKey("minioadmin").SecretKey("minioadmin")
.Prefix("data/").Include("*.csv")
.DeleteAfterRead().Delay(30_000))
.RouteId("s3-import")
.To("log:received"));
// Upload to AWS S3 with SSE-KMS
route.AddRoutes(r => r
.From("direct:upload")
.RouteId("s3-export")
.To(S3.Bucket("reports")
.Region("eu-west-1")
.AccessKey("AKIA...").SecretKey("...")
.KeyName(new HeaderExpression("fileName"))
.UseKmsEncryption("arn:aws:kms:eu-west-1:123456:key/abc")
.StorageClass("INTELLIGENT_TIERING")));
});
```
---
## URI Format
```
s3://bucket-name?option=value&...
s3:OPERATION:bucket-name?option=value&...
```
**Consumer** — polls the bucket with `ListObjectsV2`, downloads matching objects:
```
s3://my-bucket?accessKey=KEY&secretKey=SECRET&prefix=data/&include=*.json&delay=30000
```
**Producer** — default operation `PutObject` (upload):
```
s3://my-bucket?accessKey=KEY&secretKey=SECRET&keyName=output/${header.id}.json
```
**Producer with operation** — specify operation before bucket name:
```
s3:CopyObject:my-bucket?accessKey=KEY&secretKey=SECRET
s3:CreateDownloadLink:my-bucket?accessKey=KEY&secretKey=SECRET&presignedUrlExpiration=7200000
s3:ListObjects:my-bucket?accessKey=KEY&secretKey=SECRET&prefix=archive/
```
---
## Producer Operations
22 operations available, set via URI (`s3:OPERATION:bucket`) or `redbS3.Operation` header at runtime.
### Object Operations
| Operation | Description | Key Headers |
|---|---|---|
| `PutObject` | Upload an object (default) | Body → object content |
| `GetObject` | Download an object | `redbS3.Key` → body |
| `GetObjectRange` | Download byte range | `redbS3.RangeStart`, `redbS3.RangeEnd` |
| `DeleteObject` | Delete a single object | `redbS3.Key` |
| `DeleteObjects` | Batch delete | `redbS3.KeysToDelete` (`List`) |
| `CopyObject` | Copy object | `redbS3.DestinationBucket`, `redbS3.DestinationKey` |
| `ListObjects` | List objects in bucket | Prefix/Delimiter from options |
| `HeadObject` | Get metadata (no body) | `redbS3.Key` |
### Presigned URLs
| Operation | Description | Output Header |
|---|---|---|
| `CreateDownloadLink` | Pre-signed GET URL | `redbS3.PresignedUrl` |
| `CreateUploadLink` | Pre-signed PUT URL | `redbS3.PresignedUrl` |
Expiration controlled by `presignedUrlExpiration` (default: 3600000 ms = 1 hour).
### Bucket Operations
| Operation | Description | Output Header |
|---|---|---|
| `CreateBucket` | Create a new bucket | — |
| `DeleteBucket` | Delete a bucket | — |
| `HeadBucket` | Check bucket existence | `redbS3.BucketExists` |
| `ListBuckets` | List all account buckets | Body → `List` |
### Tagging
| Operation | Description | Headers |
|---|---|---|
| `GetObjectTagging` | Get tags | Body → `List` |
| `PutObjectTagging` | Set tags | `redbS3.ObjectTags` (`Dictionary`) |
| `DeleteObjectTagging` | Remove all tags | `redbS3.Key` |
### ACL
| Operation | Description |
|---|---|
| `GetObjectAcl` | Body → `S3AccessControlList` |
| `PutObjectAcl` | `redbS3.CannedAcl` header or option |
### Versioning
| Operation | Description | Headers |
|---|---|---|
| `GetBucketVersioning` | Get versioning config | Body → status string |
| `PutBucketVersioning` | Enable/suspend versioning | `redbS3.VersioningStatus` (`"Enabled"` / `"Suspended"`) |
### Glacier
| Operation | Description | Headers |
|---|---|---|
| `RestoreObject` | Initiate Glacier restore | `redbS3.RestoreDays`, `redbS3.RestoreTier` (`Standard`/`Bulk`/`Expedited`) |
---
## Consumer
Polls S3 bucket using `ListObjectsV2` with automatic pagination.
### Pipeline
1. **List** — `ListObjectsV2` with `Prefix`. Without `SortBy` the listing streams page by
page with an early exit at `MaxMessagesPerPoll`; with `SortBy` the full listing is
buffered (sorting honestly needs it — mind the cost on big buckets).
2. **Filter** — glob `Include`/`Exclude` patterns (matched against the FILE NAME, the last
`/`-segment of the key), `MinAge`/`MaxAge`, folder exclusion
3. **Sort** — `SortBy` (Key, LastModified, Size + Desc variants)
4. **Limit** — `MaxMessagesPerPoll` (default: 10, 0 = unlimited)
5. **Per object**:
- Done-file check (`DoneFileName` pattern; `${file:name}` expands to the FULL object key, `${file:name.noext}` to the key without the extension, `${file:ext}` to the extension, `${file:parent}` to the key prefix before the last `/`; an unknown key fails validation)
- Idempotency check (in-memory, key = `Key + ETag + Size`)
- Download body (or stream; with `IncludeBody=false` no content is downloaded at all)
- Process exchange
- Post-process **only when the exchange succeeded** (no unhandled exception, not marked rollback-only by
`.RollbackAll()`): `DeleteAfterRead` (default) or
`MoveAfterRead`. A failed object stays in place and is retried on the next poll; with
`Idempotent` enabled, only successfully processed objects are marked as seen. As in Apache Camel's
aws2-s3 there is no `moveFailed`: a route that wants to set a failed object aside handles the failure itself.
### Move After Read
```csharp
.From(S3.Bucket("incoming")
.AccessKey("KEY").SecretKey("SECRET")
.MoveAfterRead("archive", prefix: "processed/")
.RemovePrefixOnMove())
```
Objects are copied to the destination bucket then deleted from source.
Destination key shaping: `RemovePrefixOnMove` strips the source `Prefix`,
`DestinationBucketPrefix` is prepended, and `DestinationBucketSuffix` is inserted BEFORE the
file extension (`report.csv` + suffix `-done` → `report-done.csv`; appended at the end when
there is no extension). A failed delete after a successful copy logs the duplication and
moves on — it never fails the poll.
### Done File Markers
```csharp
.From(S3.Bucket("data")
.AccessKey("KEY").SecretKey("SECRET")
.DoneFileName("${file:name}.done"))
```
Consumer only processes `report.csv` when `report.csv.done` exists in the same prefix.
### Idempotency
```csharp
.From(S3.Bucket("data")
.AccessKey("KEY").SecretKey("SECRET")
.Idempotent())
```
Uses an in-memory repository keyed by `Key + ETag + Size` with double-buffer eviction at
10K entries (up to 2×10K of history is retained). The mark is written only after a
SUCCESSFUL exchange. For a custom idempotency key use the route-level
`IdempotentConsumer(...)` EIP with a real expression.
For deduplication that survives restarts and scale-out, use a NAMED repository instead —
the same `IIdempotentRepository` contract the route-level EIP uses (two-phase
Add → process → Confirm/Remove, so a concurrent consumer cannot take the same object twice):
```csharp
context.AddIdempotentRepository("s3-dedup", myRedbIdempotentRepository);
// s3://data?...&idempotentRepository=s3-dedup
```
---
## Connection & Credentials
Credential resolution order:
1. `UseDefaultCredentialsProvider` → AWS default chain (env vars, instance profile, ECS task role)
2. `ProfileName` → named profile from `~/.aws/credentials`
3. `SessionToken` set → `SessionCredentials` (STS temporary credentials)
4. `AccessKey` + `SecretKey` → `BasicAWSCredentials`
### MinIO / S3-Compatible
```csharp
S3.Bucket("my-bucket")
.ServiceUrl("http://localhost:9000")
.ForcePathStyle()
.AccessKey("minioadmin")
.SecretKey("minioadmin")
```
`ForcePathStyle` is required for MinIO, Ceph, Dell ECS, and most S3-compatible stores.
### Connection Factory
Register a named `S3ConnectionFactory` in DI, then reference by name:
```csharp
S3.Bucket("data").ConnectionFactory("myS3Factory")
```
### Proxy
```csharp
S3.Bucket("data")
.AccessKey("KEY").SecretKey("SECRET")
.Proxy("proxy.corp.local", 8080)
```
---
## Multipart Upload
For large files, enable multipart upload:
```csharp
.To(S3.Bucket("large-files")
.AccessKey("KEY").SecretKey("SECRET")
.KeyName("uploads/${header.name}")
.MultiPartUpload()
.PartSize(10_485_760)) // 10 MB parts (min 5 MB)
```
Automatically splits files larger than `PartSize` into parts uploaded sequentially.
---
## Server-Side Encryption
Three SSE modes:
```csharp
// SSE-S3: AWS-managed AES-256
.UseAes256Encryption()
// SSE-KMS: AWS KMS managed key
.UseKmsEncryption("arn:aws:kms:region:account:key/id")
// SSE-C: Customer-provided key
.UseCustomerEncryption("AES256", "base64-key", "base64-key-md5")
```
---
## Batching many exchanges into one object
Accumulate-then-write is the route's job, not the transport's: use the core **Aggregate** EIP,
which completes a batch by count, size or timeout, and hand the result to the plain S3 producer.
```csharp
From("kafka://events?...")
.Aggregate(
"all", // one running batch
(acc, next) => AppendLine(acc, next), // e.g. build a JSONL body
completionSize: 100,
completionTimeout: TimeSpan.FromSeconds(30))
.SetHeader(S3Headers.Key, e => $"batch/events-{DateTime.UtcNow:yyyyMMddHHmmss}.jsonl")
.To(S3.Bucket("logs").AccessKey("KEY").SecretKey("SECRET"));
```
> The former `StreamingUpload`/`NamingStrategy` options promised this at the transport level and
> were never implemented — they are gone as of the 4.0.0 breaking bundle.
---
## Conditional Write
```csharp
.To(S3.Bucket("data")
.AccessKey("KEY").SecretKey("SECRET")
.KeyName("unique-file.json")
.ConditionalWrite())
```
Uses `x-amz-if-none-match` — upload fails if the object key already exists.
---
## Configuration Reference
### Connection / Credentials
| Parameter | Type | Default | Description |
|---|---|---|---|
| `serviceUrl` | string | `""` | S3-compatible endpoint URL |
| `region` | string | `"us-east-1"` | AWS region |
| `accessKey` | string | `""` | AWS access key ID |
| `secretKey` | string | `""` | AWS secret access key |
| `sessionToken` | string | `""` | STS session token |
| `profileName` | string | `""` | AWS named profile |
| `forcePathStyle` | bool | `false` | Path-style URLs (required for MinIO) |
| `useDefaultCredentialsProvider` | bool | `false` | Use AWS default credential chain |
| `connectionFactory` | string | `""` | Named connection factory from DI |
| `proxyHost` | string | `""` | HTTP proxy host |
| `proxyPort` | int | `0` | HTTP proxy port |
| `connectionTimeout` | int | `30000` | Connection timeout (ms) |
| `socketTimeout` | int | `60000` | Socket/read timeout (ms) |
| `maxConnections` | int | `50` | SDK connection pool size |
| `retryCount` | int | `3` | Retry attempts |
| `retryMode` | string | `"standard"` | `"standard"` or `"adaptive"` |
| `trustAllCertificates` | bool | `false` | Trust self-signed SSL certs |
### Common
| Parameter | Type | Default | Description |
|---|---|---|---|
| `autoCreateBucket` | bool | `false` | Auto-create bucket if missing |
| `prefix` | string | `""` | Key prefix filter |
| `delimiter` | string | `""` | ListObjectsV2 delimiter |
| `includeBody` | bool | `true` | Download object body |
| `streamBody` | bool | `false` | Body as `Stream` instead of `byte[]` |
| `ignoreBody` | bool | `false` | Skip body entirely (metadata only) |
| `includeFolders` | bool | `false` | Include folder markers |
### Consumer
| Parameter | Type | Default | Description |
|---|---|---|---|
| `delay` | int | `60000` | Polling interval (ms) |
| `initialDelay` | int | `1000` | Delay before first poll (ms) |
| `maxMessagesPerPoll` | int | `10` | Max objects per poll (0 = unlimited) |
| `deleteAfterRead` | bool | `true` | Delete after successful processing; with `moveAfterRead=true` the move takes its place (an explicit `deleteAfterRead=true` beside it is an error) |
| `moveAfterRead` | bool | `false` | Move to destination bucket instead of delete; needs `destinationBucket` |
| `destinationBucket` | string | `""` | Target bucket for move |
| `destinationBucketPrefix` | string | `""` | Prefix for moved key |
| `destinationBucketSuffix` | string | `""` | Suffix for moved key |
| `removePrefixOnMove` | bool | `false` | Strip source prefix on move |
| `fileName` | string | `""` | Consume single file by key |
| `include` | string | `""` | Glob include pattern |
| `exclude` | string | `""` | Glob exclude pattern |
| `sendEmptyMessageWhenIdle` | bool | `false` | Heartbeat on empty poll |
| `doneFileName` | string | `""` | Done-file marker pattern |
| `sortBy` | enum | `None` | `None`, `Key`, `KeyDesc`, `LastModified`, `LastModifiedDesc`, `Size`, `SizeDesc` |
| `minAge` | long | `0` | Min object age (ms) |
| `maxAge` | long | `0` | Max object age (ms, 0 = no limit) |
| `idempotent` | bool | `false` | Enable idempotent consumer |
| `idempotentKey` | string | `""` | Custom idempotent key expression |
### Producer
| Parameter | Type | Default | Description |
|---|---|---|---|
| `keyName` | DynamicValue | — | Object key (supports `${header.xxx}` expressions) |
| `storageClass` | string | `""` | S3 storage class |
| `contentType` | string | `""` | Content-Type (empty = auto-detect) |
| `contentDisposition` | string | `""` | Content-Disposition |
| `contentEncoding` | string | `""` | Content-Encoding |
| `cacheControl` | string | `""` | Cache-Control |
| `cannedAcl` | enum | `Private` | `Private`, `PublicRead`, `PublicReadWrite`, `AuthenticatedRead`, `BucketOwnerRead`, `BucketOwnerFullControl` |
| `multiPartUpload` | bool | `false` | Enable multipart upload |
| `partSize` | long | `26214400` (25 MB) | Multipart part size (min 5 MB) |
| `deleteAfterWrite` | bool | `false` | Delete source after upload |
| `conditionalWrite` | bool | `false` | Fail if object exists |
### Server-Side Encryption
| Parameter | Type | Default | Description |
|---|---|---|---|
| `serverSideEncryption` | enum | `None` | `None`, `Aes256`, `AwsKms`, `CustomerKey` |
| `kmsKeyId` | string | `""` | KMS key ARN (required for `AwsKms`) |
| `customerAlgorithm` | string | `""` | SSE-C algorithm |
| `customerKeyId` | string | `""` | SSE-C key (base64) |
| `customerKeyMD5` | string | `""` | SSE-C key MD5 (base64) |
### Presigned URLs
| Parameter | Type | Default | Description |
|---|---|---|---|
| `presignedUrlExpiration` | long | `3600000` (1h) | URL expiration (ms) |
### Metadata
| Parameter | Type | Default | Description |
|---|---|---|---|
| `metadata` | string | `""` | Comma-separated `key=value` pairs |
---
## Headers Reference
### Common (set by consumer, used by producer)
| Header | Description |
|---|---|
| `redbS3.BucketName` | Bucket name |
| `redbS3.Key` | Object key |
| `redbS3.ContentType` | Content-Type |
| `redbS3.ContentLength` | Content-Length (bytes) |
| `redbS3.ContentMD5` | Content MD5 (base64) |
| `redbS3.ContentDisposition` | Content-Disposition |
| `redbS3.ContentEncoding` | Content-Encoding |
| `redbS3.CacheControl` | Cache-Control |
| `redbS3.ETag` | Object ETag |
| `redbS3.LastModified` | Last modified timestamp |
| `redbS3.StorageClass` | Storage class |
| `redbS3.VersionId` | Version ID |
| `redbS3.ServerSideEncryption` | SSE algorithm |
| `redbS3.Operation` | Operation type (runtime override) |
### Consumer Output
| Header | Description |
|---|---|
| `redbS3.ExpirationTime` | Object expiration (lifecycle) |
| `redbS3.ReplicationStatus` | Replication status |
| `redbS3.Timestamp` | Message timestamp (Unix ms) |
### Producer Input
| Header | Description |
|---|---|
| `redbS3.DestinationBucket` | Target bucket (CopyObject) |
| `redbS3.DestinationKey` | Target key (CopyObject) |
| `redbS3.CannedAcl` | ACL preset |
| `redbS3.RangeStart` | Byte range start (GetObjectRange) |
| `redbS3.RangeEnd` | Byte range end (GetObjectRange) |
| `redbS3.PresignedUrlExpiration` | URL expiration override (ms) |
| `redbS3.KeysToDelete` | `List` of keys (DeleteObjects) |
| `redbS3.ObjectTags` | `Dictionary` (PutObjectTagging) |
| `redbS3.VersioningStatus` | `"Enabled"` / `"Suspended"` (PutBucketVersioning) |
| `redbS3.RestoreDays` | Glacier restore days |
| `redbS3.RestoreTier` | `Standard` / `Bulk` / `Expedited` |
| `redbS3.OverrideBucketName` | Dynamic bucket override |
### Producer Output
| Header | Description |
|---|---|
| `redbS3.PresignedUrl` | Generated presigned URL |
| `redbS3.ProducedKey` | Resolved key after upload |
| `redbS3.ProducedBucketName` | Resolved bucket name |
| `redbS3.BucketExists` | Bucket existence result (HeadBucket) |
### Metadata Mapping
Headers prefixed with `redbS3.Meta.` are mapped to/from S3 user metadata:
```
redbS3.Meta.x-amz-meta-author → S3 metadata "x-amz-meta-author"
```
---
## DSL
```csharp
using redb.Route.S3;
// Basic consumer
S3.Bucket("my-bucket")
.ServiceUrl("http://localhost:9000").ForcePathStyle()
.AccessKey("minioadmin").SecretKey("minioadmin")
// Producer with operation
S3.Bucket("my-bucket", S3OperationType.CopyObject)
.Region("eu-west-1")
.AccessKey("KEY").SecretKey("SECRET")
// Presigned download link
S3.Bucket("my-bucket", S3OperationType.CreateDownloadLink)
.AccessKey("KEY").SecretKey("SECRET")
.PresignedUrlExpiration(7_200_000)
// Full producer example
S3.Bucket("archive")
.Region("eu-west-1")
.AccessKey("KEY").SecretKey("SECRET")
.KeyName(new HeaderExpression("fileName"))
.MultiPartUpload().PartSize(10_485_760)
.UseKmsEncryption("my-key-id")
.StorageClass("INTELLIGENT_TIERING")
.Metadata("env=prod,team=data")
```
The builder implements `implicit operator string` — pass directly to `.From()` / `.To()`.
---
## DI Registration
```csharp
services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteS3();
// ...
});
```
Registers the `S3Component` (scheme `s3`).
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup — a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new S3ConnectionFactory
{
ServiceUrl = "http://minio.internal:9000",
ForcePathStyle = true,
AccessKey = "svc",
SecretKey = secrets.S3Secret,
});
// s3://backups?connectionFactory=prod
```
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `redb.route.endpoint` and the bucket as
`messaging.destination.name`:
- **Consumer.** One `Consumer` span, `{bucket} receive`, per routed object. An object carries no trace context, so the
span is a root, never a child of the activity the poll loop inherited from whoever started the routes. An empty poll
opens none, nor does an object skipped for a missing done file. A failed route marks it an error; our own stop does not.
- **Producer.** One `Client` span per call, `s3 {operation}`; an error when the call fails, unless our own token
cancelled it.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span.
Path: redb-route/redb.Route.S3/S3ClientConfigSupport.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/S3ClientConfigSupport.cs
----
using Amazon.Runtime;
using Amazon.S3;
namespace redb.Route.S3;
///
/// Shared wiring of connection options into — one place for the
/// endpoint-options path and the path (before it,
/// SocketTimeout/RetryMode/TrustAllCertificates were declared but never reached the SDK).
///
internal static class S3ClientConfigSupport
{
///
/// The region and service URL a built client talks to, for the "client created" log: read from the client's own
/// configuration, so a connection factory's values show, not the endpoint's defaults.
///
internal static (string Region, string ServiceUrl) Target(IClientConfig config) => (
config.RegionEndpoint?.SystemName ?? (string.IsNullOrEmpty(config.AuthenticationRegion) ? "(default)" : config.AuthenticationRegion),
string.IsNullOrEmpty(config.ServiceURL) ? "(default)" : redb.Route.Abstractions.EndpointUri.Sanitize(config.ServiceURL));
///
/// Applies timeouts, connection limits, retry policy and certificate trust to the config.
/// connectionTimeoutMs maps to ,
/// socketTimeoutMs to the overall request .
///
internal static void Apply(AmazonS3Config config,
int connectionTimeoutMs, int socketTimeoutMs, int maxConnections, int retryCount,
string retryMode, bool trustAllCertificates)
{
config.ConnectTimeout = TimeSpan.FromMilliseconds(connectionTimeoutMs);
config.Timeout = TimeSpan.FromMilliseconds(socketTimeoutMs);
config.MaxConnectionsPerServer = maxConnections;
config.MaxErrorRetry = retryCount;
config.RetryMode = ParseRetryMode(retryMode);
if (trustAllCertificates)
config.HttpClientFactory = new TrustAllHttpClientFactory();
}
// SDK v4 knows only Standard and Adaptive (Legacy retired with v3).
private static RequestRetryMode ParseRetryMode(string retryMode) =>
string.Equals(retryMode, "adaptive", StringComparison.OrdinalIgnoreCase)
? RequestRetryMode.Adaptive
: RequestRetryMode.Standard;
}
///
/// HTTP client factory that disables server-certificate validation — for MinIO/Ceph and
/// friends behind self-signed TLS. Dangerous by definition; enabled only by the explicit option
/// trustAllCertificates=true.
///
internal sealed class TrustAllHttpClientFactory : HttpClientFactory
{
public override HttpClient CreateHttpClient(IClientConfig clientConfig) =>
new(new HttpClientHandler
{
ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
});
}
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);
}
}
Path: redb-route/redb.Route.S3/S3ConnectionFactory.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/S3ConnectionFactory.cs
----
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using redb.Route.Core;
namespace redb.Route.S3;
///
/// Connection factory for S3/MinIO. Register via DI or in the route registry
/// and reference by name in endpoint URIs (connectionFactory=myFactory).
///
/// Supports AWS S3, MinIO, Dell ECS, Ceph, and other S3-compatible stores.
///
///
public sealed class S3ConnectionFactory
{
///
/// Custom service URL for S3-compatible stores (MinIO, Dell ECS, Ceph).
/// Example: http://localhost:9000.
///
public string ServiceUrl { get; set; } = "";
/// AWS region. (default: "us-east-1")
public string Region { get; set; } = "us-east-1";
/// AWS access key ID.
[Sensitive]
public string AccessKey { get; set; } = "";
/// AWS secret access key.
[Sensitive]
public string SecretKey { get; set; } = "";
/// AWS session token (for temporary STS credentials).
[Sensitive]
public string SessionToken { get; set; } = "";
/// AWS named profile from ~/.aws/credentials.
public string ProfileName { get; set; } = "";
///
/// Use path-style URLs (required for MinIO and most S3-compatible stores).
/// (default: false)
///
public bool ForcePathStyle { get; set; }
///
/// Use the default AWS credentials provider chain.
/// (default: false)
///
public bool UseDefaultCredentialsProvider { get; set; }
/// Trust all SSL certificates. (default: false)
public bool TrustAllCertificates { get; set; }
// ── Timeouts ──
/// Connection timeout in milliseconds. (default: 30000)
public int ConnectionTimeout { get; set; } = 30_000;
/// Socket/read timeout in milliseconds. (default: 60000)
public int SocketTimeout { get; set; } = 60_000;
/// Maximum concurrent connections. (default: 50)
public int MaxConnections { get; set; } = 50;
/// Number of retry attempts. (default: 3)
public int RetryCount { get; set; } = 3;
/// Retry mode: "standard" or "adaptive". (default: "standard")
public string RetryMode { get; set; } = "standard";
// ── Proxy ──
/// HTTP proxy host.
public string ProxyHost { get; set; } = "";
/// HTTP proxy port.
public int ProxyPort { get; set; }
///
/// Creates an and an client
/// from this factory's settings.
///
public IAmazonS3 Build()
{
var config = new AmazonS3Config { ForcePathStyle = ForcePathStyle };
// ServiceURL and RegionEndpoint are mutually exclusive, and in SDK v4 setting one
// CLEARS the other — the old "set region, then null it out for ServiceUrl" dance
// wiped ServiceURL and Build() with a custom URL always threw
// "No RegionEndpoint or ServiceURL configured".
if (!string.IsNullOrEmpty(ServiceUrl))
{
config.ServiceURL = ServiceUrl;
config.AuthenticationRegion = Region;
}
else
{
config.RegionEndpoint = RegionEndpoint.GetBySystemName(Region);
}
S3ClientConfigSupport.Apply(config,
ConnectionTimeout, SocketTimeout, MaxConnections,
RetryCount, RetryMode, TrustAllCertificates);
if (!string.IsNullOrEmpty(ProxyHost) && ProxyPort > 0)
{
config.ProxyHost = ProxyHost;
config.ProxyPort = ProxyPort;
}
var credentials = ResolveCredentials();
return new AmazonS3Client(credentials, config);
}
///
/// Creates an from this factory's settings
/// without building the client.
///
internal AmazonS3Config BuildConfig()
{
var config = new AmazonS3Config { ForcePathStyle = ForcePathStyle };
S3ClientConfigSupport.Apply(config,
ConnectionTimeout, SocketTimeout, MaxConnections,
RetryCount, RetryMode, TrustAllCertificates);
if (!string.IsNullOrEmpty(ServiceUrl))
{
config.ServiceURL = ServiceUrl;
config.AuthenticationRegion = Region;
}
else
{
config.RegionEndpoint = RegionEndpoint.GetBySystemName(Region);
}
if (!string.IsNullOrEmpty(ProxyHost) && ProxyPort > 0)
{
config.ProxyHost = ProxyHost;
config.ProxyPort = ProxyPort;
}
return config;
}
private AWSCredentials ResolveCredentials()
{
if (UseDefaultCredentialsProvider)
// SDK v4: the non-deprecated default-chain resolver (env -> profile -> IMDS etc.)
return Amazon.Runtime.Credentials.DefaultAWSCredentialsIdentityResolver.GetCredentials();
if (!string.IsNullOrEmpty(ProfileName))
{
var chain = new Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain();
if (chain.TryGetAWSCredentials(ProfileName, out var profileCreds))
return profileCreds;
throw new InvalidOperationException($"AWS profile '{ProfileName}' not found.");
}
if (!string.IsNullOrEmpty(SessionToken))
return new SessionAWSCredentials(AccessKey, SecretKey, SessionToken);
return new BasicAWSCredentials(AccessKey, SecretKey);
}
}
Path: redb-route/redb.Route.S3/S3Consumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.S3/S3Consumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.Telemetry;
namespace redb.Route.S3;
///
/// S3 consumer — polls a bucket for objects using ListObjectsV2.
/// Extends for graceful two-CTS shutdown.
///
/// Supports prefix/include/exclude filtering, sort order, min/max age,
/// idempotency, max-messages-per-poll, delete-after-read, move-after-read
/// with destination bucket/prefix/suffix, and done-file markers.
/// Inspired by Apache Camel aws2-s3 consumer patterns.
///
///
internal sealed class S3Consumer : DrainableConsumer
{
private readonly S3Endpoint _endpoint;
private readonly S3EndpointOptions _options;
private IAmazonS3? _client;
private long _processedCount;
// In-memory idempotent repository with double-buffer eviction (S-6): when current fills
// up it rotates to previous and starts fresh — retains up to 2×MaxIdempotentEntries of
// history instead of growing without bound.
private const int MaxIdempotentEntries = 10_000;
private ConcurrentDictionary? _idempotentRepo;
private ConcurrentDictionary? _previousIdempotentRepo;
// Named repository: the shared IIdempotentRepository contract of the route-level
// IdempotentConsumer EIP — dedup survives consumer restarts (and process restarts with
// a persistent implementation).
private IIdempotentRepository? _sharedRepo;
// Include/Exclude patterns compiled from glob
private readonly Regex? _includeRegex;
private readonly Regex? _excludeRegex;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"s3://{_endpoint.BucketName}";
/// Number of objects processed since start.
internal long ProcessedCount => Interlocked.Read(ref _processedCount);
internal S3Consumer(S3Endpoint endpoint, IProcessor processor, S3EndpointOptions options)
: base(processor)
{
_endpoint = endpoint;
_options = options;
if (options.Idempotent)
_idempotentRepo = new ConcurrentDictionary();
if (!string.IsNullOrEmpty(options.Include))
_includeRegex = GlobToRegex(options.Include);
if (!string.IsNullOrEmpty(options.Exclude))
_excludeRegex = GlobToRegex(options.Exclude);
}
///
protected override async Task OnStarting(CancellationToken ct)
{
_client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
if (!string.IsNullOrEmpty(_options.IdempotentRepository))
{
var context = (_endpoint.Component as ComponentBase)?.Context
?? throw new InvalidOperationException(
$"IdempotentRepository '{_options.IdempotentRepository}' requires a route context " +
"(register the repository with context.AddIdempotentRepository(name, ...)).");
_sharedRepo = context.GetIdempotentRepositoryProvider().Get(_options.IdempotentRepository);
}
if (_options.AutoCreateBucket)
{
try
{
await _client.EnsureBucketExistsAsync(_endpoint.BucketName).ConfigureAwait(false);
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.Conflict)
{
// Already exists
}
}
}
///
protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
// Initial delay
if (_options.InitialDelay > 0)
await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false);
while (!pollCt.IsCancellationRequested)
{
try
{
await PollBucketAsync(processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (pollCt.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Logger?.LogError(ex, "S3 consumer poll error on bucket {Bucket}", _endpoint.BucketName);
_endpoint.RecordError(ex); // with its details, or LastErrorMessage stays empty
}
// Wait between polls
try
{
await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
}
// ═══════════════════════════════════════════════════════════════════
// POLLING
// ═══════════════════════════════════════════════════════════════════
private async Task PollBucketAsync(CancellationToken ct)
{
// If fileName is specified, handle single-file mode
if (!string.IsNullOrEmpty(_options.FileName))
{
await PollSingleFileAsync(ct).ConfigureAwait(false);
return;
}
// Without sorting the listing streams page by page with an early exit at
// MaxMessagesPerPoll — a big bucket no longer costs O(N) memory per poll (S-7).
if (_options.SortBy == S3SortBy.None)
{
await PollStreamingAsync(ct).ConfigureAwait(false);
return;
}
var request = new ListObjectsV2Request
{
BucketName = _endpoint.BucketName,
Prefix = _options.Prefix,
Delimiter = _options.Delimiter,
};
var allObjects = new List();
string? continuationToken = null;
// Paginate through listing — SortBy honestly needs the full list in memory.
do
{
request.ContinuationToken = continuationToken;
var response = await _client!.ListObjectsV2Async(request, ct).ConfigureAwait(false);
foreach (var obj in response.S3Objects ?? [])
{
// Skip folder markers
if (!_options.IncludeFolders && obj.Key.EndsWith('/'))
continue;
allObjects.Add(obj);
}
continuationToken = response.IsTruncated == true ? response.NextContinuationToken : null;
} while (continuationToken != null);
// Apply filters
var eligible = FilterObjects(allObjects);
// Sort
eligible = SortObjects(eligible);
// Apply max-messages-per-poll
if (_options.MaxMessagesPerPoll > 0)
eligible = eligible.Take(_options.MaxMessagesPerPoll).ToList();
if (eligible.Count == 0)
{
if (_options.SendEmptyMessageWhenIdle)
{
var emptyExchange = CreateExchange(null);
await ProcessWithTracking(emptyExchange, ct).ConfigureAwait(false);
}
return;
}
// Process each object
foreach (var obj in eligible)
{
if (ct.IsCancellationRequested)
break;
await ProcessObjectAsync(obj, ct).ConfigureAwait(false);
}
}
///
/// Streaming poll for the unsorted case (S-7): pages are processed as they arrive and the
/// loop exits as soon as MaxMessagesPerPoll eligible objects were handled.
///
private async Task PollStreamingAsync(CancellationToken ct)
{
var request = new ListObjectsV2Request
{
BucketName = _endpoint.BucketName,
Prefix = _options.Prefix,
Delimiter = _options.Delimiter,
};
var processed = 0;
var anyEligible = false;
var now = DateTime.UtcNow;
string? continuationToken = null;
do
{
request.ContinuationToken = continuationToken;
var response = await _client!.ListObjectsV2Async(request, ct).ConfigureAwait(false);
foreach (var obj in response.S3Objects ?? [])
{
if (ct.IsCancellationRequested)
return;
if (!_options.IncludeFolders && obj.Key.EndsWith('/'))
continue;
if (!PassesFilters(obj, now))
continue;
anyEligible = true;
await ProcessObjectAsync(obj, ct).ConfigureAwait(false);
if (_options.MaxMessagesPerPoll > 0 && ++processed >= _options.MaxMessagesPerPoll)
return;
}
continuationToken = response.IsTruncated == true ? response.NextContinuationToken : null;
} while (continuationToken != null);
if (!anyEligible && _options.SendEmptyMessageWhenIdle)
{
var emptyExchange = CreateExchange(null);
await ProcessWithTracking(emptyExchange, ct).ConfigureAwait(false);
}
}
private async Task PollSingleFileAsync(CancellationToken ct)
{
try
{
var metadata = await _client!.GetObjectMetadataAsync(_endpoint.BucketName, _options.FileName, ct)
.ConfigureAwait(false);
var pseudoObj = new S3Object
{
BucketName = _endpoint.BucketName,
Key = _options.FileName,
Size = metadata.ContentLength,
LastModified = metadata.LastModified,
ETag = metadata.ETag,
};
// Idempotency: check only — the mark is written after success in ProcessObjectAsync (S-2)
if (IsAlreadySeen(pseudoObj))
return;
await ProcessObjectAsync(pseudoObj, ct).ConfigureAwait(false);
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// File doesn't exist yet — skip
}
}
private async Task ProcessObjectAsync(S3Object obj, CancellationToken ct)
{
// Named repo: two-phase claim BEFORE the download — Add is atomic, so a
// concurrent consumer cannot take the same object twice; released on any failure.
if (_sharedRepo is not null
&& !await _sharedRepo.Add(BuildIdempotentKey(obj), ct).ConfigureAwait(false))
return;
try
{
await ProcessObjectCoreAsync(obj, ct).ConfigureAwait(false);
}
catch
{
await ReleaseSharedClaimAsync(obj, ct).ConfigureAwait(false);
throw;
}
}
private async Task ProcessObjectCoreAsync(S3Object obj, CancellationToken ct)
{
// Done file check
if (!string.IsNullOrEmpty(_options.DoneFileName))
{
var doneKey = ResolveDoneFileName(obj.Key);
try
{
await _client!.GetObjectMetadataAsync(_endpoint.BucketName, doneKey, ct).ConfigureAwait(false);
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
Logger?.LogDebug("S3: Skipping {Key} — done file {DoneKey} not found", obj.Key, doneKey);
// Release the claim: the object must be re-offered once the done file appears.
await ReleaseSharedClaimAsync(obj, ct).ConfigureAwait(false);
return;
}
}
// Download object. IncludeBody=false (and IgnoreBody) mean "no content download" —
// no GET is issued at all; previously a raw ResponseStream leaked into the body (S-8).
object? body = null;
GetObjectResponse? getResponse = null;
if (!_options.IgnoreBody && (_options.StreamBody || _options.IncludeBody))
{
var getRequest = new GetObjectRequest
{
BucketName = _endpoint.BucketName,
Key = obj.Key,
};
getResponse = await _client!.GetObjectAsync(getRequest, ct).ConfigureAwait(false);
if (_options.StreamBody)
{
// Ownership: the stream goes into the exchange; Exchange.DisposeAsync closes
// it, which releases the HTTP connection. The response object must NOT be
// disposed here — that would close the stream we just handed over (S-8).
body = getResponse.ResponseStream;
}
else
{
try
{
using var ms = new MemoryStream();
await getResponse.ResponseStream.CopyToAsync(ms, ct).ConfigureAwait(false);
body = ms.ToArray(); // BytesIn is counted by the core around the routed consumer
}
catch
{
getResponse.Dispose();
throw;
}
}
}
// Create exchange
var exchange = CreateExchange(body);
SetConsumerHeaders(exchange, obj, getResponse);
// Buffered path: the response is fully read and its headers copied — release the
// connection now instead of leaking it until GC (S-8).
if (getResponse is not null && !_options.StreamBody)
getResponse.Dispose();
// Process (MessagesIn is counted by the core StatisticsProcessor - ownership audit)
var success = await ProcessExchangeAsync(exchange, obj.Key, ct).ConfigureAwait(false);
Interlocked.Increment(ref _processedCount);
if (success)
{
// Idempotent mark only AFTER success (S-2): a failed object and objects beyond
// MaxMessagesPerPoll must be offered again on the next poll.
MarkSeen(obj);
if (_sharedRepo is not null)
await _sharedRepo.Confirm(BuildIdempotentKey(obj), ct).ConfigureAwait(false);
await PostProcessAsync(obj, ct).ConfigureAwait(false);
}
else
{
await ReleaseSharedClaimAsync(obj, ct).ConfigureAwait(false);
}
}
/// Releases the two-phase claim so a failed object is offered again.
private async Task ReleaseSharedClaimAsync(S3Object obj, CancellationToken ct)
{
if (_sharedRepo is null) return;
try
{
await _sharedRepo.Remove(BuildIdempotentKey(obj), ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Logger?.LogWarning(ex,
"S3: releasing idempotent claim for {Key} failed — the object stays marked until manual cleanup",
obj.Key);
}
}
///
/// Runs the exchange through the processor with inflight tracking and reports whether it
/// succeeded. A processing failure must not delete/move the object (S-1), so unlike
/// the outcome is observed here:
/// a raw throw (no error handler took the exchange), an unhandled exchange.Exception
/// set by the pipeline and a rollback-only exchange (.RollbackAll()) all count as failure
/// (), as in Camel aws2-s3, which deletes or
/// moves the object only when the exchange commits.
///
private async Task ProcessExchangeAsync(IExchange exchange, string key, CancellationToken ct)
{
// An object carries no trace context: its span is a root, never a child of the activity the poll runs under.
using var span = RouteTelemetryExtensions.StartConsumerSpan