### Async-std Runtime Setup Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Example of setting up the async-std runtime for asynchronous operations. ```Rust #[async_std::main] async fn main() -> Result<(), S3Error> { // ... async operations ... Ok(()) } ``` -------------------------------- ### Run Minio Example Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Execute the example configured for Minio. Requires AWS credentials. ```bash cargo run --example minio ``` -------------------------------- ### Run Sync Example Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Execute the synchronous example with specific features. Requires AWS credentials. ```bash cargo run --example sync --no-default-features --features sync-native-tls ``` -------------------------------- ### Tokio Runtime Setup Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Example of setting up the Tokio runtime for asynchronous operations. ```Rust #[tokio::main] async fn main() -> Result<(), S3Error> { // ... async operations ... Ok(()) } ``` -------------------------------- ### Synchronous (Blocking) Setup Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Example of setting up a synchronous (blocking) client for operations. ```Rust use rust_s3::sync_client::S3Client; let client = S3Client::new(Region::UsEast1)?; // ... blocking operations ... ``` -------------------------------- ### Run R2 Example Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Execute the example configured for Cloudflare R2. Requires AWS credentials. ```bash cargo run --example r2 ``` -------------------------------- ### Run Google Cloud Example Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Execute the example configured for Google Cloud Storage. Requires AWS credentials. ```bash cargo run --example google-cloud ``` -------------------------------- ### Run Tokio Example Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Execute the example that uses the Tokio runtime. Requires AWS credentials. ```bash cargo run --example tokio ``` -------------------------------- ### Run rust-s3 Examples Source: https://github.com/durch/rust-s3/blob/master/s3/README.md Examples can be run using cargo. Specify the desired runtime and features as needed. ```bash # tokio, default cargo run --example tokio # async-std cargo run --example async-std --no-default-features --features async-std-native-tls # sync cargo run --example sync --no-default-features --features sync-native-tls # minio cargo run --example minio # r2 cargo run --example r2 # google cloud cargo run --example google-cloud ``` -------------------------------- ### Run Async-std Example Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Execute the example using async-std runtime with specific features. Requires AWS credentials. ```bash cargo run --example async-std --no-default-features --features async-std-native-tls ``` -------------------------------- ### Bucket Constructor Examples Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Demonstrates how to create new bucket instances, including public access configurations. ```Rust let bucket = Bucket::new("my-bucket", Region::UsEast1)?; let public_bucket = Bucket::new_public("my-public-bucket", Region::UsWest2)?; ``` -------------------------------- ### Pure Sync (No Runtime) Setup for Rust S3 Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md For environments without an async runtime, use the pure synchronous setup. This requires the 'sync' and 'native-tls' features for rust-s3, enabling direct use of synchronous methods. ```rust fn main() -> Result<(), Box> { let credentials = Credentials::default()?; let region: Region = "us-east-1".parse()?; let bucket = Bucket::new("my-bucket", region, credentials)?; // These are synchronous (no async/await needed) bucket.put_object("file.txt", b"content")?; Ok(()) } ``` ```toml [dependencies] rust-s3 = { version = "0.37.2", default-features = false, features = ["sync", "native-tls"] } ``` -------------------------------- ### Wasabi Bucket Initialization Source: https://github.com/durch/rust-s3/blob/master/_autodocs/credentials-and-regions.md Example of creating a bucket for Wasabi storage. Use the appropriate Wasabi region identifier. ```rust let bucket = Bucket::new( "my-bucket", Region::WaUsEast1, Credentials::default()? )?; ``` -------------------------------- ### DigitalOcean Spaces Bucket Initialization Source: https://github.com/durch/rust-s3/blob/master/_autodocs/credentials-and-regions.md Example of creating a bucket for DigitalOcean Spaces. Ensure you have the correct region identifier and default credentials. ```rust let bucket = Bucket::new( "my-space", Region::DoNyc3, Credentials::default()? )?; ``` -------------------------------- ### Minimal Synchronous Setup Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md A minimal configuration for synchronous operations using attohttpc and native TLS. Explicitly disables default features. ```toml # Minimal sync setup [dependencies] rust-s3 = { version = "0.37.2", default-features = false, features = ["sync", "native-tls"] } ``` -------------------------------- ### Rust Function Signature Example Source: https://github.com/durch/rust-s3/blob/master/_autodocs/README.md An example of a Rust function signature as per the project's documentation conventions. It includes the full signature, parameter types, and return type. ```rust pub fn put_object>( &self, path: S, content: &[u8] ) -> Result ``` -------------------------------- ### Example: Display Region Source: https://github.com/durch/rust-s3/blob/master/_autodocs/credentials-and-regions.md Demonstrates how to print the string representation of a Region variant. ```rust let region = Region::UsEast1; println!("{}", region); // Prints: "us-east-1" ``` -------------------------------- ### Tokio Runtime Setup for Rust S3 Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md Use this setup when your project is already using or can use the Tokio runtime. Ensure Tokio is added as a dependency with the 'macros' and 'rt' features. ```rust #[tokio::main] async fn main() -> Result<(), Box> { let credentials = Credentials::default()?; let region: Region = "us-east-1".parse()?; let bucket = Bucket::new("my-bucket", region, credentials)?; bucket.put_object("file.txt", b"content").await?; Ok(()) } ``` ```toml [dependencies] tokio = { version = "1", features = ["macros", "rt"] } rust-s3 = "0.37.2" # Already depends on tokio ``` -------------------------------- ### Manual S3 Request Signing Example Source: https://github.com/durch/rust-s3/blob/master/_autodocs/signing-and-core-traits.md Demonstrates how to manually construct and sign an S3 request for advanced use cases. Requires setting up AWS credentials, region, and current time. ```rust use s3::signing::*; use time::OffsetDateTime; use std::str::FromStr; #[tokio::main] async fn manual_signing() -> Result<(), Box> { let secret_key = "my-secret-key"; let region: Region = "us-east-1".parse()?; let now = OffsetDateTime::now_utc(); // Build canonical request let canonical_uri = canonical_uri_string(&url)?; let canonical_qs = canonical_query_string(&url)?; let canonical_hdrs = canonical_header_string(&headers)?; let signed_hdrs = signed_header_string(&headers); let payload_hash = "sha256_hash_of_body"; let canonical = canonical_request( "PUT", &canonical_uri, &canonical_qs, &canonical_hdrs, &signed_hdrs, payload_hash, ); // Create string to sign let scope = scope_string(&now, ®ion)?; let string_to_sign = string_to_sign(&now, &scope, &canonical)?; // Derive signing key and sign let signing_key = signing_key(&now, secret_key, ®ion, "s3")?; let mut hmac = HmacSha256::new_from_slice(&signing_key)?; hmac.update(string_to_sign.as_bytes()); let signature = hex::encode(hmac.finalize().into_bytes()); // Create authorization header let auth_header = authorization_header(&scope, &signed_hdrs, &signature); println!("Authorization: {}", auth_header); Ok(()) } ``` -------------------------------- ### Cloudflare R2 Bucket Initialization Source: https://github.com/durch/rust-s3/blob/master/_autodocs/credentials-and-regions.md Example of creating a bucket for Cloudflare R2. Requires your Cloudflare account ID and specifies global or EU region. ```rust let region = Region::R2 { account_id: "abc123def456".to_string(), }; let bucket = Bucket::new( "my-bucket", region, Credentials::default()? )?; ``` -------------------------------- ### PostPolicyExpiration Enum Usage Examples Source: https://github.com/durch/rust-s3/blob/master/_autodocs/post-policy-api.md Demonstrates creating PostPolicyExpiration values. Examples show setting a policy to expire after a specific duration and setting an absolute expiration timestamp. ```rust use s3::post_policy::PostPolicyExpiration; use std::time::Duration; use time::OffsetDateTime; // Valid for 1 hour let exp1 = PostPolicyExpiration::Duration(Duration::from_secs(3600)); // Valid until specific time let exp2 = PostPolicyExpiration::Timestamp( OffsetDateTime::now_utc() + time::Duration::hours(2) ); ``` -------------------------------- ### PostPolicyValue Enum Usage Examples Source: https://github.com/durch/rust-s3/blob/master/_autodocs/post-policy-api.md Illustrates how to use the PostPolicyValue enum variants for different policy conditions. Examples cover exact matches, prefix matching, size ranges, and allowing any value. ```rust use s3::post_policy::PostPolicyValue; // Exact value PostPolicyValue::Exact("public-read".into()) // Prefix constraint PostPolicyValue::StartsWith("image/".into()) // Size range: 1 byte to 100 MB PostPolicyValue::Range(1, 104_857_600) // Allow any value for this field PostPolicyValue::Anything ``` -------------------------------- ### Async-Std Runtime Setup for Rust S3 Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md This configuration is suitable for projects utilizing the async-std runtime. Include async-std with the 'attributes' feature and rust-s3 with 'with-async-std' and 'native-tls' features. ```rust #[async_std::main] async fn main() -> Result<(), Box> { let credentials = Credentials::default()?; let region: Region = "us-east-1".parse()?; let bucket = Bucket::new("my-bucket", region, credentials)?; bucket.put_object("file.txt", b"content").await?; Ok(()) } ``` ```toml [dependencies] async-std = { version = "1", features = ["attributes"] } rust-s3 = { version = "0.37.2", default-features = false, features = ["with-async-std", "native-tls"] } ``` -------------------------------- ### Limit Upload File Size Source: https://github.com/durch/rust-s3/blob/master/_autodocs/post-policy-api.md This example shows how to set a range for the upload file size, from a minimum of 1 KB to a maximum of 50 MB. This prevents excessively large or small files from being uploaded. ```rust let policy = PostPolicy::new(PostPolicyExpiration::Duration(Duration::from_secs(3600))) .condition( PostPolicyField::ContentLength, PostPolicyValue::Range(1024, 52_428_800) // 1 KB to 50 MB )?; ``` -------------------------------- ### Region Parsing Example Source: https://github.com/durch/rust-s3/blob/master/_autodocs/types.md Demonstrates parsing a standard AWS region string into the Region enum and creating a custom Region variant for a local endpoint. ```rust let region: Region = "us-east-1".parse()?; let custom = Region::Custom { region: "minio-local".to_string(), endpoint: "http://localhost:9000".to_string(), }; ``` -------------------------------- ### Presigned URL Generation Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt The `bucket.md` and `post-policy-api.md` files describe methods for generating presigned URLs for various operations, including GET, PUT, DELETE, and POST. The `post-policy-api.md` specifically details the `PostPolicy` struct and its builder pattern for creating presigned POST requests. ```APIDOC ## Presigned URL Operations ### Description This section covers the functionality for generating presigned URLs, which allow temporary access to S3 objects without requiring AWS credentials. This includes generating URLs for direct object retrieval, upload, deletion, and for form-based uploads using POST policies. ### Methods - **Bucket Presigned URLs**: `Bucket::presign_get()`, `Bucket::presign_put()`, `Bucket::presign_delete()`, `Bucket::presign_post()` - **PostPolicy API**: `PostPolicy::new()`, `PostPolicy::condition()`, `PostPolicy::sign()` ### Parameters - **`Bucket::presign_get(object_key, expires_in)`**: Generates a presigned URL for GET requests. - **`Bucket::presign_put(object_key, expires_in)`**: Generates a presigned URL for PUT requests. - **`Bucket::presign_delete(object_key, expires_in)`**: Generates a presigned URL for DELETE requests. - **`Bucket::presign_post(object_key, expires_in)`**: Generates a presigned URL for POST requests. - **`PostPolicy` methods**: Various methods for defining conditions and signing policies for form-based uploads. ### Request Example (Presigned POST) ```html
``` ### Response Example (Presigned URL) `"https://your-bucket.s3.amazonaws.com/your-object?AWSAccessKeyId=YOUR_ACCESS_KEY&Expires=1678886400&Signature=YOUR_SIGNATURE"` ``` -------------------------------- ### Create a Restrictive Post Policy Source: https://github.com/durch/rust-s3/blob/master/_autodocs/post-policy-api.md Example of creating a restrictive POST policy with conditions on key, content type, content length, and ACL. This helps prevent malicious uploads. ```rust let policy = PostPolicy::new(PostPolicyExpiration::Duration(Duration::from_secs(900))) // 15 min .condition( PostPolicyField::Key, PostPolicyValue::Exact(Cow::from("profiles/avatar-" + &user_id)) )? .condition( PostPolicyField::ContentType, PostPolicyValue::Exact(Cow::from("image/jpeg")) )? .condition( PostPolicyField::ContentLength, PostPolicyValue::Range(1024, 5_242_880) // 1 KB to 5 MB )? .condition( PostPolicyField::Acl, PostPolicyValue::Exact(Cow::from("private")) )?; ``` -------------------------------- ### Default rust-s3 Dependency Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md Includes fail-on-err, tags, and tokio-native-tls by default. Use this for a standard async setup with native TLS. ```toml [dependencies] rust-s3 = "0.37.2" # Includes: fail-on-err, tags, tokio-native-tls ``` -------------------------------- ### Synchronous (Blocking) Setup for Rust S3 Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md Enable the 'blocking' feature for synchronous execution. This provides `*_blocking` variants for async methods, allowing direct use without an explicit async runtime. Requires the 'sync' and 'blocking' features for rust-s3. ```rust fn main() -> Result<(), Box> { let credentials = Credentials::default()?; let region: Region = "us-east-1".parse()?; let bucket = Bucket::new("my-bucket", region, credentials)?; // Use blocking variant bucket.put_object_blocking("file.txt", b"content")?; Ok(()) } ``` ```toml [dependencies] rust-s3 = { version = "0.37.2", default-features = false, features = ["sync", "native-tls", "blocking"] } ``` -------------------------------- ### Error Handling Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt The `errors.md` file provides a comprehensive guide to error handling within the Rust-S3 library. It details the `S3Error` enum, error catalog, HTTP status code mapping, and various error handling patterns with code examples. ```APIDOC ## Error Handling ### Description This section outlines the error handling mechanisms provided by the Rust-S3 library. It covers the comprehensive `S3Error` enum, common error scenarios, HTTP status code mappings, and strategies for managing and recovering from errors. ### Error Types - **`S3Error` Enum**: Contains over 30 distinct error variants, covering a wide range of potential issues. - **Error Catalog**: Details trigger conditions and locations for various errors. - **HTTP Status Code Mapping**: Maps S3 errors to corresponding HTTP status codes (e.g., 200, 403, 404, 400, 409, 503). - **Specific Errors**: Includes errors related to credential locking, serialization/parsing, and feature-specific issues (tokio, async-std, sync). ### Error Handling Patterns - **Automatic Retry Behavior**: The library includes built-in retry logic for transient errors. - **4 Error Handling Patterns**: The documentation provides examples for different approaches to handling errors, including: - Basic error checking - Using `Result` and `?` operator - Custom error mapping - Implementing retry logic manually ### Code Examples Code examples demonstrating these error handling patterns are available in the `errors.md` reference. ``` -------------------------------- ### Generate Presigned GET URL Source: https://github.com/durch/rust-s3/blob/master/_autodocs/README.md Generates a presigned URL for GET requests to an object, valid for a specified duration. ```rust let url = bucket.presign_get("key", 3600).await?; ``` -------------------------------- ### Create Bucket with Configuration Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md Use `BucketConfiguration` to specify ACL, object lock, and region when creating a new bucket. Ensure `credentials` and `Region` are correctly provided. ```rust use s3::bucket_ops::{BucketConfiguration, CannedBucketAcl}; let config = BucketConfiguration { acl: Some(CannedBucketAcl::Private), object_lock_enabled: false, location_constraint: Some(Region::EuWest1), ..Default::default() }; let response = Bucket::create( "new-bucket-name", Region::EuWest1, credentials, config ).await?; ``` -------------------------------- ### Constraining Content Type in POST Policy Source: https://github.com/durch/rust-s3/blob/master/_autodocs/post-policy-api.md Example demonstrating how to set a condition on the 'ContentType' field using the PostPolicyField enum and PostPolicyValue. This specific example allows uploads of any image type. ```rust use s3::post_policy::{PostPolicyField, PostPolicyValue}; use std::borrow::Cow; let condition = policy.condition( PostPolicyField::ContentType, PostPolicyValue::StartsWith(Cow::from("image/")) )?; ``` -------------------------------- ### HTTP Client Configuration (Proxy) Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Sets up an HTTP proxy for all client requests. ```Rust let bucket = Bucket::builder() .proxy("http://proxy.example.com:8080") .build("my-bucket", Region::UsEast1)?; ``` -------------------------------- ### Run CI Tests Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Execute the Continuous Integration tests, which is the recommended first step for development. ```bash make ci ``` -------------------------------- ### Get Bucket Tagging Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Retrieves tags associated with a bucket. ```Rust let tags = bucket.get_tags("my-bucket").await?; ``` -------------------------------- ### Get Bucket Location Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Retrieves the region where a bucket is located. ```Rust let location = bucket.location("my-bucket").await?; ``` -------------------------------- ### Download a File (Basic) Source: https://github.com/durch/rust-s3/blob/master/_autodocs/INDEX.md Downloads a file and retrieves its content as bytes. Ensure the file exists in the bucket. ```rust let response = bucket.get_object("file.txt").await?; let content = response.bytes(); ``` -------------------------------- ### GET Object Operations Source: https://github.com/durch/rust-s3/blob/master/README.md Methods for retrieving objects from an S3 bucket. ```APIDOC ## GET Object ### Description Retrieves an object from an S3 bucket. Supports synchronous, asynchronous, and asynchronous-blocking variants. These methods are generic over `std::io::Write` for sync/async and `tokio::io::AsyncWriteExt` for tokio variants. ### Method GET ### Endpoint [get_object](https://docs.rs/rust-s3/latest/s3/bucket/struct.Bucket.html#method.get_object) ``` ```APIDOC ## GET Object Stream ### Description Retrieves an object from an S3 bucket as a stream. Supports synchronous, asynchronous, and asynchronous-blocking variants. ### Method GET ### Endpoint [get_object_stream](https://docs.rs/rust-s3/latest/s3/bucket/struct.Bucket.html#method.get_object_stream) ``` ```APIDOC ## GET Object to Writer ### Description Retrieves an object from an S3 bucket and writes it directly to a writer. Supports synchronous, asynchronous, and asynchronous-blocking variants. ### Method GET ### Endpoint [get_object_to_writer](https://docs.rs/rust-s3/latest/s3/bucket/struct.Bucket.html#method.get_object_to_writer) ``` -------------------------------- ### Test Tokio Runtime Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Navigate to the 's3' directory and test the implementation using the Tokio runtime. ```bash cd s3 make tokio ``` -------------------------------- ### Create Bucket Instance Source: https://github.com/durch/rust-s3/blob/master/_autodocs/README.md Creates a new Bucket instance. Requires a bucket name, region, and credentials. ```rust let bucket = Bucket::new("name", region, credentials)?; ``` -------------------------------- ### HTML Form for Presigned POST Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Example of an HTML form that can be used with a presigned POST policy. ```html
``` -------------------------------- ### Object Get Operation Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Retrieves an object from an S3 bucket. Requires a configured bucket instance. ```Rust let object_data = bucket.get("my-object.txt").await?; ``` -------------------------------- ### Test Async-std Runtime Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Navigate to the 's3' directory and test the implementation using the async-std runtime. ```bash cd s3 make async-std ``` -------------------------------- ### Runtime and HTTP Configuration Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt The `configuration.md` file explains how to configure the Rust-S3 client's runtime, TLS options, and HTTP client settings. It covers feature selection for different runtimes (tokio, async-std, sync), TLS backends, and various HTTP client customizations. ```APIDOC ## Runtime and HTTP Configuration ### Description This section details the configuration options for the Rust-S3 client's runtime environment, TLS settings, and underlying HTTP client. It allows for customization to suit different application requirements and environments. ### Runtime Feature Selection - **Runtimes**: Support for `tokio`, `async-std`, and synchronous (blocking) execution. - **Feature Combinations**: Examples and explanations for combining different features. - **Runtime Setup**: Specific instructions for setting up the Tokio and Async-std runtimes, as well as pure synchronous setup. ### TLS Options - **TLS Backends**: `native-tls`, `rustls`, `vendored`. ### HTTP Client Configuration - **Global Retry Configuration**: Setting default retry behavior. - **HTTP Client Configuration**: Customizing the underlying HTTP client. - **Proxy Setup**: Configuring proxy settings. - **Bucket Configuration**: Specific settings per bucket, including `timeout`, `headers`, `query`, and `style` (path vs. subdomain). - **ListObjects Version**: Selecting between v1 and v2. - **Multipart Upload Configuration**: Settings for multipart uploads. - **POST Policy Configuration**: Options related to presigned POST policies. - **Content Type Defaults**: Default content type handling. - **Async vs. Blocking vs. Sync Patterns**: Guidance on choosing the appropriate execution pattern. ``` -------------------------------- ### Get Object Metadata Source: https://github.com/durch/rust-s3/blob/master/_autodocs/README.md Retrieves metadata for an object in an S3 bucket without downloading the object content. ```rust let meta = bucket.head_object("key").await?; ``` -------------------------------- ### BucketConfiguration Methods Source: https://github.com/durch/rust-s3/blob/master/_autodocs/types.md Provides methods for creating and configuring a `BucketConfiguration`. Use `new` for basic creation and `with_region` to specify the bucket's region. ```rust pub fn new(region: Option) -> Self> pub fn with_region(mut self, region: Region) -> Self> ``` -------------------------------- ### Get Bucket Location Source: https://github.com/durch/rust-s3/blob/master/s3/README.md Retrieves the region where the S3 bucket is located. Supports synchronous, asynchronous, and asynchronous-blocking modes. ```APIDOC ## Get Bucket Location ### Description Retrieves the region where the S3 bucket is located. This method is available in synchronous, asynchronous, and asynchronous-blocking variants. ### Method GET ### Endpoint `/location` ### Parameters *Path Parameters* None *Query Parameters* None *Request Body* None ### Request Example ```json { "example": "GET request to retrieve bucket location" } ``` ### Response #### Success Response (200) - **location** (string) - The region of the S3 bucket (e.g., "us-east-1"). #### Response Example ```json { "example": "us-west-2" } ``` ``` -------------------------------- ### Bucket::new Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Creates a new S3 bucket instance using subdomain-style URL format. Requires bucket name, AWS region, and credentials. ```APIDOC ## Bucket::new ### Description Creates a new bucket instance with the specified name, region, and credentials using subdomain-style URL format. ### Parameters #### Path Parameters - **name** (string) - Required - Name of the S3 bucket - **region** (Region) - Required - AWS region where the bucket resides - **credentials** (Credentials) - Required - AWS credentials (access key, secret key, optional token) ### Request Example ```rust use s3::bucket::Bucket; use s3::creds::Credentials; use s3::region::Region; let bucket_name = "my-bucket"; let region: Region = "us-east-1".parse()?; let credentials = Credentials::default()?; let bucket = Bucket::new(bucket_name, region, credentials)?; ``` ### Response #### Success Response - **Bucket** - A configured Bucket instance - **S3Error** - An error if instantiation fails ``` -------------------------------- ### Test Sync Native TLS Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Navigate to the 's3' directory and test the synchronous implementation with native TLS. ```bash cd s3 make sync-nativetls ``` -------------------------------- ### Create Bucket with LocalStack Configuration Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md Instantiate a `Bucket` for use with LocalStack by specifying a custom region with the LocalStack endpoint and providing test credentials. ```rust use s3::region::Region; let region = Region::Custom { region: "us-east-1".to_string(), endpoint: "http://localhost:4566".to_string(), }; let credentials = Credentials::new( Some("test"), Some("test"), None, None, None )?; let bucket = Bucket::new("test-bucket", region, credentials)?; ``` -------------------------------- ### Get Object by Byte Range Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Retrieves a specific range of bytes from an object. Useful for partial reads or when only a segment of a file is needed. ```rust let range_response = bucket.get_object_range("file.bin", 0, Some(1023)).await?; ``` -------------------------------- ### Upload a File (Basic) Source: https://github.com/durch/rust-s3/blob/master/_autodocs/INDEX.md Uploads a file with basic content. Ensure the bucket object is available. ```rust bucket.put_object("file.txt", b"content").await?; ``` -------------------------------- ### Generate Basic Presigned POST Policy Source: https://github.com/durch/rust-s3/blob/master/_autodocs/post-policy-api.md Use this snippet to create a presigned POST policy with a specific key and content length constraint. Ensure you have the necessary bucket, region, and credentials configured. ```rust use s3::post_policy::{PostPolicy, PostPolicyExpiration, PostPolicyField, PostPolicyValue}; use std::time::Duration; use std::borrow::Cow; #[tokio::main] async fn main() -> Result<(), Box> { let bucket = Bucket::new("my-bucket", region, credentials)?; let policy = PostPolicy::new( PostPolicyExpiration::Duration(Duration::from_secs(3600)) ) .condition( PostPolicyField::Key, PostPolicyValue::Exact(Cow::from("uploads/document.pdf")) )? .condition( PostPolicyField::ContentLength, PostPolicyValue::Range(1, 10_485_760) // 1 byte to 10 MB )? .condition( PostPolicyField::Acl, PostPolicyValue::Exact(Cow::from("private")) )?; let presigned = policy.sign(Box::new(bucket)).await?; println!("Form URL: {}", presigned.url); println!("Fields:"); for (k, v) in &presigned.fields { println!(" {} = {}", k, v); } Ok(()) } ``` -------------------------------- ### Object Tagging Operations Source: https://github.com/durch/rust-s3/blob/master/s3/README.md Provides methods to manage tags associated with S3 objects. Supports putting and getting object tags. ```APIDOC ## PUT Object Tagging ### Description Applies or replaces tags on an S3 object. This method is available in synchronous, asynchronous, and asynchronous-blocking variants. ### Method PUT ### Endpoint `/objects/{object_key}/tagging` ### Parameters *Path Parameters* - **object_key** (string) - Required - The key of the object to tag. *Query Parameters* None *Request Body* - **tags** (object) - Required - A key-value map of tags to apply. - **tag_key** (string) - The key of the tag. - **tag_value** (string) - The value of the tag. ### Request Example ```json { "example": { "tags": { "environment": "production", "version": "1.0" } } } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the tagging operation was successful. #### Response Example ```json { "example": true } ``` ``` ```APIDOC ## GET Object Tagging ### Description Retrieves the tags associated with an S3 object. This method is available in synchronous, asynchronous, and asynchronous-blocking variants. ### Method GET ### Endpoint `/objects/{object_key}/tagging` ### Parameters *Path Parameters* - **object_key** (string) - Required - The key of the object whose tags to retrieve. *Query Parameters* None *Request Body* None ### Request Example ```json { "example": "GET request to retrieve object tags" } ``` ### Response #### Success Response (200) - **tags** (object) - A key-value map of tags associated with the object. - **tag_key** (string) - The key of the tag. - **tag_value** (string) - The value of the tag. #### Response Example ```json { "example": { "environment": "production", "version": "1.0" } } ``` ``` -------------------------------- ### Bucket Configuration (Path Style) Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Enables path-style access for buckets, often required by S3-compatible storage. ```Rust let bucket = Bucket::builder() .path_style() .build("my-bucket", Region::UsEast1)?; ``` -------------------------------- ### URI Encoding Example Source: https://github.com/durch/rust-s3/blob/master/_autodocs/signing-and-core-traits.md Encodes a URI string according to AWS-specific rules. Use `encode_slash` to control whether forward slashes are percent-encoded. ```rust let encoded = uri_encode("my key/file.txt", false); // Result: "my%20key/file.txt" let encoded = uri_encode("my key/file.txt", true); // Result: "my%20key%2Ffile.txt" ``` -------------------------------- ### Post Policy Builder (Basic) Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Creates a basic POST policy for form uploads. ```Rust use rust_s3::presigned_post::{PostPolicy, PostPolicyField, PostPolicyValue, PostPolicyExpiration}; let policy = PostPolicy::new(Region::UsEast1, Duration::from_secs(3600)) .field(PostPolicyField::ContentLengthRange(0, 10_000_000)) .sign("my-bucket", "my-object.txt")?; ``` -------------------------------- ### List Buckets Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Lists all buckets accessible by the configured credentials. ```Rust let buckets = bucket.list_buckets().await?; ``` -------------------------------- ### Basic Credentials Usage Source: https://github.com/durch/rust-s3/blob/master/_autodocs/credentials-and-regions.md Loads default credentials from environment variables or configuration files and creates a new S3 bucket instance. Credentials are automatically refreshed. ```rust use s3::bucket::Bucket; use s3::creds::Credentials; use s3::region::Region; #[tokio::main] async fn main() -> Result<(), Box> { // Load credentials from environment/config let credentials = Credentials::default()?; let region: Region = "us-east-1".parse()?; let bucket = Bucket::new("my-bucket", region, credentials)?; // Credentials are automatically refreshed as needed bucket.put_object("file.txt", b"Hello").await?; Ok(()) } ``` -------------------------------- ### Get Mutable Bucket Extra Headers Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Returns a mutable reference to the bucket's extra headers map. Use this to modify headers directly. ```rust pub fn extra_headers_mut(&mut self) -> &mut HeaderMap ``` -------------------------------- ### Working with S3-Compatible Services Source: https://github.com/durch/rust-s3/blob/master/_autodocs/credentials-and-regions.md Configures custom regions for S3-compatible services like MinIO, Backblaze B2, and Google Cloud Storage by specifying their endpoints. ```rust // MinIO local instance let minio = Region::Custom { region: "minio-local".to_string(), endpoint: "http://localhost:9000".to_string(), }; let bucket = Bucket::new("my-bucket", minio, credentials)?; // Backblaze B2 let b2 = Region::Custom { region: "us-west-001".to_string(), endpoint: "https://s3.us-west-001.backblazeb2.com".to_string(), }; // Google Cloud Storage let gcs = Region::Custom { region: "us-central1".to_string(), endpoint: "https://storage.googleapis.com".to_string(), }; // Wasabi (simpler: use predefined region) let wasabi = Region::WaUsEast1; ``` -------------------------------- ### Get Object Stream Reader Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Obtains a stream reader for an object, enabling consumption of its content in chunks. Ideal for processing large objects efficiently. ```rust let mut stream = bucket.get_object_stream("large-file.bin").await?; // Consume stream in chunks ``` -------------------------------- ### Format Code Source: https://github.com/durch/rust-s3/blob/master/CLAUDE.md Apply code formatting rules to the project. ```bash make fmt ``` -------------------------------- ### Get Object Content Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Retrieves an object's entire content as bytes. Use this for smaller objects where loading the full content into memory is acceptable. ```rust let response = bucket.get_object("path/to/file.txt").await?; println!("Status: {}", response.status_code()); println!("Content: {:?}", response.bytes()); ``` -------------------------------- ### Create a new Bucket instance with credentials Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Use `Bucket::new` to create a bucket instance when you have AWS credentials. This is the standard way to interact with private or authenticated S3 buckets. ```rust use s3::bucket::Bucket; use s3::creds::Credentials; use s3::region::Region; let bucket_name = "my-bucket"; let region: Region = "us-east-1".parse()?; let credentials = Credentials::default()?; let bucket = Bucket::new(bucket_name, region, credentials)?; ``` -------------------------------- ### Get Immutable Bucket Extra Headers Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Returns an immutable reference to the bucket's extra headers map. Use this to inspect headers without modifying them. ```rust pub fn extra_headers(&self) -> &HeaderMap ``` -------------------------------- ### List All Objects with Prefix Source: https://github.com/durch/rust-s3/blob/master/_autodocs/INDEX.md Lists all objects in a bucket that match a given prefix. Iterates through paginated results. ```rust let results = bucket.list("prefix".to_string(), None).await?; for result in results { for obj in result.contents { println!("{}", obj.key); } } ``` -------------------------------- ### Get Detailed Object Attributes with get_object_attributes Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Retrieves detailed attributes of an object, including checksums and multipart information. Use this for in-depth object property inspection. ```rust pub async fn get_object_attributes>( &self, path: S ) -> Result ``` -------------------------------- ### PostPolicy Methods Source: https://github.com/durch/rust-s3/blob/master/_autodocs/types.md Provides methods for creating, configuring, and signing a POST policy for presigned uploads. ```rust pub fn new>(expiration: T) -> Self ``` ```rust pub fn condition( self, field: PostPolicyField, value: PostPolicyValue ) -> Result ``` ```rust pub async fn sign(self, bucket: Box) -> Result ``` -------------------------------- ### Configure and Get S3 Retries Source: https://github.com/durch/rust-s3/blob/master/_autodocs/errors.md Set the global retry count for all S3 operations or retrieve the current retry count. Retries are only performed on transient failures. ```rust s3::set_retries(3); let retries = s3::get_retries(); println!("Current retries: {}", retries); ``` -------------------------------- ### Create Bucket Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Creates a new bucket in the specified region. ```Rust bucket.create("new-bucket-name").await?; ``` -------------------------------- ### Enable Path-Style URLs for S3 Bucket Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Use this method to create a new bucket instance configured for path-style URLs. This is useful when subdomain-style URLs are not supported or preferred. ```rust pub fn with_path_style(&self) -> Box ``` ```rust let path_style_bucket = bucket.with_path_style(); // Uses URLs like: https://s3.amazonaws.com/my-bucket/file.txt ``` -------------------------------- ### Presign Operations Source: https://github.com/durch/rust-s3/blob/master/s3/README.md Provides methods to generate pre-signed URLs for various S3 operations (POST, PUT, GET, DELETE). These are useful for granting temporary access to S3 resources. ```APIDOC ## POST presign_post ### Description Generates a pre-signed URL for a POST request to an S3 object. ### Method POST ### Endpoint `/presign_post` ### Parameters *Path Parameters* None *Query Parameters* None *Request Body* None ### Request Example ```json { "example": "POST request details for presigning" } ``` ### Response #### Success Response (200) - **presigned_url** (string) - The generated pre-signed URL. #### Response Example ```json { "example": "https://your-bucket.s3.amazonaws.com/your-object?AWSAccessKeyId=...&Expires=...&Signature=..." } ``` ``` ```APIDOC ## PUT presign_put ### Description Generates a pre-signed URL for a PUT request to an S3 object. ### Method PUT ### Endpoint `/presign_put` ### Parameters *Path Parameters* None *Query Parameters* None *Request Body* None ### Request Example ```json { "example": "PUT request details for presigning" } ``` ### Response #### Success Response (200) - **presigned_url** (string) - The generated pre-signed URL. #### Response Example ```json { "example": "https://your-bucket.s3.amazonaws.com/your-object?AWSAccessKeyId=...&Expires=...&Signature=..." } ``` ``` ```APIDOC ## GET presign_get ### Description Generates a pre-signed URL for a GET request to an S3 object. ### Method GET ### Endpoint `/presign_get` ### Parameters *Path Parameters* None *Query Parameters* None *Request Body* None ### Request Example ```json { "example": "GET request details for presigning" } ``` ### Response #### Success Response (200) - **presigned_url** (string) - The generated pre-signed URL. #### Response Example ```json { "example": "https://your-bucket.s3.amazonaws.com/your-object?AWSAccessKeyId=...&Expires=...&Signature=..." } ``` ``` ```APIDOC ## DELETE presign_delete ### Description Generates a pre-signed URL for a DELETE request to an S3 object. ### Method DELETE ### Endpoint `/presign_delete` ### Parameters *Path Parameters* None *Query Parameters* None *Request Body* None ### Request Example ```json { "example": "DELETE request details for presigning" } ``` ### Response #### Success Response (200) - **presigned_url** (string) - The generated pre-signed URL. #### Response Example ```json { "example": "https://your-bucket.s3.amazonaws.com/your-object?AWSAccessKeyId=...&Expires=...&Signature=..." } ``` ``` -------------------------------- ### HTML Form for Presigned POST Upload Source: https://github.com/durch/rust-s3/blob/master/_autodocs/post-policy-api.md An example of an HTML form that uses the presigned POST policy details to enable client-side uploads to S3. It includes placeholders for dynamic fields that the client must populate. ```html
{% for key, value in presigned.fields %} {% endfor %} {% for key, value in presigned.dynamic_fields %} {% if key == "file" %} {% else %} {% endif %} {% endfor %}
``` -------------------------------- ### Synchronous Runtime Configuration Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md Sets up rust-s3 for synchronous, blocking operations using attohttpc. Disable default features to select specific sync capabilities. ```toml # Synchronous only [dependencies] rust-s3 = { version = "0.37.2", default-features = false, features = ["sync", "native-tls"] } ``` -------------------------------- ### S3 Credentials Configuration Recovery Source: https://github.com/durch/rust-s3/blob/master/_autodocs/errors.md Shows how to correctly configure S3 credentials. Ensure AWS environment variables or the credentials file are set up. ```rust // Ensure credentials are configured use s3::creds::Credentials; match Credentials::default() { Ok(creds) => { let bucket = Bucket::new("my-bucket", region, creds)?; // proceed } Err(e) => { eprintln!("Missing AWS credentials: {}", e); // Check AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY env vars // or ~/.aws/credentials file } } ``` -------------------------------- ### Configure Object Tags for S3 Bucket Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md Enables and uses object tags for an S3 bucket. Requires the `tags` feature, which is enabled by default in `rust-s3` version 0.37.2. Demonstrates putting and getting object tags. ```toml [dependencies] rust-s3 = "0.37.2" # tags enabled by default ``` ```rust use s3::bucket::Tag; let tags = vec![ Tag { key: "env".into(), value: "production".into() }, Tag { key: "app".into(), value: "web".into() }, ]; bucket.put_object_tagging("file.txt", &tags).await?; let retrieved = bucket.get_object_tagging("file.txt").await?; ``` -------------------------------- ### Bucket::initiate_multipart_upload Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Initiates a multipart upload for large objects, returning an upload ID. ```APIDOC ## Bucket::initiate_multipart_upload ### Description Initiates a multipart upload for large objects. ### Method Not specified (likely POST based on operation) ### Endpoint Not specified ### Parameters #### Path Parameters - **key** (string) - Required - Object key #### Query Parameters - **content_type** (string) - Required - MIME type ### Request Example ```rust let response = bucket.initiate_multipart_upload("large-file.bin", "application/octet-stream").await?; let upload_id = response.upload_id; ``` ### Response #### Success Response (200) - **InitiateMultipartUploadResponse** - Response containing upload ID ``` -------------------------------- ### Bucket::create Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Creates a new S3 bucket with the specified name, region, credentials, and configuration. ```APIDOC ## Bucket::create ### Description Creates a new S3 bucket. ### Method `create` ### Parameters #### Path Parameters - **name** (string) - Required - New bucket name - **region** (Region) - Required - Bucket region - **credentials** (Credentials) - Required - AWS credentials - **config** (BucketConfiguration) - Required - Bucket configuration ### Response #### Success Response - **CreateBucketResponse** - Creation response with status ### Example ```rust use s3::bucket_ops::BucketConfiguration; let config = BucketConfiguration::default(); let response = Bucket::create("new-bucket", region, creds, config).await?; if response.success() { println!("Bucket created!"); } ``` ``` -------------------------------- ### ClientOptions for Tokio Backend Source: https://github.com/durch/rust-s3/blob/master/_autodocs/signing-and-core-traits.md Configuration options for the Tokio backend's HTTP client. Allows customization of HTTP allowance and request timeouts. ```rust pub fn default() -> Self pub fn with_allow_http(mut self, allow_http: bool) -> Self pub fn with_timeout(mut self, timeout: Duration) -> Self ``` -------------------------------- ### Configure Proxy for HTTP Client Source: https://github.com/durch/rust-s3/blob/master/_autodocs/configuration.md Set up a proxy for S3 requests using `reqwest::Proxy`. This is applied to a specific bucket instance. ```rust use reqwest::Proxy; let bucket = Bucket::new("my-bucket", region, credentials)?; let proxy = Proxy::https("http://proxy.example.com:3128")?; let proxied_bucket = bucket.set_proxy(proxy)?; ``` -------------------------------- ### Handle S3 Errors (404, 403) Source: https://github.com/durch/rust-s3/blob/master/_autodocs/INDEX.md Demonstrates handling common S3 errors like 'Not Found' (404) and 'Access Denied' (403) using a match statement. ```rust match bucket.get_object("file.txt").await { Ok(response) => println!("Got file"), Err(S3Error::HttpFailWithBody(404, _)) => println!("Not found"), Err(S3Error::HttpFailWithBody(403, _)) => println!("Access denied"), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Credential Management (Default) Source: https://github.com/durch/rust-s3/blob/master/_autodocs/COMPLETION_SUMMARY.txt Creates default credentials, typically from environment variables or configuration files. ```Rust let credentials = Credentials::default()?; ``` -------------------------------- ### List Objects with Prefix and Delimiter Source: https://github.com/durch/rust-s3/blob/master/_autodocs/bucket.md Lists objects in the bucket, handling pagination automatically. Use this for a comprehensive listing filtered by a prefix and grouped by a delimiter. ```rust pub async fn list( &self, prefix: String, delimiter: Option ) -> Result, S3Error> ``` ```rust let results = bucket.list("logs/".to_string(), Some("/".to_string())).await?; for result in results { for obj in result.contents { println!("{}", obj.key); } } ``` -------------------------------- ### Upload a File with Custom Headers and Metadata Source: https://github.com/durch/rust-s3/blob/master/_autodocs/INDEX.md Uploads a file using a builder pattern to set custom headers like Cache-Control and metadata. ```rust bucket.put_object_builder("file.txt", b"content") .with_cache_control("max-age=3600")? .with_metadata("user-id", "123")? .execute() .await?; ```