aws-s3-transfer 1.0.0

Transfer Manager for Amazon S3 - a high-performance data plane client for uploading and downloading objects and directories.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Objects, S3 clients, handles and transfers that download tests run against.

use std::sync::Arc;

use super::sink::{Event, Op, ScriptedSinkFactory, WriteScript};
use crate::operation::download::body::{new_recv_body_with_disk_mode, RecvBodyConsumer};
use crate::operation::download::sink::SinkFactory;
use crate::operation::download::transfer::DownloadWork;
use crate::operation::download::{DownloadInput, DownloadTransfer};
use crate::runtime::buffer_pool::Reservation;
use crate::scheduler::test_util::assert_ready;
use crate::transfer::{IoRequest, TransferContext, WorkOutcome};
use crate::types::{BucketType, ByteSize};

/// Deterministic object contents of `len` bytes, distinct from the zeros an
/// unwritten or preallocated region reads as.
pub(crate) fn object_bytes(len: usize) -> Arc<[u8]> {
    (0..len).map(|i| (i % 251) as u8 + 1).collect()
}

/// A whole-object HEAD response with stable size and ETag for any key.
pub(crate) fn head_rule(object_len: u64) -> aws_smithy_mocks::Rule {
    aws_smithy_mocks::mock!(aws_sdk_s3::Client::head_object).then_output(move || {
        aws_sdk_s3::operation::head_object::HeadObjectOutput::builder()
            .content_length(object_len as i64)
            .e_tag("test-etag")
            .build()
    })
}

/// An S3 client that serves `object` for any key, answering each ranged
/// `GetObject` with exactly the requested bytes.
pub(crate) fn object_client(object: Arc<[u8]>) -> aws_sdk_s3::Client {
    use aws_sdk_s3::operation::get_object::GetObjectOutput;
    use aws_sdk_s3::primitives::ByteStream;
    use aws_smithy_mocks::{mock, mock_client, MockResponse, RuleMode};

    use crate::http::header::{ByteRange, Range};

    let head = head_rule(object.len() as u64);
    let get = mock!(aws_sdk_s3::Client::get_object).then_compute_response(move |req| {
        let last = object.len() as u64 - 1;
        let (start, end) = match req.range().and_then(|r| r.parse::<Range>().ok()) {
            Some(Range(ByteRange::Inclusive(start, end))) => (start, end.min(last)),
            Some(Range(ByteRange::AllFrom(start))) => (start, last),
            _ => (0, last),
        };
        let body = object[start as usize..=end as usize].to_vec();
        MockResponse::Output(
            GetObjectOutput::builder()
                .content_length(body.len() as i64)
                .content_range(format!("bytes {start}-{end}/{}", object.len()))
                .e_tag("test-etag")
                .body(ByteStream::from(body))
                .build(),
        )
    });
    mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[head, get])
}

/// An S3 client serving `object` by range that answers the range starting at
/// `failing_start` with a server error. SDK retries are disabled.
///
/// Panics on a request without an inclusive byte range.
pub(crate) fn object_client_failing_at(
    object: Arc<[u8]>,
    failing_start: u64,
) -> aws_sdk_s3::Client {
    use aws_sdk_s3::operation::get_object::GetObjectOutput;
    use aws_sdk_s3::primitives::ByteStream;
    use aws_smithy_mocks::MockResponse;

    let object_len = object.len();
    strict_range_client(
        object,
        Some(failing_start),
        None,
        move |start, end, body| {
            MockResponse::Output(
                GetObjectOutput::builder()
                    .content_length(body.len() as i64)
                    .content_range(format!("bytes {start}-{end}/{object_len}"))
                    .e_tag("test-etag")
                    .body(ByteStream::from(body.to_vec()))
                    .build(),
            )
        },
    )
}

