storage-transfer-lib 0.2.0

Bounded S3 and local directory transfers using Apache OpenDAL
Documentation
# storage-transfer-lib

A Rust library for copying files between S3-compatible buckets and local filesystem directories using Apache OpenDAL. It preserves relative paths and streams data in bounded chunks. A file counts as copied when its destination writer closes successfully.

The engine recursively lists file objects into a bounded queue. All transfers use the same Operator-based listing, copy workers, progress tracking, and reports. Copy workers share one HTTP concurrency limit across source and destination, including listing, reads, multipart writes and retries.

**Source files must remain unchanged for the entire transfer**, including listing
and copying. This includes contents, sizes, names, copied metadata and the set of files
under the source root. The caller must enforce this: the library does not use
conditional source reads or detect changes. Modifying the source during a run can
produce incomplete or inconsistent output even when the run succeeds.

## Setup

Requires Rust 1.91 or newer and a Tokio runtime. Add these dependencies to your application's `Cargo.toml`:

```toml
[dependencies]
storage-transfer-lib = "0.2.0"
opendal = { version = "0.59.5", default-features = false, features = ["services-s3", "http-transport-reqwest", "executors-tokio"] }
tokio = { version = "1.53.3", features = ["macros", "rt"] }
```

The default `s3` feature enables OpenDAL’s S3 backend and reqwest HTTP transport.

Call `opendal::install_default()` before constructing S3 operators to install the
default HTTP transport.

## Copy a bucket on OCI

Use existing source and destination buckets. The credentials need permission to list/read the source and write the destination, including multipart operations. Destination read permission is not required.

