### Manage OSS Buckets in Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Provides examples of common bucket operations using the ali-oss-rs SDK. This includes creating buckets with specific configurations and ACLs, listing buckets with filtering, retrieving bucket information and statistics, and deleting empty buckets. It showcases asynchronous usage with `tokio`. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::bucket::BucketOperations; use ali_oss_rs::bucket_common::{ PutBucketConfiguration, PutBucketOptions, ListBucketsOptions, ListObjectsOptionsBuilder, BucketAcl }; use ali_oss_rs::common::{StorageClass, DataRedundancyType}; use std::collections::HashMap; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); // Create a new bucket with configuration let config = PutBucketConfiguration { storage_class: Some(StorageClass::Standard), data_redundancy_type: Some(DataRedundancyType::LRS), }; let options = PutBucketOptions { acl: Some(BucketAcl::Private), resource_group_id: None, tags: HashMap::from([ ("environment".to_string(), "production".to_string()) ]) }; client.put_bucket("my-new-bucket", config, Some(options)).await?; // List all buckets with pagination let list_options = ListBucketsOptions { prefix: Some("my-".to_string()), max_keys: Some(10), ..Default::default() }; let result = client.list_buckets(Some(list_options)).await?; for bucket in result.buckets { println!("Bucket: {} ({})", bucket.name, bucket.storage_class); } // Get bucket information let info = client.get_bucket_info("my-bucket").await?; println!("Bucket ACL: {:?}", info.access_control_list); // Get bucket statistics let stats = client.get_bucket_stat("my-bucket").await?; println!("Total storage: {} bytes, Objects: {}", stats.storage, stats.object_count); // Get bucket location let location = client.get_bucket_location("my-bucket").await?; println!("Bucket location: {}", location); // List objects in bucket with prefix and delimiter let list_opts = ListObjectsOptionsBuilder::new() .prefix("documents/") .delimiter('/') .max_keys(100) .fetch_owner(true) .build(); let objects = client.list_objects("my-bucket", Some(list_opts)).await?; for obj in objects.contents { println!("Object: {} ({} bytes)", obj.key, obj.size); } // Delete bucket (must be empty) client.delete_bucket("my-empty-bucket").await?; Ok(()) } ``` -------------------------------- ### Restore Archive Objects with Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Provides examples of how to restore archived or cold archived objects to a readable state using the ali-oss-rs Rust SDK. It covers different restoration tiers and cleaning up restored copies. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::object::ObjectOperations; use ali_oss_rs::object_common::{RestoreObjectRequest, RestoreJobTier}; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; // Restore archive object (standard priority) let request = RestoreObjectRequest { days: 7, // Keep restored for 7 days tier: Some(RestoreJobTier::Standard), // 2-5 hours version_id: None, }; let result = client.restore_object(bucket, "archived/old-data.zip", request).await?; println!("Restore initiated: {:?}", result.object_restore_priority); // Restore with expedited priority (faster, higher cost) let request = RestoreObjectRequest { days: 1, tier: Some(RestoreJobTier::Expedited), // 1 hour for Archive, 12 hours for ColdArchive version_id: None, }; client.restore_object(bucket, "archived/urgent-file.zip", request).await?; // Clean restored object (remove restored copy) client.clean_restored_object(bucket, "archived/old-data.zip").await?; Ok(()) } ``` -------------------------------- ### Manage Ali OSS Objects with Rust SDK Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Demonstrates how to retrieve object metadata, check for object existence, copy objects within or between buckets, and delete single or multiple objects using the ali-oss-rs SDK. It includes examples for basic metadata retrieval, detailed head object information, copying with storage class and metadata changes, and batch deletion. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::object::ObjectOperations; use ali_oss_rs::object_common::{ GetObjectMetadataOptions, HeadObjectOptionsBuilder, CopyObjectOptionsBuilder, DeleteMultipleObjectsConfig }; use ali_oss_rs::common::StorageClass; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; // Check if object exists let exists = client.exists(bucket, "documents/report.pdf", None).await?; println!("Object exists: {}", exists); // Get basic object metadata let meta = client.get_object_metadata(bucket, "documents/report.pdf", None).await?; println!("Size: {} bytes, ETag: {}", meta.content_length, meta.etag); // Get detailed metadata with HeadObject let options = HeadObjectOptionsBuilder::new() .if_match("\"etag-value\"") .build(); let meta = client.head_object(bucket, "documents/report.pdf", Some(options)).await?; println!("Storage class: {:?}", meta.storage_class); println!("Last modified: {:?}", meta.last_modified); println!("Content MD5: {:?}", meta.content_md5); for (key, value) in &meta.metadata { println!("Custom metadata {}: {}", key, value); } // Copy object within same bucket client.copy_object( bucket, "source/file.txt", bucket, "destination/file.txt", None ).await?; // Copy with options (change storage class, add metadata) let options = CopyObjectOptionsBuilder::new() .storage_class(StorageClass::Archive) .metadata("x-oss-meta-copied", "true") .tag("backup", "true") .forbid_overwrite(false) .build(); client.copy_object( "source-bucket", "original.txt", "dest-bucket", "copy.txt", Some(options) ).await?; // Delete single object client.delete_object(bucket, "old-file.txt", None).await?; // Delete folder (must be empty) client.delete_folder(bucket, "empty-folder/").await?; // Delete multiple objects at once let keys = vec![ "file1.txt", "file2.txt", "folder/file3.txt", ]; let result = client.delete_multiple_objects( bucket, DeleteMultipleObjectsConfig::FromKeys(&keys) ).await?; println!("Deleted {} objects", result.items.len()); Ok(()) } ``` -------------------------------- ### Manage Object Tags with Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Demonstrates how to get, set, and delete key-value tags associated with objects in an OSS bucket using the ali-oss-rs Rust SDK. This is useful for organizing and managing objects. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::tagging::ObjectTagOperations; use std::collections::HashMap; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; let object_key = "documents/contract.pdf"; // Get existing tags let tags = client.get_object_tags(bucket, object_key, None).await?; for (key, value) in &tags { println!("Tag: {} = {}", key, value); } // Set new tags (replaces all existing tags) let new_tags = HashMap::from([ ("department".to_string(), "legal".to_string()), ("confidential".to_string(), "true".to_string()), ("retention-years".to_string(), "7".to_string()), ]); client.put_object_tags(bucket, object_key, new_tags, None).await?; // Delete all tags client.delete_object_tags(bucket, object_key, None).await?; Ok(()) } ``` -------------------------------- ### Presigned URL Operations Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Generate presigned URLs for temporary access to objects without requiring credentials. Supports both GET and PUT requests. ```APIDOC ## Presigned URL Operations ### Description Generate presigned URLs for temporary access to objects without requiring credentials. ### Method - `presign_url` (for GET requests) - `presign_raw_request` (for other methods like PUT) ### Endpoint - N/A (URLs are generated, not tied to a specific endpoint call in this context) ### Parameters #### For `presign_url` (GET) - **bucket** (string) - Required - The name of the bucket. - **object_key** (string) - Required - The key of the object. - **options** (PresignGetOptions) - Optional - Options for the presigned GET URL. - `expires_in` (u64) - Required - The duration in seconds for which the URL is valid. - `process` (string) - Optional - Specifies image processing parameters. #### For `presign_raw_request` (Other Methods) - **oss_request** (OssRequest) - Required - An `OssRequest` object detailing the request parameters. - `method` (RequestMethod) - Required - The HTTP method (e.g., `RequestMethod::Put`). - `bucket` (string) - Required - The name of the bucket. - `object` (string) - Required - The key of the object. - `headers` (HashMap) - Optional - Additional headers to include in the request. - `query_params` (HashMap) - Optional - Query parameters for the request. ### Request Example (Generating Download URL) ```rust use ali_oss_rs::presign_common::PresignGetOptionsBuilder; let options = PresignGetOptionsBuilder::new(3600) // Valid for 1 hour .process("style/thumbnail") // Optional: image processing .build(); let download_url = client.presign_url(bucket, object_key, options); ``` ### Request Example (Generating Upload URL) ```rust use ali_oss_rs::request::{OssRequest, RequestMethod}; let request = OssRequest::new() .method(RequestMethod::Put) .bucket(bucket) .object("uploads/new-file.txt") .add_header("content-type", "text/plain") .add_header("content-length", "1024"); let SignedOssRequest { url, headers } = client.presign_raw_request(request); ``` ### Response #### Success Response - **url** (string) - The generated presigned URL. - **headers** (HashMap) - Required headers that must be included when using the presigned URL (for `presign_raw_request`). #### Response Example (Upload URL) ```json { "url": "https://my-bucket.oss-cn-hangzhou.aliyuncs.com/uploads/new-file.txt?Expires=...&Signature=...", "headers": { "authorization": "OSS ...", "x-oss-date": "..." } } ``` ``` -------------------------------- ### Object Tagging Operations Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Manage key-value tags on objects for organization and lifecycle management. This includes getting, setting, and deleting tags. ```APIDOC ## Object Tagging Operations ### Description Manage key-value tags on objects for organization and lifecycle management. ### Method - GET: `get_object_tags` - PUT: `put_object_tags` - DELETE: `delete_object_tags` ### Endpoint - `/{bucket}/{object_key}` (for GET, PUT, DELETE operations on tags) ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket. - **object_key** (string) - Required - The key of the object. #### Query Parameters - **versionId** (string) - Optional - Specifies the object version ID. #### Request Body (for PUT) - **tags** (HashMap) - Required - A map of key-value tags to set on the object. This replaces all existing tags. ### Request Example (Setting Tags) ```rust use std::collections::HashMap; let new_tags = HashMap::from([ ("department".to_string(), "legal".to_string()), ("confidential".to_string(), "true".to_string()), ("retention-years".to_string(), "7".to_string()), ]); client.put_object_tags(bucket, object_key, new_tags, None).await?; ``` ### Response #### Success Response (200) - **tags** (HashMap) - A map of key-value tags associated with the object. #### Response Example (Getting Tags) ```json { "department": "legal", "confidential": "true", "retention-years": "7" } ``` ``` -------------------------------- ### Initialize Aliyun OSS Client and List Buckets in Rust Source: https://github.com/yuqiang-yuan/ali-oss-rs/blob/master/README.md Initializes an Aliyun OSS client from environment variables and lists all buckets associated with the account. It requires the `dotenvy` crate for loading environment variables and assumes specific keys are set in the `.env` file. The output displays the name and storage class of each bucket. ```rust dotenvy::dotenv().unwrap(); // `.env` file should contain the following keys // // ALI_ACCESS_KEY_ID=your_access_key_id // ALI_ACCESS_KEY_SECRET=your_access_key_secret // ALI_OSS_REGION=cn-beijing // ALI_OSS_ENDPOINT=oss-cn-beijing.aliyuncs.com let client = ali_oss_rs::Client::from_env(); let list_buckets_result = client.list_buckets(None).await?; list_buckets_result.buckets.iter().for_each(|b| println!("{}\t{}", b.name, b.storage_class)); Ok(()) ``` -------------------------------- ### Initialize Ali OSS Client in Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Demonstrates various methods to create an OSS client instance. This includes initialization from environment variables, explicit credentials, and using `ClientBuilder` for advanced configurations like STS tokens and custom HTTP clients. The client is essential for all subsequent interactions with the OSS service. ```rust use ali_oss_rs::{Client, ClientBuilder}; // Method 1: Create client from environment variables // Required env vars: ALI_ACCESS_KEY_ID, ALI_ACCESS_KEY_SECRET, ALI_OSS_ENDPOINT // Optional env var: ALI_OSS_REGION (inferred from endpoint if not set) let client = Client::from_env(); // Method 2: Create client with explicit credentials let client = Client::new( "your_access_key_id", "your_access_key_secret", "cn-beijing", "oss-cn-beijing.aliyuncs.com" ); // Method 3: Use ClientBuilder for advanced configuration let client = ClientBuilder::new( "your_access_key_id", "your_access_key_secret", "oss-cn-hangzhou.aliyuncs.com" ) .region("cn-hangzhou") .scheme("https") .sts_token("your_sts_token") // Optional: for STS token authentication .client(reqwest::Client::new()) // Optional: custom reqwest client .build() .expect("Failed to build client"); // Clone client to different region with same credentials let shanghai_client = client.clone_to("cn-shanghai", "oss-cn-shanghai.aliyuncs.com"); ``` -------------------------------- ### List Objects in a Bucket with Options in Rust Source: https://github.com/yuqiang-yuan/ali-oss-rs/blob/master/README.md Lists objects within a specified Aliyun OSS bucket using provided options such as prefix and delimiter. This function is asynchronous and requires a pre-initialized client. The output includes the key and size of each object found. ```rust let objects = client .list_objects( "example-bucket", Some( ListObjectsOptionsBuilder::default() .prefix("test/") .delimiter('/') .build() ) ).await?; objects.contents.iter().for_each(|o| println!("{}\t{}", o.key, o.size)); Ok(()) ``` -------------------------------- ### Create and Manage Symlinks with Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Shows how to create symbolic links (soft links) to objects and retrieve the target of a symlink using the ali-oss-rs Rust SDK. This allows for creating shortcuts to objects. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::symlink::ObjectSymlinkOperations; use ali_oss_rs::symlink_common::PutSymlinkOptionsBuilder; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; // Create symlink with metadata let options = PutSymlinkOptionsBuilder::new() .metadata("x-oss-meta-link-type", "shortcut") .build(); let result = client.put_symlink( bucket, "shortcuts/latest-report.pdf", // Symlink path "documents/2024/q4-report.pdf", // Target object Some(options) ).await?; println!("Symlink version: {:?}", result.version_id); // Get symlink target let target = client.get_symlink(bucket, "shortcuts/latest-report.pdf", None).await?; println!("Points to: {}", target); Ok(()) } ``` -------------------------------- ### Generate Presigned URLs with Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Illustrates how to generate presigned URLs for temporary access to objects using the ali-oss-rs Rust SDK. This includes URLs for downloading and for making authenticated upload requests. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::presign::SignedOssRequest; use ali_oss_rs::presign_common::PresignGetOptionsBuilder; use ali_oss_rs::request::{OssRequest, RequestMethod}; fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; let object_key = "documents/report.pdf"; // Generate presigned URL for download (browser-friendly) let options = PresignGetOptionsBuilder::new(3600) // Valid for 1 hour .process("style/thumbnail") // Optional: image processing .build(); let download_url = client.presign_url(bucket, object_key, options); println!("Download URL: {}", download_url); // Generate presigned request for upload (with headers) let request = OssRequest::new() .method(RequestMethod::Put) .bucket(bucket) .object("uploads/new-file.txt") .add_header("content-type", "text/plain") .add_header("content-length", "1024"); let SignedOssRequest { url, headers } = client.presign_raw_request(request); println!("Upload URL: {}", url); println!("Required headers:"); for (key, value) in &headers { println!(" {}: {}", key, value); } // Example: Use presigned URL with curl // curl -X GET "download_url_here" // curl -X PUT "upload_url_here" -H "authorization: ..." -H "x-oss-date: ..." --data-binary @file.txt Ok(()) } ``` -------------------------------- ### Perform Multipart Uploads in Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Handles uploading large files in parts, essential for files over 5GB. It includes initiating the upload, uploading individual parts, completing the upload, listing ongoing uploads, listing parts of an upload, and aborting an upload. Requires the ali-oss-rs crate and tokio for async operations. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::multipart::MultipartUploadsOperations; use ali_oss_rs::multipart_common::{ InitiateMultipartUploadOptions, UploadPartRequest, CompleteMultipartUploadRequest, CompleteMultipartUploadResult, ListMultipartUploadsOptionsBuilder }; use std::ops::Range; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; let object_key = "large-files/video.mp4"; let file_path = "/path/to/large-video.mp4"; // Calculate part ranges (5MB minimum per part, except last) let file_size = std::fs::metadata(file_path)?.len(); let part_size: u64 = 10 * 1024 * 1024; // 10MB parts let mut ranges: Vec> = vec![]; let mut start = 0u64; while start < file_size { let end = (start + part_size).min(file_size); ranges.push(start..end); start = end; } // Step 1: Initiate multipart upload let init_result = client.initiate_multipart_uploads( bucket, object_key, None ).await?; let upload_id = init_result.upload_id; println!("Upload ID: {}", upload_id); // Step 2: Upload parts let mut part_results: Vec<(u32, String)> = vec![]; for (i, range) in ranges.iter().enumerate() { let part_number = (i + 1) as u32; let params = UploadPartRequest { part_number, upload_id: upload_id.clone(), }; let result = client.upload_part_from_file( bucket, object_key, file_path, range.clone(), params ).await?; part_results.push((part_number, result.etag)); println!("Uploaded part {}/{}", part_number, ranges.len()); } // Step 3: Complete multipart upload let complete_request = CompleteMultipartUploadRequest { upload_id: upload_id.clone(), parts: part_results, }; let result = client.complete_multipart_uploads( bucket, object_key, complete_request, None ).await?; match result { CompleteMultipartUploadResult::ApiResponse(resp) => { println!("Upload complete! Location: {}", resp.location); } CompleteMultipartUploadResult::CallbackResponse(json) => { println!("Callback: {}", json); } } // List ongoing multipart uploads let list_opts = ListMultipartUploadsOptionsBuilder::new() .prefix("large-files/") .max_uploads(10) .build(); let uploads = client.list_multipart_uploads(bucket, Some(list_opts)).await?; for upload in uploads.uploads { println!("Pending upload: {} ({})", upload.key, upload.upload_id); } // List parts of an upload let parts = client.list_parts(bucket, object_key, &upload_id, None).await?; for part in parts.parts { println!("Part {}: {} bytes", part.part_number, part.size); } // Abort a multipart upload (cleanup) client.abort_multipart_uploads(bucket, "abandoned-upload.zip", "upload-id").await?; Ok(()) } ``` -------------------------------- ### Download Objects from Ali OSS to Files or Memory (Rust) Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Downloads objects from Ali OSS to local files or memory buffers. Supports range requests for partial downloads and conditional downloads using headers like If-Modified-Since. It also demonstrates downloading specific versions of an object. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::object::ObjectOperations; use ali_oss_rs::object_common::GetObjectOptionsBuilder; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; // Simple download to file client.get_object_to_file( bucket, "documents/report.pdf", "/path/to/download/report.pdf", None ).await?; // Download with range (partial content) let options = GetObjectOptionsBuilder::new() .range("bytes=0-1023") // First 1KB .build(); client.get_object_to_file( bucket, "large-file.zip", "/path/to/partial.zip", Some(options) ).await?; // Conditional download with If-Modified-Since let options = GetObjectOptionsBuilder::new() .if_modified_since("Fri, 13 Nov 2024 14:47:53 GMT") .accept_encoding("gzip") .build(); client.get_object_to_file( bucket, "data.json", "/path/to/data.json", Some(options) ).await?; // Download to memory buffer let buffer = client.get_object_to_buffer(bucket, "small-file.txt", None).await?; let content = String::from_utf8(buffer)?; println!("File content: {}", content); // Download specific version let options = GetObjectOptionsBuilder::new() .version_id("CAEQARiBgID...") .build(); let buffer = client.get_object_to_buffer(bucket, "versioned-file.txt", Some(options)).await?; Ok(()) } ``` -------------------------------- ### Synchronous Operations with Blocking API in Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Demonstrates synchronous object and bucket operations using the blocking API of the ali-oss-rs SDK. Requires enabling the 'blocking' feature in Cargo.toml. Handles bucket listing, object listing with options, file uploads, and downloads. ```rust // Cargo.toml: ali-oss-rs = { version = "0.2", features = ["blocking"] } use ali_oss_rs::blocking::{Client, BucketOperations, ObjectOperations}; use ali_oss_rs::bucket_common::ListObjectsOptionsBuilder; use ali_oss_rs::Result; fn main() -> Result<()> { let client = Client::from_env(); // All operations are synchronous let buckets = client.list_buckets(None)?; println!("Found {} buckets", buckets.buckets.len()); let options = ListObjectsOptionsBuilder::new() .prefix("docs/") .delimiter('/') .build(); let objects = client.list_objects("my-bucket", Some(options))?; for obj in objects.contents { println!("{}: {} bytes", obj.key, obj.size); } // Upload file synchronously client.put_object_from_file("my-bucket", "test.txt", "/path/to/file.txt", None)?; // Download synchronously client.get_object_to_file("my-bucket", "test.txt", "/path/to/download.txt", None)?; Ok(()) } ``` -------------------------------- ### Symlink Operations Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Create and manage symbolic links (soft links) to objects. This includes creating and retrieving symlinks. ```APIDOC ## Symlink Operations ### Description Create and manage symbolic links (soft links) to objects. ### Method - PUT: `put_symlink` - GET: `get_symlink` ### Endpoint - `/{bucket}/{symlink_path}` (for PUT and GET operations) ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket. - **symlink_path** (string) - Required - The path for the symlink to be created or retrieved. #### Query Parameters - **versionId** (string) - Optional - Specifies the symlink version ID. #### Request Body (for PUT) - **target_object** (string) - Required - The path of the object the symlink points to. - **options** (PutSymlinkOptions) - Optional - Options for creating the symlink, such as metadata. - `metadata` (HashMap) - Optional - Key-value metadata to associate with the symlink. ### Request Example (Creating Symlink) ```rust use ali_oss_rs::symlink_common::PutSymlinkOptionsBuilder; let options = PutSymlinkOptionsBuilder::new() .metadata("x-oss-meta-link-type", "shortcut") .build(); let result = client.put_symlink( bucket, "shortcuts/latest-report.pdf", // Symlink path "documents/2024/q4-report.pdf", // Target object Some(options) ).await?; ``` ### Response #### Success Response (200) - **target** (string) - The target object path the symlink points to. - **version_id** (string) - The version ID of the symlink (if versioning is enabled). #### Response Example (Getting Symlink) ```rust let target = client.get_symlink(bucket, "shortcuts/latest-report.pdf", None).await?; println!("Points to: {}", target); ``` ``` -------------------------------- ### Manage Object ACLs in Rust Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Demonstrates how to retrieve and set Access Control Lists (ACLs) for individual objects in an OSS bucket. This allows fine-grained control over object access permissions. It uses the ali-oss-rs crate and tokio for asynchronous operations. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::acl::ObjectAclOperations; use ali_oss_rs::object_common::ObjectAcl; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; let object_key = "public/image.jpg"; // Get current object ACL let acl = client.get_object_acl(bucket, object_key, None).await?; println!("Current ACL: {:?}", acl); // Set object to public read client.put_object_acl(bucket, object_key, ObjectAcl::PublicRead, None).await?; // Reset to inherit bucket ACL client.put_object_acl(bucket, object_key, ObjectAcl::Default, None).await?; // Set to private client.put_object_acl(bucket, object_key, ObjectAcl::Private, None).await?; Ok(()) } ``` -------------------------------- ### Upload Objects to Ali OSS from Various Sources (Rust) Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Uploads objects to Ali OSS from local files, memory buffers, or base64 encoded strings. Supports configuring metadata, tags, storage classes, and callback notifications. The SDK handles different upload result types, including API responses and callback responses. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::object::ObjectOperations; use ali_oss_rs::object_common::{ PutObjectOptionsBuilder, PutObjectResult, ObjectAcl, CallbackBuilder, CallbackBodyParameter }; use ali_oss_rs::common::StorageClass; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; // Simple file upload let result = client.put_object_from_file( bucket, "documents/report.pdf", "/path/to/local/report.pdf", None ).await?; // Upload with options: metadata, tags, storage class let options = PutObjectOptionsBuilder::new() .mime_type("application/pdf") .storage_class(StorageClass::InfrequentAccess) .object_acl(ObjectAcl::PublicRead) .cache_control("max-age=3600") .content_disposition("attachment; filename=\"report.pdf\"" ) .metadata("x-oss-meta-author", "John Doe") .metadata("x-oss-meta-version", "1.0") .tag("department", "engineering") .tag("confidential", "false") .forbid_overwrite(true) .build(); let result = client.put_object_from_file( bucket, "documents/report-v2.pdf", "/path/to/local/report.pdf", Some(options) ).await?; // Handle upload result match result { PutObjectResult::ApiResponse(resp) => { println!("ETag: {}, MD5: {}", resp.etag, resp.content_md5); } PutObjectResult::CallbackResponse(json) => { println!("Callback response: {}", json); } } // Upload from memory buffer let data = b"Hello, World!".to_vec(); let options = PutObjectOptionsBuilder::new() .mime_type("text/plain") .build(); client.put_object_from_buffer(bucket, "hello.txt", data, Some(options)).await?; // Upload from base64 string let base64_data = "SGVsbG8sIFdvcmxkIQ=="; // "Hello, World!" in base64 client.put_object_from_base64(bucket, "hello-b64.txt", base64_data, None).await?; // Upload with callback notification let callback = CallbackBuilder::new("https://your-server.com/oss-callback") .body_parameter(CallbackBodyParameter::OssBucket("bucket")) .body_parameter(CallbackBodyParameter::OssObject("object")) .body_parameter(CallbackBodyParameter::OssSize("size")) .body_parameter(CallbackBodyParameter::OssETag("etag")) .body_parameter(CallbackBodyParameter::OssMimeType("mime")) .body_parameter(CallbackBodyParameter::Custom("custom_key", "var1", "custom_value".to_string())) .custom_variable("var1", "my_custom_data") .build(); let options = PutObjectOptionsBuilder::new() .callback(callback) .build(); let result = client.put_object_from_file( bucket, "with-callback.txt", "/path/to/file.txt", Some(options) ).await?; // Create a folder (directory marker) client.create_folder(bucket, "new-folder/").await?; Ok(()) } ``` -------------------------------- ### Append Data to Ali OSS Objects with Rust SDK Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Shows how to append data to an object in Ali OSS, which is suitable for log files or streaming data. It covers initial appends, continuing appends at the next position, appending data from a file, and appending data from a base64 encoded string. ```rust use ali_oss_rs::{Client, Result}; use ali_oss_rs::object::ObjectOperations; use ali_oss_rs::object_common::AppendObjectOptionsBuilder; #[tokio::main] async fn main() -> Result<()> { let client = Client::from_env(); let bucket = "my-bucket"; let object_key = "logs/app.log"; // Initial append (position 0) let options = AppendObjectOptionsBuilder::new() .mime_type("text/plain") .build(); let result = client.append_object_from_buffer( bucket, object_key, b"First log entry\n".to_vec(), 0, // Starting position Some(options) ).await?; println!("Next position: {}", result.next_append_position); // Continue appending at returned position let next_pos = result.next_append_position; let result = client.append_object_from_buffer( bucket, object_key, b"Second log entry\n".to_vec(), next_pos, None ).await?; // Append from file let result = client.append_object_from_file( bucket, object_key, "/path/to/more-logs.txt", result.next_append_position, None ).await?; // Append from base64 string let base64_data = "TG9nIGVudHJ5IGZyb20gYmFzZTY0Cg=="; let result = client.append_object_from_base64( bucket, object_key, base64_data, result.next_append_position, None ).await?; Ok(()) } ``` -------------------------------- ### Restore Archive Objects Source: https://context7.com/yuqiang-yuan/ali-oss-rs/llms.txt Restore archived or cold archived objects to a readable state. Supports different restoration tiers and cleaning up restored copies. ```APIDOC ## Restore Archive Objects ### Description Restore archived or cold archived objects to a readable state. ### Method - POST: `restore_object` - POST: `clean_restored_object` ### Endpoint - `/{bucket}/{object_key}?restore` (for `restore_object`) - `/{bucket}/{object_key}?clean` (for `clean_restored_object`) ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket. - **object_key** (string) - Required - The key of the object to restore or clean. #### Query Parameters - **versionId** (string) - Optional - Specifies the object version ID. #### Request Body (for `restore_object`) - **request** (RestoreObjectRequest) - Required - Details for the restore request. - `days` (u32) - Required - The number of days to keep the restored object. - `tier` (RestoreJobTier) - Optional - The restoration priority tier (`Standard`, `Expedited`, `Bulk`). - `version_id` (Option) - Optional - The specific version ID to restore. ### Request Example (Restore Object) ```rust use ali_oss_rs::object_common::{RestoreObjectRequest, RestoreJobTier}; let request = RestoreObjectRequest { days: 7, tier: Some(RestoreJobTier::Standard), // 2-5 hours version_id: None, }; client.restore_object(bucket, "archived/old-data.zip", request).await?; ``` ### Response #### Success Response (200) - **object_restore_priority** (string) - Indicates the priority of the restore job. #### Response Example (Restore Initiated) ```json { "object_restore_priority": "STANDARD" } ``` ### Clean Restored Object #### Description Removes the restored copy of an archive object, reverting it to its archived state. ### Method - POST: `clean_restored_object` ### Request Example ```rust client.clean_restored_object(bucket, "archived/old-data.zip").await?; ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.