/// An S3 client serving `object` by range as HTTP responses that carry each
/// range's CRC32, so the SDK validates every body it delivers. The range starting
/// at `failing_start`, if any, answers with a server error. SDK retries are
/// disabled.
///
/// Panics on a request without an inclusive byte range.
pub(crate) fn crc32_object_client(
    object: Arc<[u8]>,
    failing_start: Option<u64>,
) -> aws_sdk_s3::Client {
    let mut checksum = aws_smithy_checksums::ChecksumAlgorithm::Crc32.into_impl();
    checksum.update(&object);
    crc32_object_client_with_stored_checksum(
        object,
        failing_start,
        aws_smithy_types::base64::encode(checksum.finalize()),
    )
}

/// Serves independently validated CRC32 ranges and reports `stored_checksum` on HEAD.
///
/// The stored value may disagree with the served object, while every range still
/// passes SDK validation. The range at `failing_start`, if set, returns a server error.
/// Panics on a request without an inclusive byte range.
pub(crate) fn crc32_object_client_with_stored_checksum(
    object: Arc<[u8]>,
    failing_start: Option<u64>,
    stored_checksum: String,
) -> aws_sdk_s3::Client {
    use aws_smithy_mocks::MockResponse;
    use aws_smithy_runtime_api::http::{Response, StatusCode};
    use aws_smithy_types::body::SdkBody;

    let object_len = object.len();
    strict_range_client(
        object,
        failing_start,
        Some(stored_checksum),
        move |start, end, body| {
            let mut crc32 = aws_smithy_checksums::ChecksumAlgorithm::Crc32.into_impl();
            crc32.update(body);
            let mut response = Response::new(
                StatusCode::try_from(200).unwrap(),
                SdkBody::from(body.to_vec()),
            );
            let headers = response.headers_mut();
            headers.insert("content-length", body.len().to_string());
            headers.insert("content-range", format!("bytes {start}-{end}/{object_len}"));
            headers.insert("etag", "test-etag");
            headers.insert(
                "x-amz-checksum-crc32",
                aws_smithy_types::base64::encode(crc32.finalize()),
            );
            MockResponse::Http(response)
        },
    )
}

/// An S3 client serving `object` by inclusive byte range, clamped to the object,
/// with SDK retries disabled. `respond` builds the answer from the range's start,
/// end and bytes; the range starting at `failing_start`, if any, answers with a
/// server error instead.
///
/// Panics on a request without an inclusive byte range.
fn strict_range_client(
    object: Arc<[u8]>,
    failing_start: Option<u64>,
    object_checksum: Option<String>,
    respond: impl Fn(
            u64,
            u64,
            &[u8],
        ) -> aws_smithy_mocks::MockResponse<
            aws_sdk_s3::operation::get_object::GetObjectOutput,
            aws_sdk_s3::operation::get_object::GetObjectError,
        > + Send
        + Sync
        + 'static,
) -> aws_sdk_s3::Client {
    use aws_smithy_mocks::{mock, mock_client, MockResponse, RuleMode};
    use aws_smithy_runtime_api::http::{Response, StatusCode};
    use aws_smithy_types::body::SdkBody;

    use crate::http::header::{ByteRange, Range};

    let object_len = object.len() as i64;
    let head = mock!(aws_sdk_s3::Client::head_object).then_output(move || {
        aws_sdk_s3::operation::head_object::HeadObjectOutput::builder()
            .content_length(object_len)
            .e_tag("test-etag")
            .set_checksum_crc32(object_checksum.clone())
            .build()
    });
    let get = mock!(aws_sdk_s3::Client::get_object).then_compute_response(move |req| {
        let (start, end) = match req.range().and_then(|r| r.parse::<Range>().ok()) {
            Some(Range(ByteRange::Inclusive(start, end))) => {
                (start, end.min(object.len() as u64 - 1))
            }
            other => panic!("unexpected range request {other:?}"),
        };
        if Some(start) == failing_start {
            return MockResponse::Http(Response::new(
                StatusCode::try_from(500).unwrap(),
                SdkBody::from("internal error"),
            ));
        }
        respond(start, end, &object[start as usize..=end as usize])
    });
    mock_client!(aws_sdk_s3, RuleMode::MatchAny, &[head, get], |conf| {
        conf.retry_config(aws_sdk_s3::config::retry::RetryConfig::disabled())
    })
}

