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`). [![NuGet](https://img.shields.io/nuget/v/redb.Route.S3?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.S3) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../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( (_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.BucketName} receive", ActivityKind.Consumer, "redb.system", "s3", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.BucketName, operation: "receive"); IncrementInflight(); try { await Processor.Process(exchange, ct).ConfigureAwait(false); if (!exchange.EndedInFailure()) return true; // A failed route marks the span; a rolled-back one (no exception) does not. // Our own stop is not a failure; any other cancellation, a timeout inside the route, is. if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !ct.IsCancellationRequested)) span.Activity.RecordFailure(failure); return false; } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; // shutdown — let the poll loop exit } catch (Exception ex) { // Pipeline errors are counted by the core StatisticsProcessor (ownership audit). span.Activity.RecordFailure(ex); Logger?.LogError(ex, "S3: processing failed for {Key}; object is kept.", key); return false; } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } private async Task PostProcessAsync(S3Object obj, CancellationToken ct) { // Move-after-read if (_options.MoveAfterRead && !string.IsNullOrEmpty(_options.DestinationBucket)) { var destKey = BuildDestinationKey(obj.Key); if (_options.AutoCreateBucket) { try { await _client!.EnsureBucketExistsAsync(_options.DestinationBucket).ConfigureAwait(false); } catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.Conflict) { } } await _client!.CopyObjectAsync(new CopyObjectRequest { SourceBucket = _endpoint.BucketName, SourceKey = obj.Key, DestinationBucket = _options.DestinationBucket, DestinationKey = destKey, }, ct).ConfigureAwait(false); // Delete from source after successful copy. A failed delete must not bubble as a // poll error (S-9): the copy already succeeded — log the duplication and move on; // the idempotent mark (when enabled) keeps the source from being re-processed. try { await _client.DeleteObjectAsync(_endpoint.BucketName, obj.Key, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { Logger?.LogWarning(ex, "S3: MoveAfterRead copied {Bucket}/{Key} → {DestBucket}/{DestKey} but delete of source failed. " + "Object exists in both locations until the next successful delete", _endpoint.BucketName, obj.Key, _options.DestinationBucket, destKey); } Logger?.LogDebug("S3: Moved {Bucket}/{Key} → {DestBucket}/{DestKey}", _endpoint.BucketName, obj.Key, _options.DestinationBucket, destKey); } else if (_options.DeleteAfterRead) { await _client!.DeleteObjectAsync(_endpoint.BucketName, obj.Key, ct).ConfigureAwait(false); Logger?.LogDebug("S3: Deleted {Bucket}/{Key} after read", _endpoint.BucketName, obj.Key); } } // ═══════════════════════════════════════════════════════════════════ // FILTERING // ═══════════════════════════════════════════════════════════════════ private List FilterObjects(List objects) { var now = DateTime.UtcNow; return objects.Where(obj => PassesFilters(obj, now)).ToList(); } private bool PassesFilters(S3Object obj, DateTime now) { // Extract filename (last segment) for glob matching var fileName = obj.Key.Contains('/') ? obj.Key[(obj.Key.LastIndexOf('/') + 1)..] : obj.Key; // Include pattern if (_includeRegex != null && !_includeRegex.IsMatch(fileName)) return false; // Exclude pattern if (_excludeRegex != null && _excludeRegex.IsMatch(fileName)) return false; // Min age if (_options.MinAge > 0) { var age = (now - (obj.LastModified ?? now)).TotalMilliseconds; if (age < _options.MinAge) return false; } // Max age if (_options.MaxAge > 0) { var age = (now - (obj.LastModified ?? now)).TotalMilliseconds; if (age > _options.MaxAge) return false; } // Idempotency: check only — the "seen" mark is written after a SUCCESSFUL // exchange (S-2), never at filter time. if (IsAlreadySeen(obj)) return false; return true; } private List SortObjects(List objects) { return _options.SortBy switch { S3SortBy.Key => objects.OrderBy(o => o.Key).ToList(), S3SortBy.KeyDesc => objects.OrderByDescending(o => o.Key).ToList(), S3SortBy.LastModified => objects.OrderBy(o => o.LastModified).ToList(), S3SortBy.LastModifiedDesc => objects.OrderByDescending(o => o.LastModified).ToList(), S3SortBy.Size => objects.OrderBy(o => o.Size).ToList(), S3SortBy.SizeDesc => objects.OrderByDescending(o => o.Size).ToList(), _ => objects, }; } // ═══════════════════════════════════════════════════════════════════ // EXCHANGE CREATION // ═══════════════════════════════════════════════════════════════════ private IExchange CreateExchange(object? body) { // ScopeFactory from the endpoint — otherwise per-exchange DI scopes are dead (S-4). return Exchange.Create(new Message { Body = body }, _endpoint.ScopeFactory); } private void SetConsumerHeaders(IExchange exchange, S3Object obj, GetObjectResponse? response) { var headers = exchange.In.Headers; headers[S3Headers.BucketName] = obj.BucketName ?? _endpoint.BucketName; headers[S3Headers.Key] = obj.Key; headers[S3Headers.ContentLength] = obj.Size; headers[S3Headers.ETag] = obj.ETag; headers[S3Headers.LastModified] = obj.LastModified; headers[S3Headers.StorageClass] = obj.StorageClass?.Value; headers[S3Headers.Timestamp] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); if (response != null) { headers[S3Headers.ContentType] = response.Headers.ContentType; headers[S3Headers.VersionId] = response.VersionId; headers[S3Headers.ServerSideEncryption] = response.ServerSideEncryptionMethod?.Value; // User metadata foreach (var meta in response.Metadata.Keys) headers[$"{S3Headers.MetadataPrefix}{meta}"] = response.Metadata[meta]; } } // ═══════════════════════════════════════════════════════════════════ // HELPERS // ═══════════════════════════════════════════════════════════════════ private static string BuildIdempotentKey(S3Object obj) => $"{obj.Key}|{obj.ETag}|{obj.Size}"; private bool IsAlreadySeen(S3Object obj) { if (_idempotentRepo is null) return false; var key = BuildIdempotentKey(obj); return _idempotentRepo.ContainsKey(key) || _previousIdempotentRepo?.ContainsKey(key) == true; } private void MarkSeen(S3Object obj) { if (_idempotentRepo is null) return; // Double-buffer eviction (S-6) if (_idempotentRepo.Count > MaxIdempotentEntries) { _previousIdempotentRepo = _idempotentRepo; _idempotentRepo = new ConcurrentDictionary(); } _idempotentRepo.TryAdd(BuildIdempotentKey(obj), true); } private string BuildDestinationKey(string sourceKey) { var key = sourceKey; // Remove source prefix if (_options.RemovePrefixOnMove && !string.IsNullOrEmpty(_options.Prefix) && key.StartsWith(_options.Prefix)) key = key[_options.Prefix.Length..]; // Add destination prefix/suffix if (!string.IsNullOrEmpty(_options.DestinationBucketPrefix)) key = _options.DestinationBucketPrefix + key; if (!string.IsNullOrEmpty(_options.DestinationBucketSuffix)) { var lastDot = key.LastIndexOf('.'); if (lastDot > 0) key = key[..lastDot] + _options.DestinationBucketSuffix + key[lastDot..]; else key += _options.DestinationBucketSuffix; } return key; } private string ResolveDoneFileName(string objectKey) { // "${file:name}.done" is "objectKey.done"; the other file keys read the key too (ObjectKeyFacts). return FileLanguage.Substitute(_options.DoneFileName, new ObjectKeyFacts(objectKey), StringComparison.OrdinalIgnoreCase); } private static Regex GlobToRegex(string glob) { // Support comma-separated patterns var patterns = glob.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); var regexPatterns = patterns.Select(p => { var escaped = Regex.Escape(p) .Replace(@"\*\*", ".*") // ** matches anything including / .Replace(@"\*", "[^/]*") // * matches anything except / .Replace(@"\?", "[^/]"); // ? matches single char except / return $"(?:{escaped})"; }); return new Regex($"^(?:{string.Join("|", regexPatterns)})$", RegexOptions.Compiled | RegexOptions.IgnoreCase); } } Path: redb-route/redb.Route.S3/S3EndpointOptions.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/S3EndpointOptions.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.S3; /// /// Endpoint options for S3/MinIO transport. All properties are auto-bound from URI query parameters. /// /// URI format: s3://bucket-name?region=us-east-1&accessKey=KEY&secretKey=SECRET /// /// /// For producer operations: s3:PutObject:bucket-name?keyName=folder/${header.name}&... /// /// /// Enterprise-grade S3 integration compatible with AWS S3 and MinIO. /// Supports multipart uploads, server-side encryption (SSE-S3, SSE-KMS, SSE-C), /// presigned URLs, tagging, versioning, ACL, lifecycle, and more. /// Inspired by Apache Camel's aws2-s3 component (81 parameters). /// /// public class S3EndpointOptions : EndpointOptions { // ═══════════════════════════════════════════════════════════════════ // CONNECTION / CREDENTIALS // ═══════════════════════════════════════════════════════════════════ /// /// Custom service URL for S3-compatible storage (MinIO, Dell ECS, Ceph, etc.). /// Example: http://localhost:9000 for MinIO. /// When set, should typically be true. /// public string ServiceUrl { get; set; } = ""; /// /// AWS region (e.g. "us-east-1", "eu-west-1"). Required for AWS S3. /// For MinIO, use any value (e.g. "us-east-1"). (default: "us-east-1") /// public string Region { get; set; } = "us-east-1"; /// AWS access key ID. Required unless using default credentials provider. [Sensitive] public string AccessKey { get; set; } = ""; /// AWS secret access key. Required unless using default credentials provider. [Sensitive] public string SecretKey { get; set; } = ""; /// AWS session token for temporary credentials (STS AssumeRole). [Sensitive] public string SessionToken { get; set; } = ""; /// AWS named profile for credentials (from ~/.aws/credentials). public string ProfileName { get; set; } = ""; /// /// Use path-style URL (http://host/bucket/key) instead of virtual-hosted-style /// (http://bucket.host/key). Required for MinIO and most S3-compatible stores. /// (default: false) /// public bool ForcePathStyle { get; set; } /// /// Use the default AWS credentials provider chain (env vars, instance profile, etc.) /// instead of explicit AccessKey/SecretKey. (default: false) /// public bool UseDefaultCredentialsProvider { get; set; } /// /// Named connection factory reference. If set, looks up an /// from the DI registry by this name to build the S3 client. Overrides individual connection options. /// [RegistryReference(typeof(S3ConnectionFactory))] public string ConnectionFactory { get; set; } = ""; // ── Proxy ──────────────────────────────────────────────────────── /// HTTP proxy host for the S3 client. public string ProxyHost { get; set; } = ""; /// HTTP proxy port. (default: 0 = no proxy) public int ProxyPort { get; set; } // ── Timeouts / Resilience ──────────────────────────────────────── /// Connection timeout in milliseconds. (default: 30000 = 30s) public int ConnectionTimeout { get; set; } = 30_000; /// Socket/read timeout in milliseconds. (default: 60000 = 60s) public int SocketTimeout { get; set; } = 60_000; /// Maximum number of connections in the SDK connection pool. (default: 50) public int MaxConnections { get; set; } = 50; /// Number of retry attempts for failed requests. (default: 3) public int RetryCount { get; set; } = 3; /// /// Retry mode: "standard" or "adaptive". (default: "standard") /// public string RetryMode { get; set; } = "standard"; /// Trust all SSL certificates (for self-signed MinIO certs). (default: false) public bool TrustAllCertificates { get; set; } // ═══════════════════════════════════════════════════════════════════ // COMMON (consumer + producer) // ═══════════════════════════════════════════════════════════════════ /// /// Automatically create the S3 bucket if it doesn't exist. /// Also applies to when is true. /// (default: false) /// public bool AutoCreateBucket { get; set; } /// /// Prefix filter for ListObjectsV2. Only objects whose key starts with this prefix /// are listed by the consumer or the ListObjects producer operation. /// public string Prefix { get; set; } = ""; /// /// Delimiter for ListObjectsV2 to group keys (typically "/"). /// When set, keys containing the delimiter after the prefix are rolled up into common-prefix entries. /// public string Delimiter { get; set; } = ""; /// /// If true, download the object body and place it in the exchange body. /// If false, set headers only (metadata mode). (default: true) /// public bool IncludeBody { get; set; } = true; /// /// If true, the exchange body is set to the S3 response stream (Stream) instead of byte[]. /// Takes precedence over . The stream is closed by Exchange.DisposeAsync(). Default: false. /// public bool StreamBody { get; set; } /// /// If true, the S3 object body is completely ignored (no download, no stream). /// Overrides and . (default: false) /// public bool IgnoreBody { get; set; } /// /// If true, include folder/directory marker objects in consumer results. /// If false, objects ending with "/" are skipped. (default: false) /// public bool IncludeFolders { get; set; } // ═══════════════════════════════════════════════════════════════════ // CONSUMER (polling bucket) // ═══════════════════════════════════════════════════════════════════ /// Polling delay in milliseconds between bucket scans. (default: 60000 = 60s) public int Delay { get; set; } = 60_000; /// Initial delay before the first poll in milliseconds. (default: 1000) public int InitialDelay { get; set; } = 1000; /// Maximum number of objects to retrieve per poll. 0 = unlimited. (default: 10) public int MaxMessagesPerPoll { get; set; } = 10; /// /// Delete objects from S3 after they have been successfully consumed. /// Only performed if the exchange completes without error and is not marked rollback-only. (default: true; with the /// object is moved instead, as Apache Camel's move takes the place of the delete) /// public bool DeleteAfterRead { get => _deleteAfterRead; set { _deleteAfterRead = value; _deleteAfterReadSet = true; } } private bool _deleteAfterRead = true; // Only a delete asked for explicitly conflicts with a move; the default gives way to it. private bool _deleteAfterReadSet; /// /// Move objects to after successful consumption /// instead of deleting. Requires to be set. /// (default: false) /// public bool MoveAfterRead { get; set; } /// Destination bucket for move-after-read. Required when MoveAfterRead=true. public string DestinationBucket { get; set; } = ""; /// Prefix to add to the destination key when moving objects. public string DestinationBucketPrefix { get; set; } = ""; /// Suffix to add to the destination key when moving objects. public string DestinationBucketSuffix { get; set; } = ""; /// /// Remove the source prefix from the key before constructing the destination key. /// Only applicable when is true. (default: false) /// public bool RemovePrefixOnMove { get; set; } /// /// Filter consumer to only process a specific object by key name. /// When set, the consumer downloads this single file directly (no listing). /// public string FileName { get; set; } = ""; /// /// Glob pattern to include objects (applied to the object key). e.g. "*.csv", "data/*.json". /// Empty = all objects. (default: "") /// public string Include { get; set; } = ""; /// /// Glob pattern to exclude objects. e.g. "*.tmp", ".hidden/*". /// Empty = exclude nothing. (default: "") /// public string Exclude { get; set; } = ""; /// /// If the poll returns no objects, send an empty exchange (heartbeat). /// (default: false) /// public bool SendEmptyMessageWhenIdle { get; set; } /// /// Done file marker pattern. If set, the consumer only processes an object /// when a corresponding marker object exists (e.g. ${file:name}.done). The file keys read the object key: /// ${file:name} is the whole key, ${file:name.noext}, ${file:ext} and ${file:parent} its parts. /// public string DoneFileName { get; set; } = ""; /// Sort order for consumed objects. (default: None) public S3SortBy SortBy { get; set; } = S3SortBy.None; /// Minimum object age in milliseconds before consumption. (default: 0) public long MinAge { get; set; } /// Maximum object age in milliseconds. Objects older than this are skipped. 0 = no limit. (default: 0) public long MaxAge { get; set; } // ── Idempotency ───────────────────────────────────────────────── /// /// Enable idempotent consumer — skip objects already processed /// (tracked by key|ETag|size). Uses an in-memory repository by default. /// (default: false) /// public bool Idempotent { get; set; } /// /// Name of an IIdempotentRepository registered via /// context.AddIdempotentRepository(name, repo) — the same contract the route-level /// IdempotentConsumer EIP uses. With a persistent repository (RedbIdempotentRepository) /// deduplication survives restarts and scale-out. Takes precedence over the in-memory /// flag. /// [RegistryReference(typeof(IIdempotentRepository))] public string IdempotentRepository { get; set; } = ""; // ═══════════════════════════════════════════════════════════════════ // PRODUCER (uploading/operations) // ═══════════════════════════════════════════════════════════════════ /// /// Dynamic object key name for upload. Supports ${header.xxx} expressions. /// If not set, falls back to the header from the exchange. /// public DynamicValue? KeyName { get; set; } /// /// S3 storage class for uploaded objects: STANDARD, REDUCED_REDUNDANCY, GLACIER, /// STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING, DEEP_ARCHIVE, GLACIER_IR. /// Empty = bucket default (STANDARD). (default: "") /// public string StorageClass { get; set; } = ""; /// Content-Type for uploaded objects. Empty = auto-detect. public string ContentType { get; set; } = ""; /// Content-Disposition header for uploaded objects. public string ContentDisposition { get; set; } = ""; /// Content-Encoding header for uploaded objects (e.g. "gzip"). public string ContentEncoding { get; set; } = ""; /// Cache-Control header for uploaded objects. public string CacheControl { get; set; } = ""; /// Canned ACL for uploaded objects. (default: Private) public S3CannedAcl CannedAcl { get; set; } = S3CannedAcl.Private; /// /// If true, use multipart upload for files larger than . /// Smaller files use single-part upload. (default: false) /// public bool MultiPartUpload { get; set; } /// /// Part size in bytes for multipart uploads. Minimum AWS limit: 5 MB. /// (default: 26214400 = 25 MB) /// public long PartSize { get; set; } = 26_214_400; /// /// If true, upload only succeeds if the object key does not already exist. /// Uses conditional writes (x-amz-if-none-match). (default: false) /// public bool ConditionalWrite { get; set; } // ── Server-Side Encryption ────────────────────────────────────── /// Server-side encryption mode. (default: None) public S3ServerSideEncryption ServerSideEncryption { get; set; } = S3ServerSideEncryption.None; /// KMS key ID for SSE-KMS encryption. public string KmsKeyId { get; set; } = ""; /// Customer encryption key (base64-encoded) for SSE-C. public string CustomerKeyId { get; set; } = ""; /// MD5 hash of the customer encryption key (base64-encoded) for SSE-C. public string CustomerKeyMD5 { get; set; } = ""; // ── Presigned URLs ────────────────────────────────────────────── /// /// Presigned URL expiration in milliseconds. /// (default: 3600000 = 1 hour) /// public long PresignedUrlExpiration { get; set; } = 3_600_000; // The Streaming Upload Mode block (StreamingUploadMode, BatchMessageNumber, BatchSize, // BufferSize, StreamingUploadTimeout, NamingStrategy) is gone since the options sweep. // Six options and a DSL verb promised camel-style accumulate-and-flush, and NOTHING read them // beyond Validate(): the mode was never implemented. Accumulate-then-write is the route's job // in this framework, and the core Aggregate(...) EIP already does it with completion by // count, size and timeout: .Aggregate(...).To(S3.Bucket(...)) - see the README recipe. // ── Metadata ──────────────────────────────────────────────────── /// /// User metadata as comma-separated key=value pairs to attach to uploaded objects. /// Example: author=redb,env=production. /// public string Metadata { get; set; } = ""; // ═══════════════════════════════════════════════════════════════════ // VALIDATION // ═══════════════════════════════════════════════════════════════════ /// public override void Validate() { if (!string.IsNullOrEmpty(DoneFileName) && FileLanguage.FindUnknownKey(DoneFileName, StringComparison.OrdinalIgnoreCase) is { } key) throw new InvalidOperationException($"doneFileName='{DoneFileName}': {FileLanguage.UnknownKeyMessage(key)}"); if (!UseDefaultCredentialsProvider && string.IsNullOrEmpty(ConnectionFactory) && string.IsNullOrEmpty(ProfileName) && (string.IsNullOrEmpty(AccessKey) || string.IsNullOrEmpty(SecretKey))) { throw new ArgumentException( "S3 credentials required: provide AccessKey+SecretKey, set UseDefaultCredentialsProvider=true, " + "specify ProfileName, or reference a ConnectionFactory."); } if (string.IsNullOrWhiteSpace(Region)) throw new ArgumentException("S3 Region must be specified."); if (Delay < 0) throw new ArgumentOutOfRangeException(nameof(Delay), Delay, "Delay cannot be negative."); if (InitialDelay < 0) throw new ArgumentOutOfRangeException(nameof(InitialDelay), InitialDelay, "InitialDelay cannot be negative."); if (MaxMessagesPerPoll < 0) throw new ArgumentOutOfRangeException(nameof(MaxMessagesPerPoll), MaxMessagesPerPoll, "MaxMessagesPerPoll cannot be negative."); if (MoveAfterRead && string.IsNullOrEmpty(DestinationBucket)) throw new InvalidOperationException("DestinationBucket is required when MoveAfterRead=true."); if (MoveAfterRead && DeleteAfterRead && _deleteAfterReadSet) throw new InvalidOperationException( "Cannot set both MoveAfterRead=true and DeleteAfterRead=true. MoveAfterRead implies the object is moved, not deleted from source after move."); if (MinAge < 0) throw new ArgumentOutOfRangeException(nameof(MinAge), MinAge, "MinAge cannot be negative."); if (MaxAge < 0) throw new ArgumentOutOfRangeException(nameof(MaxAge), MaxAge, "MaxAge cannot be negative."); if (ConnectionTimeout < 0) throw new ArgumentOutOfRangeException(nameof(ConnectionTimeout), ConnectionTimeout, "ConnectionTimeout cannot be negative."); if (SocketTimeout < 0) throw new ArgumentOutOfRangeException(nameof(SocketTimeout), SocketTimeout, "SocketTimeout cannot be negative."); if (MaxConnections < 1) throw new ArgumentOutOfRangeException(nameof(MaxConnections), MaxConnections, "MaxConnections must be at least 1."); if (RetryCount < 0) throw new ArgumentOutOfRangeException(nameof(RetryCount), RetryCount, "RetryCount cannot be negative."); if (PartSize < 5_242_880) throw new ArgumentOutOfRangeException(nameof(PartSize), PartSize, "PartSize must be at least 5 MB (5242880 bytes) for multipart upload."); if (PresignedUrlExpiration <= 0) throw new ArgumentOutOfRangeException(nameof(PresignedUrlExpiration), PresignedUrlExpiration, "PresignedUrlExpiration must be positive."); if (ServerSideEncryption == S3ServerSideEncryption.AwsKms && string.IsNullOrEmpty(KmsKeyId)) throw new ArgumentException("KmsKeyId is required when ServerSideEncryption=AwsKms."); if (ServerSideEncryption == S3ServerSideEncryption.CustomerKey && string.IsNullOrEmpty(CustomerKeyId)) throw new ArgumentException("CustomerKeyId is required when ServerSideEncryption=CustomerKey."); if (ProxyPort is < 0 or > 65535) throw new ArgumentOutOfRangeException(nameof(ProxyPort), ProxyPort, "ProxyPort must be 0–65535 (0 = no proxy)."); } } Path: redb-route/redb.Route.S3/S3Enums.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/S3Enums.cs ---- namespace redb.Route.S3; /// /// Server-side encryption modes for S3 objects. /// public enum S3ServerSideEncryption { /// No server-side encryption. None, /// SSE-S3: Amazon S3 managed keys (AES-256). Aes256, /// SSE-KMS: AWS Key Management Service managed keys. AwsKms, /// SSE-C: Customer-provided encryption keys. CustomerKey, } /// /// Sort order for consumer polling results. /// public enum S3SortBy { /// No sorting (S3 listing order). None, /// Sort by object key ascending. Key, /// Sort by object key descending. KeyDesc, /// Sort by last modified ascending. LastModified, /// Sort by last modified descending. LastModifiedDesc, /// Sort by size ascending. Size, /// Sort by size descending. SizeDesc, } /// /// Canned ACL presets for S3 objects and buckets. /// public enum S3CannedAcl { /// Owner gets FULL_CONTROL. No one else has access rights. Private, /// Owner gets FULL_CONTROL. The AllUsers group gets READ access. PublicRead, /// Owner gets FULL_CONTROL. The AllUsers group gets READ and WRITE access. PublicReadWrite, /// Owner gets FULL_CONTROL. The AuthenticatedUsers group gets READ access. AuthenticatedRead, /// Object owner gets FULL_CONTROL. Bucket owner gets READ access. BucketOwnerRead, /// Both the object owner and the bucket owner get FULL_CONTROL. BucketOwnerFullControl, } Path: redb-route/redb.Route.S3/S3Headers.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/S3Headers.cs ---- namespace redb.Route.S3; /// /// Well-known header constants used by the S3 component. /// Follows the redbS3. prefix convention. /// public static class S3Headers { /// Common prefix for all S3 component headers. public const string Prefix = "redbS3."; // ═══════════════════════════════════════════════════════════════════ // COMMON (set by consumer, read by producer) // ═══════════════════════════════════════════════════════════════════ /// Bucket name. public const string BucketName = "redbS3.BucketName"; /// Object key (path within the bucket). public const string Key = "redbS3.Key"; /// Content-Type MIME type of the object. public const string ContentType = "redbS3.ContentType"; /// Content-Length in bytes. public const string ContentLength = "redbS3.ContentLength"; /// Content-MD5 (base64-encoded). public const string ContentMD5 = "redbS3.ContentMD5"; /// Content-Disposition header value. public const string ContentDisposition = "redbS3.ContentDisposition"; /// Content-Encoding header value. public const string ContentEncoding = "redbS3.ContentEncoding"; /// Cache-Control header value. public const string CacheControl = "redbS3.CacheControl"; /// ETag of the object (hex-encoded MD5 on upload, or opaque for multipart). public const string ETag = "redbS3.ETag"; /// Last modified timestamp. public const string LastModified = "redbS3.LastModified"; /// S3 storage class (STANDARD, GLACIER, etc.). public const string StorageClass = "redbS3.StorageClass"; /// Version ID (if bucket versioning is enabled). public const string VersionId = "redbS3.VersionId"; /// Server-side encryption algorithm. public const string ServerSideEncryption = "redbS3.ServerSideEncryption"; /// S3 operation to perform (used to override endpoint operation). public const string Operation = "redbS3.Operation"; // ═══════════════════════════════════════════════════════════════════ // CONSUMER (set on incoming messages) // ═══════════════════════════════════════════════════════════════════ /// Object expiration time (if lifecycle configured). public const string ExpirationTime = "redbS3.ExpirationTime"; /// Replication status (COMPLETE, PENDING, FAILED, REPLICA). public const string ReplicationStatus = "redbS3.ReplicationStatus"; /// Message timestamp (Unix ms). public const string Timestamp = "redbS3.Timestamp"; // ═══════════════════════════════════════════════════════════════════ // PRODUCER INPUT (set by user before sending) // ═══════════════════════════════════════════════════════════════════ /// Destination bucket name (for CopyObject). public const string DestinationBucket = "redbS3.DestinationBucket"; /// Destination object key (for CopyObject). public const string DestinationKey = "redbS3.DestinationKey"; /// Canned ACL preset (Private, PublicRead, etc.). public const string CannedAcl = "redbS3.CannedAcl"; /// Range start byte offset (for GetObjectRange). public const string RangeStart = "redbS3.RangeStart"; /// Range end byte offset (for GetObjectRange). public const string RangeEnd = "redbS3.RangeEnd"; /// Presigned URL expiration in milliseconds. public const string PresignedUrlExpiration = "redbS3.PresignedUrlExpiration"; /// List of keys to delete (for DeleteObjects operation). public const string KeysToDelete = "redbS3.KeysToDelete"; /// Object tags dictionary (for PutObjectTagging). public const string ObjectTags = "redbS3.ObjectTags"; /// Versioning status: "Enabled" or "Suspended" (for PutBucketVersioning). public const string VersioningStatus = "redbS3.VersioningStatus"; /// Number of days for Glacier restore (for RestoreObject). public const string RestoreDays = "redbS3.RestoreDays"; /// Restore tier: Standard, Bulk, Expedited (for RestoreObject). public const string RestoreTier = "redbS3.RestoreTier"; /// Override bucket name dynamically (overrides endpoint bucket). public const string OverrideBucketName = "redbS3.OverrideBucketName"; // ═══════════════════════════════════════════════════════════════════ // METADATA // ═══════════════════════════════════════════════════════════════════ /// /// Prefix for user metadata headers. Example: redbS3.Meta.x-amz-meta-author. /// All headers with this prefix are mapped to S3 object metadata on upload /// and populated from S3 object metadata on download. /// public const string MetadataPrefix = "redbS3.Meta."; // ═══════════════════════════════════════════════════════════════════ // PRODUCER OUTPUT // ═══════════════════════════════════════════════════════════════════ /// Presigned URL (set after CreateDownloadLink/CreateUploadLink). public const string PresignedUrl = "redbS3.PresignedUrl"; /// The produced (resolved) key name after upload. public const string ProducedKey = "redbS3.ProducedKey"; /// The produced (resolved) bucket name after operation. public const string ProducedBucketName = "redbS3.ProducedBucketName"; /// Whether the bucket exists (set after HeadBucket). public const string BucketExists = "redbS3.BucketExists"; /// Returns true if the header key belongs to the S3 component. public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.S3/S3OperationType.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/S3OperationType.cs ---- namespace redb.Route.S3; /// /// S3 operation types — determines what the producer does. /// Parsed from the first path segment of the URI: s3:OPERATION:bucket. /// When no operation is specified, the default is for producer /// and polling list for consumer. /// public enum S3OperationType { // ── Object operations ── /// Upload an object to the bucket. Default producer operation. PutObject, /// Download an object from the bucket. GetObject, /// Download a byte range of an object. GetObjectRange, /// Delete a single object. DeleteObject, /// Delete multiple objects in a single request. DeleteObjects, /// Copy an object from one bucket/key to another. CopyObject, /// List objects in the bucket (with optional prefix/delimiter). ListObjects, /// Get object metadata without downloading the body. HeadObject, // ── Presigned URLs ── /// Generate a presigned download URL. CreateDownloadLink, /// Generate a presigned upload URL. CreateUploadLink, // ── Bucket operations ── /// Create a new bucket. CreateBucket, /// Delete a bucket. DeleteBucket, /// Check if a bucket exists and is accessible. HeadBucket, /// List all buckets for the account. ListBuckets, // ── Tagging ── /// Get tags on an object. GetObjectTagging, /// Set tags on an object. PutObjectTagging, /// Delete all tags from an object. DeleteObjectTagging, // ── ACL ── /// Get the ACL of an object. GetObjectAcl, /// Set the ACL of an object. PutObjectAcl, // ── Versioning ── /// Get bucket versioning configuration. GetBucketVersioning, /// Set bucket versioning (enable/suspend). PutBucketVersioning, // ── Restore (Glacier) ── /// Restore an archived (Glacier) object. RestoreObject, } Path: redb-route/redb.Route.S3/S3Producer.Management.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/S3Producer.Management.cs ---- using System.Diagnostics; using System.Net; using Amazon.S3; using Amazon.S3.Model; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.S3; /// Bucket, tagging, ACL, versioning and restore operations of . internal sealed partial class S3Producer { // ═══════════════════════════════════════════════════════════════════ // BUCKET OPERATIONS // ═══════════════════════════════════════════════════════════════════ private async Task ProcessCreateBucketAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); await EnsureBucketExistsAsync(bucket, ct).ConfigureAwait(false); Logger?.LogDebug("S3 CreateBucket: {Bucket}", bucket); } private async Task ProcessDeleteBucketAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); await _client!.DeleteBucketAsync(bucket, ct).ConfigureAwait(false); Logger?.LogDebug("S3 DeleteBucket: {Bucket}", bucket); } private async Task ProcessHeadBucketAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); bool exists; try { await _client!.EnsureBucketExistsAsync(bucket).ConfigureAwait(false); exists = true; } catch { exists = false; } exchange.In.Headers[S3Headers.BucketExists] = exists; exchange.In.Body = exists; } private async Task ProcessListBucketsAsync(IExchange exchange, CancellationToken ct) { var response = await _client!.ListBucketsAsync(ct).ConfigureAwait(false); exchange.In.Body = response.Buckets.Select(b => new { b.BucketName, b.CreationDate }).ToList(); } // ═══════════════════════════════════════════════════════════════════ // TAGGING // ═══════════════════════════════════════════════════════════════════ private async Task ProcessGetObjectTaggingAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var response = await _client!.GetObjectTaggingAsync(new GetObjectTaggingRequest { BucketName = bucket, Key = key, }, ct).ConfigureAwait(false); exchange.In.Body = response.Tagging.ToDictionary(t => t.Key, t => t.Value); } private async Task ProcessPutObjectTaggingAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var tags = exchange.In.GetHeader>(S3Headers.ObjectTags) ?? (exchange.In.Body as Dictionary) ?? throw new InvalidOperationException($"Tags must be provided via header '{S3Headers.ObjectTags}' or body (Dictionary)."); await _client!.PutObjectTaggingAsync(new PutObjectTaggingRequest { BucketName = bucket, Key = key, Tagging = new Tagging { TagSet = tags.Select(kv => new Tag { Key = kv.Key, Value = kv.Value }).ToList() }, }, ct).ConfigureAwait(false); } private async Task ProcessDeleteObjectTaggingAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); await _client!.DeleteObjectTaggingAsync(new DeleteObjectTaggingRequest { BucketName = bucket, Key = key, }, ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // ACL // ═══════════════════════════════════════════════════════════════════ private async Task ProcessGetObjectAclAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var response = await _client!.GetObjectAclAsync(new GetObjectAclRequest { BucketName = bucket, Key = key, }, ct).ConfigureAwait(false); exchange.In.Body = response.Grants; } private async Task ProcessPutObjectAclAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var cannedAclStr = exchange.In.GetHeader(S3Headers.CannedAcl) ?? _options.CannedAcl.ToString(); await _client!.PutObjectAclAsync(new PutObjectAclRequest { BucketName = bucket, Key = key, ACL = MapCannedAcl(cannedAclStr), }, ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // VERSIONING // ═══════════════════════════════════════════════════════════════════ private async Task ProcessGetBucketVersioningAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var response = await _client!.GetBucketVersioningAsync(new GetBucketVersioningRequest { BucketName = bucket, }, ct).ConfigureAwait(false); exchange.In.Body = response.VersioningConfig.Status?.Value ?? "Off"; exchange.In.Headers[S3Headers.VersioningStatus] = response.VersioningConfig.Status?.Value ?? "Off"; } private async Task ProcessPutBucketVersioningAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var status = exchange.In.GetHeader(S3Headers.VersioningStatus) ?? "Enabled"; await _client!.PutBucketVersioningAsync(new PutBucketVersioningRequest { BucketName = bucket, VersioningConfig = new S3BucketVersioningConfig { Status = status.Equals("Enabled", StringComparison.OrdinalIgnoreCase) ? VersionStatus.Enabled : VersionStatus.Suspended, }, }, ct).ConfigureAwait(false); Logger?.LogDebug("S3 PutBucketVersioning: {Bucket} → {Status}", bucket, status); } // ═══════════════════════════════════════════════════════════════════ // RESTORE // ═══════════════════════════════════════════════════════════════════ private async Task ProcessRestoreObjectAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var days = exchange.In.GetHeader(S3Headers.RestoreDays) ?? 1; var tier = exchange.In.GetHeader(S3Headers.RestoreTier) ?? "Standard"; await _client!.RestoreObjectAsync(new RestoreObjectRequest { BucketName = bucket, Key = key, Days = days, Tier = tier switch { "Expedited" => GlacierJobTier.Expedited, "Bulk" => GlacierJobTier.Bulk, _ => GlacierJobTier.Standard, }, }, ct).ConfigureAwait(false); Logger?.LogDebug("S3 RestoreObject: {Bucket}/{Key}, days={Days}, tier={Tier}", bucket, key, days, tier); } } Path: redb-route/redb.Route.S3/S3Producer.Objects.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/S3Producer.Objects.cs ---- using System.Diagnostics; using System.Net; using Amazon.S3; using Amazon.S3.Model; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.S3; /// Object operations and presigned URLs of . internal sealed partial class S3Producer { // ═══════════════════════════════════════════════════════════════════ // OBJECT OPERATIONS // ═══════════════════════════════════════════════════════════════════ private async Task ProcessPutObjectAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var request = new PutObjectRequest { BucketName = bucket, Key = key, }; // Conditional PUT (S-5): create-only semantics — fails with 412 when the key exists. if (_options.ConditionalWrite) request.IfNoneMatch = "*"; // Resolve body to stream var body = exchange.In.Body; switch (body) { case Stream stream: request.InputStream = stream; break; case byte[] bytes: request.InputStream = new MemoryStream(bytes); break; case string text: request.ContentBody = text; break; case null: request.InputStream = new MemoryStream(Array.Empty()); break; default: request.ContentBody = BodyText.Of(body); break; } // Content headers ApplyContentHeaders(request, exchange); ApplyEncryption(request); ApplyMetadata(request, exchange); ApplyStorageClass(request); ApplyCannedAcl(request, exchange); if (_options.MultiPartUpload && request.InputStream is { Length: > 0 } s && s.Length > _options.PartSize) { var completed = await MultiPartUploadAsync(bucket, key, request, ct).ConfigureAwait(false); // The same result headers as a single PUT: which object was written, its ETag and version. SetProducedHeaders(exchange, bucket, key, completed.ETag, completed.VersionId); } else { var response = await _client!.PutObjectAsync(request, ct).ConfigureAwait(false); SetProducedHeaders(exchange, bucket, key, response.ETag, response.VersionId); } if (request.InputStream is MemoryStream ms && body is not Stream) ms.Dispose(); Logger?.LogDebug("S3 PutObject: {Bucket}/{Key}", bucket, key); } private async Task MultiPartUploadAsync(string bucket, string key, PutObjectRequest request, CancellationToken ct) { var initRequest = new InitiateMultipartUploadRequest { BucketName = bucket, Key = key, ContentType = request.ContentType, StorageClass = request.StorageClass, }; // Copy SSE settings initRequest.ServerSideEncryptionMethod = request.ServerSideEncryptionMethod; if (!string.IsNullOrEmpty(request.ServerSideEncryptionKeyManagementServiceKeyId)) initRequest.ServerSideEncryptionKeyManagementServiceKeyId = request.ServerSideEncryptionKeyManagementServiceKeyId; var initResponse = await _client!.InitiateMultipartUploadAsync(initRequest, ct).ConfigureAwait(false); var uploadId = initResponse.UploadId; try { var partETags = new List(); var stream = request.InputStream!; stream.Position = 0; var partNumber = 1; var buffer = new byte[_options.PartSize]; while (true) { var bytesRead = await ReadExactAsync(stream, buffer, ct).ConfigureAwait(false); if (bytesRead == 0) break; using var partStream = new MemoryStream(buffer, 0, bytesRead); var uploadPartRequest = new UploadPartRequest { BucketName = bucket, Key = key, UploadId = uploadId, PartNumber = partNumber, InputStream = partStream, }; var uploadPartResponse = await _client.UploadPartAsync(uploadPartRequest, ct).ConfigureAwait(false); partETags.Add(new PartETag(partNumber, uploadPartResponse.ETag)); partNumber++; } var completeRequest = new CompleteMultipartUploadRequest { BucketName = bucket, Key = key, UploadId = uploadId, PartETags = partETags, }; var completed = await _client.CompleteMultipartUploadAsync(completeRequest, ct).ConfigureAwait(false); Logger?.LogDebug("S3 MultiPartUpload completed: {Bucket}/{Key}, {Parts} parts", bucket, key, partETags.Count); return completed; } catch { // Abort multipart upload on failure try { await _client.AbortMultipartUploadAsync(new AbortMultipartUploadRequest { BucketName = bucket, Key = key, UploadId = uploadId, }, CancellationToken.None).ConfigureAwait(false); } catch (Exception abortEx) { Logger?.LogWarning(abortEx, "Failed to abort multipart upload {UploadId}", uploadId); } throw; } } private async Task ProcessGetObjectAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var request = new GetObjectRequest { BucketName = bucket, Key = key, }; var response = await _client!.GetObjectAsync(request, ct).ConfigureAwait(false); if (_options.IgnoreBody) { response.ResponseStream?.Dispose(); } else if (_options.StreamBody) { exchange.In.Body = response.ResponseStream; } else if (_options.IncludeBody) { using var ms = new MemoryStream(); await response.ResponseStream.CopyToAsync(ms, ct).ConfigureAwait(false); exchange.In.Body = ms.ToArray(); response.ResponseStream.Dispose(); _endpoint.RecordBytesIn(ms.Length); } else { exchange.In.Body = response.ResponseStream; } SetObjectMetadataHeaders(exchange, response); } private async Task ProcessGetObjectRangeAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var rangeStart = exchange.In.GetHeader(S3Headers.RangeStart) ?? 0; var rangeEnd = exchange.In.GetHeader(S3Headers.RangeEnd) ?? 0; var request = new GetObjectRequest { BucketName = bucket, Key = key, ByteRange = new ByteRange(rangeStart, rangeEnd), }; var response = await _client!.GetObjectAsync(request, ct).ConfigureAwait(false); using var ms = new MemoryStream(); await response.ResponseStream.CopyToAsync(ms, ct).ConfigureAwait(false); exchange.In.Body = ms.ToArray(); response.ResponseStream.Dispose(); SetObjectMetadataHeaders(exchange, response); _endpoint.RecordBytesIn(ms.Length); } private async Task ProcessDeleteObjectAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); await _client!.DeleteObjectAsync(bucket, key, ct).ConfigureAwait(false); Logger?.LogDebug("S3 DeleteObject: {Bucket}/{Key}", bucket, key); } private async Task ProcessDeleteObjectsAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var keys = exchange.In.GetHeader>(S3Headers.KeysToDelete) ?? throw new InvalidOperationException($"Header '{S3Headers.KeysToDelete}' (List) is required for DeleteObjects."); var request = new DeleteObjectsRequest { BucketName = bucket, Objects = keys.Select(k => new KeyVersion { Key = k }).ToList(), }; var response = await _client!.DeleteObjectsAsync(request, ct).ConfigureAwait(false); exchange.In.Body = response.DeletedObjects.Select(d => d.Key).ToList(); Logger?.LogDebug("S3 DeleteObjects: {Bucket}, {Count} deleted", bucket, response.DeletedObjects.Count); } private async Task ProcessCopyObjectAsync(IExchange exchange, CancellationToken ct) { var sourceBucket = ResolveBucket(exchange); var sourceKey = ResolveKey(exchange); var destBucket = exchange.In.GetHeader(S3Headers.DestinationBucket) ?? throw new InvalidOperationException($"Header '{S3Headers.DestinationBucket}' is required for CopyObject."); var destKey = exchange.In.GetHeader(S3Headers.DestinationKey) ?? sourceKey; var request = new CopyObjectRequest { SourceBucket = sourceBucket, SourceKey = sourceKey, DestinationBucket = destBucket, DestinationKey = destKey, }; var response = await _client!.CopyObjectAsync(request, ct).ConfigureAwait(false); // The object written is the copy: its bucket and key are the produced ones. SetProducedHeaders(exchange, destBucket, destKey, response.ETag, response.VersionId); Logger?.LogDebug("S3 CopyObject: {SrcBucket}/{SrcKey} → {DstBucket}/{DstKey}", sourceBucket, sourceKey, destBucket, destKey); } private async Task ProcessListObjectsAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var request = new ListObjectsV2Request { BucketName = bucket, Prefix = _options.Prefix, Delimiter = _options.Delimiter, MaxKeys = _options.MaxMessagesPerPoll > 0 ? _options.MaxMessagesPerPoll : 1000, }; var response = await _client!.ListObjectsV2Async(request, ct).ConfigureAwait(false); exchange.In.Body = response.S3Objects.Select(o => new S3ObjectInfo { Key = o.Key, Size = o.Size ?? 0, LastModified = o.LastModified ?? DateTime.MinValue, ETag = o.ETag, StorageClass = o.StorageClass?.Value, }).ToList(); Logger?.LogDebug("S3 ListObjects: {Bucket}, prefix={Prefix}, {Count} objects", bucket, _options.Prefix, response.S3Objects.Count); } private async Task ProcessHeadObjectAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var request = new GetObjectMetadataRequest { BucketName = bucket, Key = key, }; var response = await _client!.GetObjectMetadataAsync(request, ct).ConfigureAwait(false); exchange.In.Headers[S3Headers.ContentType] = response.Headers.ContentType; exchange.In.Headers[S3Headers.ContentLength] = response.ContentLength; exchange.In.Headers[S3Headers.ETag] = response.ETag; exchange.In.Headers[S3Headers.LastModified] = response.LastModified; exchange.In.Headers[S3Headers.VersionId] = response.VersionId; exchange.In.Headers[S3Headers.StorageClass] = response.StorageClass?.Value; exchange.In.Headers[S3Headers.ServerSideEncryption] = response.ServerSideEncryptionMethod?.Value; // User metadata foreach (var meta in response.Metadata.Keys) exchange.In.Headers[$"{S3Headers.MetadataPrefix}{meta}"] = response.Metadata[meta]; } // ═══════════════════════════════════════════════════════════════════ // PRESIGNED URLS // ═══════════════════════════════════════════════════════════════════ private Task ProcessCreateDownloadLinkAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var expirationMs = exchange.In.GetHeader(S3Headers.PresignedUrlExpiration) ?? _options.PresignedUrlExpiration; var request = new GetPreSignedUrlRequest { BucketName = bucket, Key = key, Expires = DateTime.UtcNow.AddMilliseconds(expirationMs), Verb = HttpVerb.GET, }; var url = _client!.GetPreSignedURL(request); exchange.In.Headers[S3Headers.PresignedUrl] = url; exchange.In.Body = url; Logger?.LogDebug("S3 CreateDownloadLink: {Bucket}/{Key}, expires={ExpirationMs}ms", bucket, key, expirationMs); return Task.CompletedTask; } private Task ProcessCreateUploadLinkAsync(IExchange exchange, CancellationToken ct) { var bucket = ResolveBucket(exchange); var key = ResolveKey(exchange); var expirationMs = exchange.In.GetHeader(S3Headers.PresignedUrlExpiration) ?? _options.PresignedUrlExpiration; var request = new GetPreSignedUrlRequest { BucketName = bucket, Key = key, Expires = DateTime.UtcNow.AddMilliseconds(expirationMs), Verb = HttpVerb.PUT, }; if (!string.IsNullOrEmpty(_options.ContentType)) request.ContentType = _options.ContentType; var url = _client!.GetPreSignedURL(request); exchange.In.Headers[S3Headers.PresignedUrl] = url; exchange.In.Body = url; Logger?.LogDebug("S3 CreateUploadLink: {Bucket}/{Key}, expires={ExpirationMs}ms", bucket, key, expirationMs); return Task.CompletedTask; } } Path: redb-route/redb.Route.S3/S3Producer.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/S3Producer.cs ---- using System.Diagnostics; using System.Net; using Amazon.S3; using Amazon.S3.Model; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.S3; /// /// S3 producer — sends messages to S3. Extends /// for persistent SDK client lifecycle. /// /// Supports 22 operations: PutObject, GetObject, GetObjectRange, DeleteObject, /// DeleteObjects, CopyObject, ListObjects, HeadObject, CreateDownloadLink, /// CreateUploadLink, CreateBucket, DeleteBucket, HeadBucket, ListBuckets, /// Get/Put/DeleteObjectTagging, Get/PutObjectAcl, Get/PutBucketVersioning, RestoreObject. /// /// internal sealed partial class S3Producer : ConnectableProducer { private readonly S3Endpoint _endpoint; private readonly S3EndpointOptions _options; private IAmazonS3? _client; /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"s3:{_endpoint.OperationType}:{_endpoint.BucketName}"; internal S3Producer(S3Endpoint endpoint, S3EndpointOptions options) { _endpoint = endpoint; _options = options; } /// protected override async Task ConnectAsync(CancellationToken ct) { _client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false); if (_options.AutoCreateBucket) await EnsureBucketExistsAsync(_endpoint.BucketName, ct).ConfigureAwait(false); } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); ArgumentNullException.ThrowIfNull(exchange); // Allow runtime operation override via header var operation = _endpoint.OperationType; if (exchange.In.Headers.TryGetValue(S3Headers.Operation, out var opHeader) && opHeader is string opStr) { if (Enum.TryParse(opStr, ignoreCase: true, out var headerOp)) operation = headerOp; } using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"s3 {operation}", ActivityKind.Client, "redb.system", "s3", _endpoint.Uri.NormalizedKey, destination: _endpoint.BucketName, operation: operation.ToString()); try { await DispatchOperationAsync(operation, exchange, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only our own token cancelling the call is a stop; a timeout or any other failure marks the span. activity.RecordFailure(ex); throw; } } // ═══════════════════════════════════════════════════════════════════ // OPERATION DISPATCH // ═══════════════════════════════════════════════════════════════════ private async Task DispatchOperationAsync(S3OperationType operation, IExchange exchange, CancellationToken ct) { switch (operation) { case S3OperationType.PutObject: await ProcessPutObjectAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.GetObject: await ProcessGetObjectAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.GetObjectRange: await ProcessGetObjectRangeAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.DeleteObject: await ProcessDeleteObjectAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.DeleteObjects: await ProcessDeleteObjectsAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.CopyObject: await ProcessCopyObjectAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.ListObjects: await ProcessListObjectsAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.HeadObject: await ProcessHeadObjectAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.CreateDownloadLink: await ProcessCreateDownloadLinkAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.CreateUploadLink: await ProcessCreateUploadLinkAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.CreateBucket: await ProcessCreateBucketAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.DeleteBucket: await ProcessDeleteBucketAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.HeadBucket: await ProcessHeadBucketAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.ListBuckets: await ProcessListBucketsAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.GetObjectTagging: await ProcessGetObjectTaggingAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.PutObjectTagging: await ProcessPutObjectTaggingAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.DeleteObjectTagging: await ProcessDeleteObjectTaggingAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.GetObjectAcl: await ProcessGetObjectAclAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.PutObjectAcl: await ProcessPutObjectAclAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.GetBucketVersioning: await ProcessGetBucketVersioningAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.PutBucketVersioning: await ProcessPutBucketVersioningAsync(exchange, ct).ConfigureAwait(false); break; case S3OperationType.RestoreObject: await ProcessRestoreObjectAsync(exchange, ct).ConfigureAwait(false); break; default: throw new NotSupportedException($"S3 operation '{operation}' is not supported."); } // MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit. } // ═══════════════════════════════════════════════════════════════════ // HELPERS // ═══════════════════════════════════════════════════════════════════ private string ResolveBucket(IExchange exchange) { // Priority: header override → endpoint bucket return exchange.In.GetHeader(S3Headers.OverrideBucketName) ?? _endpoint.BucketName; } private string ResolveKey(IExchange exchange) { // Priority: KeyName option (dynamic) → header → fallback to empty if (_options.KeyName is not null) { var resolved = _options.KeyName.Value.Resolve(exchange); if (!string.IsNullOrEmpty(resolved)) return resolved; } return exchange.In.GetHeader(S3Headers.Key) ?? throw new InvalidOperationException( $"Object key must be provided via KeyName option or '{S3Headers.Key}' header."); } private void ApplyContentHeaders(PutObjectRequest request, IExchange exchange) { var contentType = exchange.In.GetHeader(S3Headers.ContentType) ?? _options.ContentType; if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType; var disposition = exchange.In.GetHeader(S3Headers.ContentDisposition) ?? _options.ContentDisposition; if (!string.IsNullOrEmpty(disposition)) request.Headers["Content-Disposition"] = disposition; var encoding = exchange.In.GetHeader(S3Headers.ContentEncoding) ?? _options.ContentEncoding; if (!string.IsNullOrEmpty(encoding)) request.Headers["Content-Encoding"] = encoding; var cacheControl = exchange.In.GetHeader(S3Headers.CacheControl) ?? _options.CacheControl; if (!string.IsNullOrEmpty(cacheControl)) request.Headers["Cache-Control"] = cacheControl; } private void ApplyEncryption(PutObjectRequest request) { switch (_options.ServerSideEncryption) { case S3ServerSideEncryption.Aes256: request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256; break; case S3ServerSideEncryption.AwsKms: request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.AWSKMS; if (!string.IsNullOrEmpty(_options.KmsKeyId)) request.ServerSideEncryptionKeyManagementServiceKeyId = _options.KmsKeyId; break; case S3ServerSideEncryption.CustomerKey: request.ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256; request.ServerSideEncryptionCustomerProvidedKey = _options.CustomerKeyId; if (!string.IsNullOrEmpty(_options.CustomerKeyMD5)) request.ServerSideEncryptionCustomerProvidedKeyMD5 = _options.CustomerKeyMD5; break; } } private void ApplyMetadata(PutObjectRequest request, IExchange exchange) { // From options if (!string.IsNullOrEmpty(_options.Metadata)) { foreach (var pair in _options.Metadata.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { var eqIndex = pair.IndexOf('='); if (eqIndex > 0) request.Metadata.Add(pair[..eqIndex].Trim(), pair[(eqIndex + 1)..].Trim()); } } // From headers (MetadataPrefix) foreach (var header in exchange.In.Headers) { if (header.Key.StartsWith(S3Headers.MetadataPrefix, StringComparison.OrdinalIgnoreCase) && header.Value is string value) { var metaKey = header.Key[S3Headers.MetadataPrefix.Length..]; request.Metadata.Add(metaKey, value); } } } private void ApplyStorageClass(PutObjectRequest request) { if (!string.IsNullOrEmpty(_options.StorageClass)) request.StorageClass = new S3StorageClass(_options.StorageClass); } private void ApplyCannedAcl(PutObjectRequest request, IExchange exchange) { var cannedAclStr = exchange.In.GetHeader(S3Headers.CannedAcl); if (!string.IsNullOrEmpty(cannedAclStr)) { request.CannedACL = MapCannedAcl(cannedAclStr); return; } if (_options.CannedAcl != S3CannedAcl.Private) request.CannedACL = MapCannedAcl(_options.CannedAcl.ToString()); } private static S3CannedACL MapCannedAcl(string value) => value switch { "Private" or "private" => S3CannedACL.Private, "PublicRead" or "public-read" => S3CannedACL.PublicRead, "PublicReadWrite" or "public-read-write" => S3CannedACL.PublicReadWrite, "AuthenticatedRead" or "authenticated-read" => S3CannedACL.AuthenticatedRead, "BucketOwnerRead" or "bucket-owner-read" => S3CannedACL.BucketOwnerRead, "BucketOwnerFullControl" or "bucket-owner-full-control" => S3CannedACL.BucketOwnerFullControl, _ => S3CannedACL.Private, }; private void SetProducedHeaders(IExchange exchange, string bucket, string key, string? etag, string? versionId) { exchange.In.Headers[S3Headers.ProducedBucketName] = bucket; exchange.In.Headers[S3Headers.ProducedKey] = key; if (!string.IsNullOrEmpty(etag)) exchange.In.Headers[S3Headers.ETag] = etag; if (!string.IsNullOrEmpty(versionId)) exchange.In.Headers[S3Headers.VersionId] = versionId; } private static void SetObjectMetadataHeaders(IExchange exchange, GetObjectResponse response) { exchange.In.Headers[S3Headers.BucketName] = response.BucketName; exchange.In.Headers[S3Headers.Key] = response.Key; exchange.In.Headers[S3Headers.ContentType] = response.Headers.ContentType; exchange.In.Headers[S3Headers.ContentLength] = response.ContentLength; exchange.In.Headers[S3Headers.ETag] = response.ETag; exchange.In.Headers[S3Headers.LastModified] = response.LastModified; exchange.In.Headers[S3Headers.VersionId] = response.VersionId; exchange.In.Headers[S3Headers.StorageClass] = response.StorageClass?.Value; exchange.In.Headers[S3Headers.ServerSideEncryption] = response.ServerSideEncryptionMethod?.Value; // User metadata foreach (var meta in response.Metadata.Keys) exchange.In.Headers[$"{S3Headers.MetadataPrefix}{meta}"] = response.Metadata[meta]; } private async Task EnsureBucketExistsAsync(string bucket, CancellationToken ct) { try { await _client!.EnsureBucketExistsAsync(bucket).ConfigureAwait(false); } catch (AmazonS3Exception ex) when (ex.StatusCode == HttpStatusCode.Conflict) { // Bucket already exists (race condition) — ignore } } private static async Task ReadExactAsync(Stream stream, byte[] buffer, CancellationToken ct) { int totalRead = 0; while (totalRead < buffer.Length) { var read = await stream.ReadAsync(buffer, totalRead, buffer.Length - totalRead, ct).ConfigureAwait(false); if (read == 0) break; totalRead += read; } return totalRead; } } /// /// Lightweight object info DTO for ListObjects results. /// public sealed class S3ObjectInfo { /// Object key. public string Key { get; set; } = ""; /// Object size in bytes. public long Size { get; set; } /// Last modified timestamp. public DateTime LastModified { get; set; } /// ETag of the object. public string ETag { get; set; } = ""; /// Storage class. public string? StorageClass { get; set; } } Path: redb-route/redb.Route.S3/redb.Route.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/redb.Route.S3/redb.Route.S3.csproj ---- redb.Route.S3 S3/MinIO transport for redb.Route ESB framework. Polling consumer with prefix filtering, idempotency, move-after-read; multi-operation producer with multipart upload, SSE, presigned URLs, tagging, versioning, and ACL management. Compatible with AWS S3 and MinIO via ForcePathStyle. esb;messaging;s3;minio;aws;object-storage;redb README.md