Connect to S4 with Rust
Uses the AWS SDK for Rust. Each snippet below is an async function you can call directly.
Prerequisites
- Create a bucket in the console;
- Create a sub-user and AccessKey, and grant the sub-user access to this bucket. A new sub-user has no permissions;
- Put the keys in environment variables instead of writing them in code:
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"Install
cargo add aws-sdk-s3 urlencoding
cargo add tokio --features fullThe examples on this page were tested on aws-sdk-s3 1.161.0 and require Rust 1.94.1 or later.
Connect to S4
use aws_sdk_s3::config::{BehaviorVersion, Credentials, Region};
use aws_sdk_s3::Client;
const BUCKET: &str = "my-bucket";
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn client() -> Result<Client> {
let credentials = Credentials::new(
std::env::var("S4_ACCESS_KEY")?,
std::env::var("S4_SECRET_KEY")?,
None,
None,
"env",
);
let config = aws_sdk_s3::Config::builder()
.behavior_version(BehaviorVersion::latest())
.endpoint_url("https://s3.bitiful.net")
.region(Region::new("cn-east-1"))
.credentials_provider(credentials)
.build();
Ok(Client::from_conf(config))
}Client is reference-counted internally, so clone() is cheap and you can pass clients between tasks.
Upload files
An object with the same name is overwritten directly. If ContentType is left empty, S4 detects it automatically.
use aws_sdk_s3::primitives::ByteStream;
async fn upload(s3: &Client) -> Result<()> {
// Upload a text string
s3.put_object()
.bucket(BUCKET)
.key("docs/hello.txt")
.content_type("text/plain; charset=utf-8")
.body(ByteStream::from_static("你好,S4".as_bytes()))
.send()
.await?;
// Upload a local file, setting cache time and custom metadata
s3.put_object()
.bucket(BUCKET)
.key("images/photo.jpg")
.content_type("image/jpeg")
.cache_control("max-age=86400")
.metadata("author", "bitiful")
.body(ByteStream::from_path("photo.jpg").await?)
.send()
.await?;
Ok(())
}Upload large files
Use multipart upload for files larger than 100 MB: parts can upload concurrently, and a failed part is the only one you need to retry. Each part is 5 MiB to 20 GiB, with up to 10000 parts.
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
use tokio::io::AsyncReadExt;
const PART_SIZE: usize = 16 * 1024 * 1024; // 16 MiB per part; every part except the last must be at least 5 MiB
async fn upload_large(s3: &Client, path: &str, key: &str) -> Result<()> {
let created = s3
.create_multipart_upload()
.bucket(BUCKET)
.key(key)
.content_type("video/mp4")
.send()
.await?;
let upload_id = created.upload_id().ok_or("no upload_id returned")?;
match upload_parts(s3, path, key, upload_id).await {
Ok(parts) => {
s3.complete_multipart_upload()
.bucket(BUCKET)
.key(key)
.upload_id(upload_id)
.multipart_upload(
CompletedMultipartUpload::builder()
.set_parts(Some(parts))
.build(),
)
.send()
.await?;
Ok(())
}
Err(err) => {
// On failure, abort and clean up the uploaded parts
s3.abort_multipart_upload()
.bucket(BUCKET)
.key(key)
.upload_id(upload_id)
.send()
.await?;
Err(err)
}
}
}
async fn upload_parts(
s3: &Client,
path: &str,
key: &str,
upload_id: &str,
) -> Result<Vec<CompletedPart>> {
let mut file = tokio::fs::File::open(path).await?;
let mut parts = Vec::new();
loop {
let mut buf = Vec::with_capacity(PART_SIZE);
(&mut file).take(PART_SIZE as u64).read_to_end(&mut buf).await?;
if buf.is_empty() {
return Ok(parts);
}
let number = parts.len() as i32 + 1;
let out = s3
.upload_part()
.bucket(BUCKET)
.key(key)
.upload_id(upload_id)
.part_number(number)
.body(ByteStream::from(buf))
.send()
.await?;
parts.push(
CompletedPart::builder()
.part_number(number)
.set_e_tag(out.e_tag().map(str::to_owned))
.build(),
);
}
}Download files
Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.
async fn download(s3: &Client) -> Result<()> {
// Save to a file
let out = s3.get_object().bucket(BUCKET).key("videos/video.mp4").send().await?;
let mut reader = out.body.into_async_read();
let mut file = tokio::fs::File::create("video-copy.mp4").await?;
tokio::io::copy(&mut reader, &mut file).await?;
// Read only the first 1 KiB
let part = s3
.get_object()
.bucket(BUCKET)
.key("videos/video.mp4")
.range("bytes=0-1023")
.send()
.await?;
println!("{:?}", part.content_range());
Ok(())
}List files
Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. Delimiter supports only /.
async fn list(s3: &Client) -> Result<()> {
// List all objects under a prefix, paging automatically
let mut pages = s3
.list_objects_v2()
.bucket(BUCKET)
.prefix("images/")
.into_paginator()
.send();
while let Some(page) = pages.next().await {
for obj in page?.contents() {
println!("{:?} {:?}", obj.key(), obj.size());
}
}
// List only the top-level directories
let root = s3.list_objects_v2().bucket(BUCKET).delimiter("/").send().await?;
for p in root.common_prefixes() {
println!("Directory {:?}", p.prefix());
}
Ok(())
}Get file information
Retrieve metadata without downloading the content. You can also use this to check whether an object exists.
async fn exists(s3: &Client, key: &str) -> Result<bool> {
match s3.head_object().bucket(BUCKET).key(key).send().await {
Ok(_) => Ok(true),
Err(err) if err.as_service_error().is_some_and(|e| e.is_not_found()) => Ok(false),
Err(err) => Err(err.into()),
}
}Copy and move
Copying is done server-side, so data does not pass through your machine. Move is an S4 extension: append ?move=true to CopySource. It only changes the location without copying data, regardless of file size. See Move and rename objects.
fn copy_source(key: &str) -> String {
// URL-encode the object key, keeping /
let encoded: Vec<_> = key.split('/').map(urlencoding::encode).collect();
format!("{BUCKET}/{}", encoded.join("/"))
}
async fn copy_object(s3: &Client, src: &str, dst: &str) -> Result<()> {
s3.copy_object()
.bucket(BUCKET)
.key(dst)
.copy_source(copy_source(src))
.send()
.await?;
Ok(())
}
// Move / rename: S4 extension, no data copied
async fn move_object(s3: &Client, src: &str, dst: &str) -> Result<()> {
s3.copy_object()
.bucket(BUCKET)
.key(dst)
.copy_source(format!("{}?move=true", copy_source(src)))
.send()
.await?;
Ok(())
}Delete files
Deleted objects cannot be recovered. A batch delete handles up to 1000 keys at a time; if you lack write permission on any one key, the whole batch returns 403.
use aws_sdk_s3::types::{Delete, ObjectIdentifier};
async fn remove(s3: &Client) -> Result<()> {
// Delete one object
s3.delete_object().bucket(BUCKET).key("docs/hello.txt").send().await?;
// Batch delete, up to 1000 objects at a time
let mut delete = Delete::builder().quiet(true);
for key in ["images/a.jpg", "images/b.jpg"] {
delete = delete.objects(ObjectIdentifier::builder().key(key).build()?);
}
let out = s3.delete_objects().bucket(BUCKET).delete(delete.build()?).send().await?;
for e in out.errors() {
println!("{:?} {:?} {:?}", e.key(), e.code(), e.message());
}
Ok(())
}Presigned URLs
A presigned URL embeds the authorization in the link, so the holder can upload or download without a secret key. It is valid for up to 7 days. If you sign Content-Type for an upload, the client must send exactly the same value.
use aws_sdk_s3::presigning::PresigningConfig;
use std::time::Duration;
async fn presign(s3: &Client) -> Result<(String, String)> {
// Download URL, valid for 1 hour, with a specified file name
let get = s3
.get_object()
.bucket(BUCKET)
.key("images/photo.jpg")
.response_content_disposition("attachment; filename=\"photo.jpg\"")
.presigned(PresigningConfig::expires_in(Duration::from_secs(3600))?)
.await?;
// Upload URL, valid for 10 minutes; the client sends a PUT to it
let put = s3
.put_object()
.bucket(BUCKET)
.key("uploads/avatar.jpg")
.presigned(PresigningConfig::expires_in(Duration::from_secs(600))?)
.await?;
Ok((get.uri().to_string(), put.uri().to_string()))
}Presigned URLs with extension parameters
Extension parameters such as CoreIX processing parameters, rate limits, and request limits must be added before signing. Appending them after signing returns SignatureDoesNotMatch.
async fn presign_with_query(s3: &Client) -> Result<String> {
let req = s3
.get_object()
.bucket(BUCKET)
.key("images/photo.jpg")
.customize()
// Extension parameters are included in the signature; URL-encode the values first
.mutate_request(|req| {
let sep = if req.uri().contains('?') { '&' } else { '?' };
let uri = format!(
"{}{sep}w=500&fmt=webp&x-bitiful-limit-rate=1048576&x-bitiful-max-requests=3",
req.uri()
);
req.set_uri(uri).expect("valid URI");
})
.presigned(PresigningConfig::expires_in(Duration::from_secs(3600))?)
.await?;
Ok(req.uri().to_string())
}Handle errors
For the meaning of each error code, see Error codes and troubleshooting. Rate limiting returns 429 TooManyRequest; catch it and retry with backoff.
use aws_sdk_s3::error::{DisplayErrorContext, ProvideErrorMetadata, SdkError};
async fn handle_error(s3: &Client) {
match s3.get_object().bucket(BUCKET).key("not-exists.txt").send().await {
Ok(_) => println!("Success"),
Err(SdkError::ServiceError(e)) if e.err().is_no_such_key() => println!("Object does not exist"),
Err(SdkError::ServiceError(e)) => {
println!("{} {:?} {:?}", e.raw().status(), e.err().code(), e.err().message())
}
Err(e) => println!("Network error: {}", DisplayErrorContext(&e)),
}
}FAQ
Returns 403 AccessDenied
The sub-user has no permission on this bucket or directory. See Sub-user permissions. Creating and deleting buckets can only be done in the console.
Returns SignatureDoesNotMatch
The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the checklist.
Download speed is low
Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a CDN to serve visitors.
Related documentation
Full reference for request limits, rate limits, Simul-Transfer, and other parameters.
Checklists for 403, SignatureDoesNotMatch, and other issues.
Support status and differences for each operation.
Recommended practices for direct uploads from browsers and apps.