/// A test handle on the ambient tokio runtime whose S3 client is `client`,
/// slicing downloads into `part_size` ranges.
pub(crate) fn disk_test_handle(
    client: aws_sdk_s3::Client,
    part_size: u64,
) -> Arc<crate::client::Handle> {
    let config = crate::Config::builder()
        .sdk_client(client)
        .part_size(crate::config::PartSize::Target(ByteSize::new(part_size)))
        .build()
        .expect("valid config");
    crate::client::Handle::test_handle_tokio(config)
}

/// A test handle whose work runs on up to four managed threads under a fixed
/// `concurrency` target.
///
/// A held destination write blocks its managed thread, and work routed to that
/// thread queues behind it. A low target bounds how much work is in flight at
/// once, so a test can keep other work off the held thread.
pub(crate) fn managed_test_handle(
    config: crate::Config,
    concurrency: usize,
) -> Arc<crate::client::Handle> {
    managed_test_handle_with_max_partitions(config, concurrency, 4).0
}

/// Builds managed execution and returns the number of discovered partitions.
pub(crate) fn managed_test_handle_with_max_partitions(
    config: crate::Config,
    concurrency: usize,
    max_partitions: usize,
) -> (Arc<crate::client::Handle>, usize) {
    let mut partition_count = 0;
    let handle = crate::client::Handle::new_for_test_with_runtime(
        config,
        Arc::new(crate::scheduler::FixedConcurrency::new(concurrency)),
        |weak| {
            let execution = crate::runtime::ManagedExecution::for_test(weak, max_partitions);
            partition_count = execution.partition_count();
            Arc::new(execution)
        },
    );
    (handle, partition_count)
}

/// A disk download transfer on `handle`, writing through a sink that `sinks`
/// creates over a new file named `out` in a fresh temporary directory.
///
/// Transfers built on one handle share its memory budget. Returns the transfer,
/// its body consumer, and the directory; the test keeps both for the
/// transfer's lifetime.
pub(crate) fn disk_transfer(
    handle: Arc<crate::client::Handle>,
    sinks: &dyn SinkFactory,
) -> (DownloadTransfer, RecvBodyConsumer, tempfile::TempDir) {
    let input = DownloadInput::builder()
        .bucket("test-bucket")
        .key("test-key")
        .build()
        .unwrap();
    let dir = tempfile::tempdir().unwrap();
    let file = std::fs::File::create(dir.path().join("out")).unwrap();
    let (writer, consumer) = new_recv_body_with_disk_mode(sinks.create(file, false).unwrap());
    let (ctx, _completion_rx) = TransferContext::new(handle);
    let transfer = DownloadTransfer::new(ctx, BucketType::Standard, input, writer);
    (transfer, consumer, dir)
}

/// Executes `work` on `transfer` and returns its outcome.
pub(crate) async fn execute(transfer: &DownloadTransfer, work: &mut IoRequest) -> WorkOutcome {
    transfer.execute(work).await
}

/// Polls `transfer` for discovery, executes it, and asserts that the transfer
/// accepted the result.
///
/// Panics if the poll does not return work or the discovery does not succeed.
pub(crate) async fn assert_discovery_succeeds(transfer: &DownloadTransfer) {
    let mut work = assert_ready(transfer.poll_work());
    let outcome = execute(transfer, &mut work).await;
    assert!(
        matches!(outcome, WorkOutcome::Success { .. }),
        "discovery failed: {outcome:?}"
    );
}