For OCI, use a **Customer Secret Key** access-key/secret-key pair and the namespace's S3 compatibility endpoint. See [Oracle's S3 compatibility setup](https://docs.oracle.com/en-us/iaas/Content/Object/Tasks/s3compatibleapi.htm).

Set these environment variables in your application environment:

```sh
export OCI_REGION='us-ashburn-1'
export OCI_S3_ENDPOINT='https://<namespace>.compat.objectstorage.us-ashburn-1.oci.customer-oci.com'
export AWS_ACCESS_KEY_ID='<customer-secret-key-access-key>'
export AWS_SECRET_ACCESS_KEY='<customer-secret-key-secret>'
export SOURCE_BUCKET='source-bucket'
export DESTINATION_BUCKET='destination-bucket'
```

The following `src/main.rs` copies all file objects to the same keys in the destination. Both operators cover the bucket root in this example. This example uses the same region and credentials for both buckets; operators can also be built separately for different endpoints or credentials.

```rust
use std::{env, error::Error, path::Path, time::Duration};

use opendal::{services::S3, Operator};
use storage_transfer_lib::{RetryConfig, TimeoutConfig, TransferConfig, TransferEngine, TransferLimits};

fn bucket(name: &str) -> Result<Operator, Box<dyn Error>> {
    Ok(Operator::new(
        S3::default()
            .bucket(name)
            .root("/")
            .endpoint(&env::var("OCI_S3_ENDPOINT")?)
            .region(&env::var("OCI_REGION")?)
            .access_key_id(&env::var("AWS_ACCESS_KEY_ID")?)
            .secret_access_key(&env::var("AWS_SECRET_ACCESS_KEY")?)
            .disable_config_load()
            .disable_ec2_metadata(),
    )?)
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn Error>> {
    opendal::install_default();
    let source = bucket(&env::var("SOURCE_BUCKET")?)?;
    let destination = bucket(&env::var("DESTINATION_BUCKET")?)?;
    let config = TransferConfig {
        limits: TransferLimits::new(1024, 32)?,
        retry: RetryConfig {
            max_retries: 3,
            ..RetryConfig::default()
        },
        timeout: TimeoutConfig {
            operation: Duration::from_secs(30),
            io: Duration::from_secs(30),
        },
        ..TransferConfig::default()
    };
    let mut engine = TransferEngine::new(source, destination, config)?;
    let summary = engine.run_with_report(Path::new("transfer.jsonl")).await?;
    println!("Copied {} objects ({} bytes)", summary.copied_objects, summary.copied_bytes);
    Ok(())
}
```

Run your application with `cargo run --release`. `transfer.jsonl` must not already exist. Use a new report path for each run. For a transfer without a report, call `engine.run().await` instead.

If listing or a worker fails, the engine stops listing, discards queued objects,
and waits for active copies to finish before returning the first error. Completed
objects remain in place. Failed copies attempt to abort unfinished writes under
the configured timeout and retry policy; cleanup errors are ignored. Dropping
the transfer future or terminating the process cannot guarantee cleanup of
unfinished multipart uploads.

## Copy local folders

For local-only applications, set `default-features = false` on both this library
and OpenDAL, and enable OpenDAL’s `services-fs` feature instead of its S3 and
reqwest features. Inside a Tokio runtime, pass local operators to the same engine:

```rust
use opendal::{services::Fs, Operator};
use storage_transfer_lib::{TransferConfig, TransferEngine};

let source = Operator::new(Fs::default().root("/data/input"))?;
let destination = Operator::new(Fs::default().root("/data/output"))?;
let mut engine = TransferEngine::new(source, destination, TransferConfig::default())?;
engine.run().await?;
```

`/data/input/nested/a.csv` maps to `/data/output/nested/a.csv`. Either endpoint
can also be an S3 operator. All listing and I/O use OpenDAL; capabilities select
the metadata supported by the destination.
Reports retain relative `path` values and absolute paths for local endpoints.

Supply non-overlapping roots and an existing source directory. Link and
path semantics follow OpenDAL; use UTF-8 names without leading/trailing whitespace.
Empty directories, permissions, ownership and timestamps are not preserved.
Use `Fs` without `atomic_write_dir` for create-only writes. Failed
writes can leave partial files; inspect them before retrying. Keep reports
outside the source tree.

## Configuration

`TransferConfig` groups `timeout: TimeoutConfig`, `retry: RetryConfig`, and
`read: ReadConfig`, alongside `limits: TransferLimits` and a shared `chunk_size`.
Each group implements `Default`; override only the groups and fields you need:

| Setting | Default | Meaning |
| --- | --- | --- |
| `limits.max_queued_objects()` | 1024 | Waiting object descriptors; excludes objects being copied and the current listing page |
| `limits.max_ongoing_http_requests()` | 32 | Shared HTTP request limit across both operators in one engine |
| `chunk_size` | 8 MiB | Chunk size in bytes shared by reads and writes |
| `read.concurrency` | 1 | Maximum simultaneous chunk reads per object |
| `read.prefetch` | 0 | Extra completed chunks OpenDAL may buffer during concurrent reads |
| `timeout.operation` | 30 seconds | Timeout for each operation attempt, such as stat or opening a reader/writer |
| `timeout.io` | 30 seconds | Timeout for each I/O attempt, such as reading, writing, closing, or aborting |
| `retry.max_retries` | 2 | Additional attempts after the first attempt; `0` disables retries |
| `retry.delay` | 100 milliseconds | Initial exponential retry delay |
| `retry.max_delay` | 1 second | Maximum retry delay |

Set both concurrency limits with `TransferLimits::new(queue_capacity, http_concurrency)`. Limits must be positive. Durations must be positive and representable as deadlines; `retry.max_delay` must be at least `retry.delay`.

Set `chunk_size` in bytes. It must be positive and within the destination’s
streaming write limits (5 MiB to 5 GiB for S3). S3 objects must fit within 10,000
chunks.

The engine installs OpenDAL timeout and retry layers on both operators. HTTP capacity is held through the response body and released before retry backoff. Worker count is derived as `min(http_concurrency, 32)`. Multiple engine instances have separate limits.

For large files, enable concurrent reads and read-ahead through `TransferConfig`:

```rust
use storage_transfer_lib::{ReadConfig, TransferConfig};

let config = TransferConfig {
    chunk_size: 16 * 1024 * 1024,
    read: ReadConfig {
        concurrency: 4,
        prefetch: 2,
    },
    ..TransferConfig::default()
};
```

The reader uses one ordered stream across the object, so pending chunk reads can
continue while the destination writes earlier chunks. `read.concurrency` must be
positive; `read.prefetch` may be zero. Extra prefetch buffering is useful with
concurrent reads (`read.concurrency > 1`). Source reads and destination writes
still share `limits.max_ongoing_http_requests()`; per-object read concurrency
cannot bypass that limit. Writes remain sequential. Memory use grows with the
number of active objects, `chunk_size`, and
`read.concurrency + read.prefetch`, plus buffers held by the copy and writer.

## Progress and reports

Call `engine.subscribe()` before starting a run to obtain a `tokio::sync::watch::Receiver<TransferProgress>`. Use `changed().await` to observe updates and `borrow_and_update()` to read the latest counters. Watch receivers retain the latest snapshot rather than every update. Release the borrowed snapshot before awaiting again.

Progress includes `listed_objects`, `read_bytes`, `copied_objects`, and `copied_bytes`.
`read_bytes` advances whenever a buffer is delivered from the source stream to a
copy worker, before writing it. It counts logical bytes, excluding duplicate HTTP
retry traffic and prefetched buffers not yet delivered to the worker. Read progress
is retained if a later read or write fails. Copied counters advance after the
destination writer closes successfully. A successful run returns the final
`TransferProgress`; after an error, the receiver still exposes partial progress.
Counters reset when a new transfer run starts.

`run_with_report` writes JSONL records incrementally for attempted objects, followed by a final progress/error record when the run returns. For example:

```jsonl
{"type":"object","path":"nested/example.bin","bytes":17,"status":"copied","error":null}
{"type":"finished","progress":{"listed_objects":1,"read_bytes":17,"copied_objects":1,"copied_bytes":17},"error":null}
```

Object statuses are `copied` or `failed`. A failed run can leave listed objects unattempted; the report is not a complete bucket inventory or a resume database. Process termination can leave a partial report without a `finished` record.

## Directory-scoped transfers

Set the source and destination S3 operator roots independently:

```rust
use opendal::services::S3;

let source = S3::default().root("input/raw/");
let destination = S3::default().root("brightdata/");
```

Configure each builder's bucket, endpoint, region and credentials as in the OCI
example, then pass the operators to `TransferEngine::new` as usual.
`input/raw/nested/a.csv` maps to `brightdata/nested/a.csv`: the source directory
is stripped and the destination directory is prepended. Listing is constrained
to `input/raw/`, so `input/raw-other/` is outside the transfer. Empty prefixes
select bucket roots. Directory roots use OpenDAL's normal root normalization;
this library adds no filesystem-style prefix validation.

The caller chooses the source and destination buckets. The library does not infer
bucket identity from operator names or compare directory overlap. Create-only
writes also apply to scoped transfers. Report `path` stays relative to the configured source root;
new `source_path` and `destination_path` fields contain complete bucket-relative
keys for auditing.

## Tests

Run `cargo test` with Rust 1.91 or newer.

`tests/s3s.rs` starts an authenticated S3 server in the test process on an ephemeral
loopback port, then closes it after testing local → S3 → S3 → local transfers.
It uses temporary storage and needs no Docker, external service or credentials.
Run it alone with `cargo test --test s3s`.

The s3s 0.11 test uses ListObjects V1 and covers HTTP round trips, multipart
data and user metadata.
The mock transport tests cover pagination, other metadata and create-only writes,
which this older emulator does not fully implement.