# Connect to S4 with Ruby

> Connect to Bitiful S4 with the aws-sdk-s3 gem: Ruby examples for uploads, multipart uploads, downloads, listing, presigned URLs, extension parameters, and error handling.

Uses the AWS SDK for Ruby 3.x. The code below can be placed in a single file and run in order.

## Prerequisites

1. [Create a bucket](https://docs.bitiful.com/en/bitiful-s4/handbook/buckets.md) in the console;
2. [Create a sub-user and AccessKey](https://docs.bitiful.com/en/bitiful-s4/handbook/access-keys.md), and [grant the sub-user access to this bucket](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md). A new sub-user has no permissions;
3. Put the keys in environment variables instead of writing them in code:

```bash
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"
```

## Install

```bash
gem install aws-sdk-s3
```

The examples on this page were tested on Ruby 3.1 and aws-sdk-s3 1.245.

## Connect to S4

```ruby title="s4.rb"
require "aws-sdk-s3"

S3 = Aws::S3::Client.new(
  endpoint: "https://s3.bitiful.net",
  region: "cn-east-1",
  access_key_id: ENV.fetch("S4_ACCESS_KEY"),
  secret_access_key: ENV.fetch("S4_SECRET_KEY")
)
BUCKET = "my-bucket"
```

`Aws::S3::Client` is thread-safe; create one per process.

## Upload files

An object with the same name is overwritten directly. If `ContentType` is left empty, S4 [detects it automatically](https://docs.bitiful.com/en/best-practice/auto-detect-mime.md).

```ruby title="s4.rb"
# Upload a text string
S3.put_object(
  bucket: BUCKET,
  key: "docs/hello.txt",
  body: "你好，S4",
  content_type: "text/plain; charset=utf-8"
)

# Upload a local file, setting cache time and custom metadata
File.open("photo.jpg", "rb") do |f|
  S3.put_object(
    bucket: BUCKET,
    key: "images/photo.jpg",
    body: f,
    content_type: "image/jpeg",
    cache_control: "max-age=86400",
    metadata: { "author" => "bitiful" }
  )
end
```

## 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.

```ruby title="s4.rb"
# Split automatically above 16 MiB
transfer = Aws::S3::TransferManager.new(client: S3)
transfer.upload_file(
  "video.mp4",
  bucket: BUCKET,
  key: "videos/video.mp4",
  multipart_threshold: 16 * 1024 * 1024,
  content_type: "video/mp4",
  progress_callback: ->(bytes, totals) { puts "#{bytes.sum * 100 / totals.sum}%" }
)
```

## Download files

Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.

```ruby title="s4.rb"
# Read as a string
puts S3.get_object(bucket: BUCKET, key: "docs/hello.txt").body.read

# Save to a file
S3.get_object(bucket: BUCKET, key: "videos/video.mp4", response_target: "video-copy.mp4")

# Read only the first 1 KiB
part = S3.get_object(bucket: BUCKET, key: "videos/video.mp4", range: "bytes=0-1023")
puts part.content_range
```

## List files

Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. `Delimiter` supports only `/`.

```ruby title="s4.rb"
# List all objects under a prefix, paging automatically
S3.list_objects_v2(bucket: BUCKET, prefix: "images/").each do |page|
  page.contents.each { |obj| puts "#{obj.key} #{obj.size} #{obj.last_modified}" }
end

# List only the top-level directories
root = S3.list_objects_v2(bucket: BUCKET, delimiter: "/")
root.common_prefixes.each { |p| puts "Directory #{p.prefix}" }
```

## Get file information

Retrieve metadata without downloading the content. You can also use this to check whether an object exists.

```ruby title="s4.rb"
def exists?(key)
  S3.head_object(bucket: BUCKET, key: key)
  true
rescue Aws::S3::Errors::NotFound
  false
end
```

## 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](https://docs.bitiful.com/en/bitiful-s4/features/move-object.md).

```ruby title="s4.rb"
require "erb"

# The object key in copy_source must be URL-encoded, keeping /
def copy_source(key)
  "#{BUCKET}/#{key.split('/', -1).map { |p| ERB::Util.url_encode(p) }.join('/')}"
end

# Copy
S3.copy_object(bucket: BUCKET, key: "images/photo-copy.jpg", copy_source: copy_source("images/photo.jpg"))
```

```ruby title="s4.rb"
# Move / rename: S4 extension, no data copied
S3.copy_object(
  bucket: BUCKET,
  key: "archive/photo.jpg",
  copy_source: "#{copy_source('images/photo-copy.jpg')}?move=true"
)
```

## 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.

```ruby title="s4.rb"
# Delete one object
S3.delete_object(bucket: BUCKET, key: "docs/hello.txt")

# Batch delete, up to 1000 objects at a time
keys = ["images/a.jpg", "images/b.jpg"]
result = S3.delete_objects(
  bucket: BUCKET,
  delete: { objects: keys.map { |k| { key: k } }, quiet: true }
)
result.errors.each { |e| puts "#{e.key} #{e.code} #{e.message}" }
```

## 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.

```ruby title="s4.rb"
presigner = Aws::S3::Presigner.new(client: S3)

# Download URL, valid for 1 hour, with a specified file name
get_url = presigner.presigned_url(
  :get_object,
  bucket: BUCKET,
  key: "images/photo.jpg",
  expires_in: 3600,
  response_content_disposition: 'attachment; filename="photo.jpg"'
)
puts get_url

# Upload URL, valid for 10 minutes; the client sends a PUT to it
put_url = presigner.presigned_url(:put_object, bucket: BUCKET, key: "uploads/avatar.jpg", expires_in: 600)
puts put_url
```

## Presigned URLs with extension parameters

Extension parameters such as [CoreIX processing parameters](https://docs.bitiful.com/en/coreix/basic.md), rate limits, and request limits must be added **before signing**. Appending them after signing returns `SignatureDoesNotMatch`.

```ruby title="s4.rb"
require "uri"

# Generate a download URL with S4 extension parameters; they are included in the signature
def presign_with(key, params, expires_in: 3600)
  signer = Aws::Sigv4::Signer.new(
    service: "s3",
    region: "cn-east-1",
    access_key_id: ENV.fetch("S4_ACCESS_KEY"),
    secret_access_key: ENV.fetch("S4_SECRET_KEY"),
    uri_escape_path: false
  )
  path = key.split("/", -1).map { |p| ERB::Util.url_encode(p) }.join("/")
  query = params.map { |k, v| "#{k}=#{ERB::Util.url_encode(v.to_s)}" }.join("&")
  signer.presign_url(
    http_method: "GET",
    url: "https://#{BUCKET}.s3.bitiful.net/#{path}?#{query}",
    expires_in: expires_in,
    body_digest: "UNSIGNED-PAYLOAD"
  ).to_s
end

puts presign_with("images/photo.jpg", {
  "w" => 500,                          # CoreIX: width 500 px
  "fmt" => "webp",                     # CoreIX: convert to WebP
  "x-bitiful-limit-rate" => 1_048_576, # Per-connection rate limit of 1 MiB/s
  "x-bitiful-max-requests" => 3        # At most 3 accesses
})
```

## Conditional writes

Conditional writes prevent concurrent overwrites. When the condition is not met, S4 returns 412. See [Conditional requests](https://docs.bitiful.com/en/developer/s3/conditional-requests.md).

```ruby title="s4.rb"
begin
  # Write only if the object does not exist, to prevent overwriting
  S3.put_object(bucket: BUCKET, key: "locks/job", body: "me", if_none_match: "*")
rescue Aws::S3::Errors::PreconditionFailed
  puts "Object already exists"
end
```

## Handle errors

For the meaning of each error code, see [Error codes and troubleshooting](https://docs.bitiful.com/en/developer/s3/errors.md). Rate limiting returns 429 `TooManyRequest`; catch it and retry with backoff.

```ruby title="s4.rb"
begin
  S3.get_object(bucket: BUCKET, key: "not-exists.txt")
rescue Aws::S3::Errors::NoSuchKey
  puts "Object does not exist"
rescue Aws::S3::Errors::ServiceError => e
  puts "#{e.context.http_response.status_code} #{e.code} #{e.message}"
rescue Seahorse::Client::NetworkingError => e
  puts "Network error: #{e.message}"
end
```

## FAQ

<details>
<summary>How do I configure Rails Active Storage</summary>

In `config/storage.yml`, use `service: S3`, set `endpoint` to `https://s3.bitiful.net` and `region` to `cn-east-1`, and fill in the keys and `bucket`.

</details>

<details>
<summary>Returns 403 AccessDenied</summary>

The sub-user has no permission on this bucket or directory. See [Sub-user permissions](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md). Creating and deleting buckets can only be done in the console.

</details>

<details>
<summary>Returns SignatureDoesNotMatch</summary>

The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the [checklist](https://docs.bitiful.com/en/developer/s3/errors.md).

</details>

<details>
<summary>Download speed is low</summary>

Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a [CDN](https://docs.bitiful.com/en/cdn/intro.md) to serve visitors.

</details>

## Related documentation

[**Presigned URLs and extensions**](https://docs.bitiful.com/en/developer/s3/presigned-url.md)

Full reference for request limits, rate limits, Simul-Transfer, and other parameters.

[**Error codes and troubleshooting**](https://docs.bitiful.com/en/developer/s3/errors.md)

Checklists for 403, SignatureDoesNotMatch, and other issues.

[**S3 API compatibility**](https://docs.bitiful.com/en/developer/s3/compatibility.md)

Support status and differences for each operation.

[**Upload files securely from the client**](https://docs.bitiful.com/en/best-practice/web-uploads.md)

Recommended practices for direct uploads from browsers and apps.