/// Completes discovery and accepts the first data range, if HEAD supplied no body.
///
/// Empty objects are already complete. GET-first discovery has already accepted
/// its first body, so this helper does not issue the next range.
pub(crate) async fn assert_first_range_succeeds(transfer: &DownloadTransfer) {
    assert_discovery_succeeds(transfer).await;
    if transfer.ctx().is_active() && transfer.ctx().metrics().network_rx == 0 {
        let mut range = assert_ready(transfer.poll_work());
        assert!(matches!(
            range.data_mut::<DownloadWork>(),
            DownloadWork::GetObjectRange { .. }
        ));
        assert!(matches!(
            execute(transfer, &mut range).await,
            WorkOutcome::Success { .. }
        ));
    }
}

/// A two-part disk download writing through a scripted sink, stopped where
/// `poll_work` has issued memory relief for the resident first part.
pub(crate) struct ReliefScenario {
    /// The download, its second part's claim waiting on memory.
    pub(crate) transfer: DownloadTransfer,
    /// The `DrainResident` item `poll_work` returned, not yet executed.
    pub(crate) relief: IoRequest,
    /// Holds the memory the second part needs. Dropping it admits that part.
    pub(crate) blocker: Reservation,
    /// Length of each of the object's two parts.
    pub(crate) part_size: u64,
    /// The object the S3 client serves.
    pub(crate) object: Arc<[u8]>,
    /// The destination file.
    pub(crate) path: std::path::PathBuf,
    /// The body consumer, kept for the transfer's lifetime.
    _consumer: RecvBodyConsumer,
    /// The directory holding `path`, removed on drop.
    _dir: tempfile::TempDir,
}

/// Builds a [`ReliefScenario`] whose destination writes go through `script`.
///
/// The memory budget fits two parts, and a reservation outside the transfer
/// holds one of them. The first range fills below the drain batch,
/// the second part's claim then waits on memory, and `poll_work` relieves the
/// resident first part. Each part's response carries its CRC32.
pub(crate) async fn relief_scenario(script: &Arc<WriteScript>) -> ReliefScenario {
    let part_size = 8 * 1024 * 1024;
    let object = object_bytes(2 * part_size as usize);
    let pool = crate::memory::BufferPool::builder()
        .memory_budget(crate::config::MemoryBudgetConfig::Limit(ByteSize::new(
            (2 * part_size as usize) as u64,
        )))
        .build()
        .expect("test pool");
    let blocker = pool
        .try_reserve(part_size as usize)
        .unwrap()
        .expect("the budget fits the blocker");
    let config = crate::Config::builder()
        .sdk_client(crc32_object_client(Arc::clone(&object), None))
        .part_size(crate::config::PartSize::Target(ByteSize::new(part_size)))
        .memory(crate::config::MemoryConfig::Explicit(pool))
        .build()
        .expect("valid config");
    let handle = crate::client::Handle::test_handle_tokio(config);
    let (transfer, consumer, dir) = disk_transfer(handle, &ScriptedSinkFactory(Arc::clone(script)));
    let path = dir.path().join("out");

    assert_first_range_succeeds(&transfer).await;
    let mut relief = assert_ready(transfer.poll_work());
    assert!(
        matches!(
            relief.data_mut::<DownloadWork>(),
            DownloadWork::DrainResident
        ),
        "a memory-blocked claim with a resident part schedules relief"
    );
    ReliefScenario {
        transfer,
        relief,
        blocker,
        part_size,
        object,
        path,
        _consumer: consumer,
        _dir: dir,
    }
}

/// Executes a relief item on its own thread. Relief writes are synchronous, so
/// the item completes in one poll, blocking the thread for as long as its
/// write is held.
///
/// The thread panics if the item suspends.
pub(crate) fn spawn_relief(
    transfer: &DownloadTransfer,
    mut relief: IoRequest,
) -> std::thread::JoinHandle<WorkOutcome> {
    let transfer = transfer.clone();
    std::thread::spawn(move || {
        futures_util::FutureExt::now_or_never(transfer.execute(&mut relief))
            .expect("memory relief completes without suspending")
    })
}

/// Whether `events` include the start of a finalizing resize.
pub(crate) fn finalize_started(events: &[Event]) -> bool {
    events
        .iter()
        .any(|event| matches!(event, Event::Started(Op::Finalize { .. })))
}