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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Transfer execution on owned managed partitions.

use aws_smithy_execution::{ManagedRuntime, ManagedRuntimeHandle, RuntimePartition};
use aws_smithy_http_client::pool::{ConnectionPool, DriverSpawner, Partition, PartitionId};
use aws_smithy_http_client::proxy::ProxyConfig;
use aws_smithy_http_client::tls::{rustls_provider::CryptoMode, Provider};
use aws_smithy_managed_http::client::ManagedHttpPool;
use aws_smithy_runtime_api::{
    box_error::BoxError,
    client::{
        dns::{DnsFuture, ResolveDns},
        http::SharedHttpClient,
    },
    shared::IntoShared,
};
use futures_util::FutureExt;
use std::panic::AssertUnwindSafe;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::{Duration, Instant};

use super::{ExecutionRuntime, RuntimeComponents, RuntimeHttpOptions, ScheduledWork};
use crate::runtime::sync::SubmissionGuard;
use crate::scheduler::Scheduler;
use crate::transfer::{TransferId, WorkOutcome};

/// DNS resolver that shuffles returned IPs to distribute connections across
/// S3 fleet addresses. Wraps any [`ResolveDns`] implementation.
///
/// hyper tries resolved IPs sequentially, so without shuffling all connections
/// land on the first IP. Shuffling gives each connection a random starting IP,
/// spreading load across all resolved addresses. The connection pool's
/// transport has the same sequential behavior, so shuffling still applies.
#[derive(Debug, Clone)]
struct ShufflingDnsResolver<R> {
    inner: R,
}

impl<R> ShufflingDnsResolver<R> {
    fn new(inner: R) -> Self {
        Self { inner }
    }
}

impl<R: ResolveDns + 'static> ResolveDns for ShufflingDnsResolver<R> {
    fn resolve_dns<'a>(&'a self, name: &'a str) -> DnsFuture<'a> {
        DnsFuture::new(async move {
            let mut ips = self.inner.resolve_dns(name).await?;
            fastrand::shuffle(&mut ips);
            Ok(ips)
        })
    }
}

/// How long a pooled connection may sit idle before the pool closes it.
///
/// S3 closes idle connections server-side. Retiring them first avoids reusing a
/// connection the server is closing, which fails before the request is accepted
/// and costs a retry on a fresh connection.
const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(15);

/// Build one connection pool with a partition per managed thread and return an
/// HTTP client that dispatches each request through the calling thread's
/// partition.
///
/// Each partition spawns connection establishment, protocol drivers, and idle
/// maintenance on its thread's runtime, so a connection's I/O stays on the
/// thread that opened it. Pool partition indices match execution partition indices.
///
/// When network interfaces are configured, each partition binds its
/// connections to the interface [`partition_interface`] assigns its index.
///
/// Proxy selection follows the standard environment variables (`HTTP_PROXY`,
/// `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`), matching the SDK's default HTTPS
/// client.
///
/// Returns native pool construction and partition-client errors.
fn build_http_client(
    execution: ManagedRuntimeHandle,
    options: &RuntimeHttpOptions,
) -> Result<SharedHttpClient, BoxError> {
    #[cfg(target_os = "android")]
    let dns_resolver = ShufflingDnsResolver::new(
        // Hickory reads /etc/resolv.conf on Unix. Android routes libc
        // resolution through netd and does not provide that file.
        aws_smithy_runtime::client::dns::TokioDnsResolver::new(),
    );
    #[cfg(not(target_os = "android"))]
    let dns_resolver = ShufflingDnsResolver::new(aws_smithy_dns::HickoryDnsResolver::default());

    let partitions = execution.partitions().iter().map(|target| {
        let index = target.id().index();
        let target = target.clone();
        let spawner = DriverSpawner::from_fn(move |task| {
            drop(target.spawn(task));
        });
        let partition = Partition::new(PartitionId::from_index(index), spawner);
        bind_interface(partition, index, &options.network_interfaces)
    });
    let pool = ConnectionPool::builder()
        .dns_resolver(dns_resolver)
        .idle_timeout(POOL_IDLE_TIMEOUT)
        .max_connections_per_host(options.max_connections_per_host)
        .proxy_config(ProxyConfig::from_env())
        .partitions(partitions)
        .tls_provider(Provider::Rustls(CryptoMode::AwsLc))
        .build_https()?;
    Ok(ManagedHttpPool::from_pool(execution, pool)?.into_shared())
}

/// Bind `partition` to the interface assigned to its execution index.
#[cfg(any(
    target_os = "android",
    target_os = "fuchsia",
    target_os = "illumos",
    target_os = "ios",
    target_os = "linux",
    target_os = "macos",
    target_os = "solaris",
    target_os = "tvos",
    target_os = "visionos",
    target_os = "watchos",
))]
fn bind_interface(partition: Partition, index: usize, interfaces: &[String]) -> Partition {
    match partition_interface(index, interfaces) {
        Some(interface) => partition.interface(interface),
        None => partition,
    }
}

/// Interface binding is unavailable on this platform: `partition` is returned
/// unbound and `interfaces` is ignored.
#[cfg(not(any(
    target_os = "android",
    target_os = "fuchsia",
    target_os = "illumos",
    target_os = "ios",
    target_os = "linux",
    target_os = "macos",
    target_os = "solaris",
    target_os = "tvos",
    target_os = "visionos",
    target_os = "watchos",
)))]
fn bind_interface(partition: Partition, _index: usize, _interfaces: &[String]) -> Partition {
    partition
}

/// The network interface a managed thread's partition binds to: interfaces are
/// assigned to threads round-robin in configuration order. `None` when no
/// interfaces are configured, leaving selection to OS routing.
///
/// Assignment does not derive NIC locality from execution topology; round-robin
/// spreads threads evenly across interfaces.
#[cfg(any(
    target_os = "android",
    target_os = "fuchsia",
    target_os = "illumos",
    target_os = "ios",
    target_os = "linux",
    target_os = "macos",
    target_os = "solaris",
    target_os = "tvos",
    target_os = "visionos",
    target_os = "watchos",
))]
fn partition_interface(index: usize, interfaces: &[String]) -> Option<&str> {
    if interfaces.is_empty() {
        return None;
    }
    Some(&interfaces[index % interfaces.len()])
}

/// Selects the less loaded of two randomly sampled partitions.
struct DispatchRouter;

impl DispatchRouter {
    fn select(&self, loads: &[Arc<AtomicUsize>]) -> usize {
        let len = loads.len();
        assert!(len > 0, "no execution partitions");
        if len == 1 {
            return 0;
        }
        let a = fastrand::usize(..len);
        let mut b = fastrand::usize(..len - 1);
        if b >= a {
            b += 1;
        }
        if loads[a].load(Ordering::Relaxed) <= loads[b].load(Ordering::Relaxed) {
            a
        } else {
            b
        }
    }
}

/// Accounts for a submission until execution finishes or its future is dropped.
struct InFlight(Arc<AtomicUsize>);

impl InFlight {
    fn acquire(load: Arc<AtomicUsize>) -> Self {
        load.fetch_add(1, Ordering::Relaxed);
        Self(load)
    }
}

impl Drop for InFlight {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::Relaxed);
    }
}

/// Result of executing a single work item.
enum ExecuteResult {
    Completed(WorkOutcome, Duration),
    Panicked,
}

/// Execute a single work item, mirroring the `worker_loop` semantics from
/// `tokio_mt` but for one-shot per-task spawning.
async fn execute_work(work: &mut ScheduledWork, scheduler: &Scheduler) -> ExecuteResult {
    scheduler.on_dispatch();
    let tid = work.descriptor.id();
    work.descriptor.work_started();

    if work.descriptor.is_terminal() {
        tracing::trace!(target: crate::telemetry::TARGET_EXECUTION, %tid, "skipped (terminal)");
        return ExecuteResult::Completed(WorkOutcome::Cancelled, Duration::ZERO);
    }

    tracing::trace!(target: crate::telemetry::TARGET_EXECUTION, %tid, "executing");
    let transfer = work.descriptor.transfer();
    let started = Instant::now();

    let token = work.descriptor.cancellation_token().clone();
    let outcome = AssertUnwindSafe(async {
        tokio::select! {
            biased;
            _ = token.cancelled() => WorkOutcome::Cancelled,
            outcome = transfer.execute(&mut work.item) => outcome,
        }
    })
    .catch_unwind()
    .await;

    match outcome {
        Ok(outcome) => {
            tracing::trace!(target: crate::telemetry::TARGET_EXECUTION, %tid, ?outcome, "completed");
            ExecuteResult::Completed(outcome, started.elapsed())
        }
        Err(_panic) => {
            tracing::error!(target: crate::telemetry::TARGET_EXECUTION, %tid, "panic in transfer execute");
            ExecuteResult::Panicked
        }
    }
}

/// Owns managed execution while retaining TM-local dispatch and accounting.
pub(crate) struct ManagedExecution {
    handle: Weak<crate::client::Handle>,
    owner: Mutex<Option<ManagedRuntime>>,
    completion: crate::ShutdownCompletion,
    partitions: Box<[RuntimePartition]>,
    in_flight: Box<[Arc<AtomicUsize>]>,
    router: DispatchRouter,
    components: RuntimeComponents,
}

impl std::fmt::Debug for ManagedExecution {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ManagedExecution")
            .field("partitions", &self.partitions)
            .finish_non_exhaustive()
    }
}

/// Builds only the transport that will be installed, before client initialization.
pub(crate) fn prepare_components(
    owner: &ManagedRuntime,
    http: Option<RuntimeHttpOptions>,
) -> Result<RuntimeComponents, BoxError> {
    let http_client = match http {
        Some(options) => Some(build_http_client(owner.handle(), &options)?),
        None => None,
    };
    Ok(RuntimeComponents::managed(http_client))
}

impl ManagedExecution {
    pub(crate) fn new(
        handle: Weak<crate::client::Handle>,
        owner: ManagedRuntime,
        components: RuntimeComponents,
    ) -> Self {
        let completion = crate::ShutdownCompletion::new(owner.shutdown_completion());
        let partitions: Box<[_]> = owner.handle().partitions().to_vec().into_boxed_slice();
        let in_flight = partitions
            .iter()
            .map(|_| Arc::new(AtomicUsize::new(0)))
            .collect();
        Self {
            handle,
            owner: Mutex::new(Some(owner)),
            completion,
            partitions,
            in_flight,
            router: DispatchRouter,
            components,
        }
    }

    #[cfg(test)]
    pub(crate) fn partition_count(&self) -> usize {
        self.partitions.len()
    }

    #[cfg(test)]
    pub(crate) fn for_test(handle: Weak<crate::client::Handle>, max_partitions: usize) -> Self {
        let topology = aws_smithy_execution::topology::Topology::detect()
            .unwrap()
            .with_max_placements(max_partitions);
        let owner = ManagedRuntime::builder()
            .topology(topology)
            .pin_threads(false)
            .build()
            .unwrap();
        let components = prepare_components(&owner, None).unwrap();
        Self::new(handle, owner, components)
    }
}

impl ExecutionRuntime for ManagedExecution {
    fn dispatch(&self, batch: &mut SubmissionGuard<'_, ScheduledWork>) {
        for mut work in batch.drain() {
            let index = self.router.select(&self.in_flight);
            let flight = InFlight::acquire(self.in_flight[index].clone());
            let handle = self.handle.clone();
            let tid = work.descriptor.id();
            tracing::trace!(
                target: crate::telemetry::TARGET_EXECUTION,
                %tid,
                partition = index,
                "dispatching to managed partition",
            );
            let task = self.partitions[index].spawn(async move {
                let flight = flight;
                let Some(h) = handle.upgrade() else {
                    return;
                };
                let result = execute_work(&mut work, &h.scheduler).await;
                drop(flight);
                match result {
                    ExecuteResult::Completed(outcome, elapsed) => {
                        h.scheduler.on_completion(work, outcome, elapsed);
                    }
                    ExecuteResult::Panicked => {
                        h.scheduler.on_panic(work);
                    }
                }
            });
            drop(task);
        }
    }

    fn shutdown(&self) {
        let owner = self
            .owner
            .lock()
            .expect("managed owner lock poisoned")
            .take();
        drop(owner);
    }

    fn shutdown_completion(&self) -> Option<crate::ShutdownCompletion> {
        Some(self.completion.clone())
    }

    fn remove_pending_for_transfer(&self, _id: TransferId) -> usize {
        // Submitted tasks check terminal state and transfer cancellation.
        0
    }

    fn components(&self) -> &RuntimeComponents {
        &self.components
    }
}

#[cfg(all(test, not(miri)))]
mod tests {
    use super::*;

    #[cfg(any(
        target_os = "android",
        target_os = "fuchsia",
        target_os = "illumos",
        target_os = "ios",
        target_os = "linux",
        target_os = "macos",
        target_os = "solaris",
        target_os = "tvos",
        target_os = "visionos",
        target_os = "watchos",
    ))]
    #[test]
    fn partition_interface_assigns_round_robin() {
        let interfaces = ["ens5".to_string(), "ens6".to_string()];
        let assigned: Vec<_> = (0..5)
            .map(|i| partition_interface(i, &interfaces))
            .collect();
        assert_eq!(
            assigned,
            [
                Some("ens5"),
                Some("ens6"),
                Some("ens5"),
                Some("ens6"),
                Some("ens5")
            ]
        );
    }

    #[cfg(any(
        target_os = "android",
        target_os = "fuchsia",
        target_os = "illumos",
        target_os = "ios",
        target_os = "linux",
        target_os = "macos",
        target_os = "solaris",
        target_os = "tvos",
        target_os = "visionos",
        target_os = "watchos",
    ))]
    #[test]
    fn partition_interface_unbound_without_interfaces() {
        assert_eq!(partition_interface(0, &[]), None);
        assert_eq!(partition_interface(3, &[]), None);
    }

    fn loads(values: &[usize]) -> Vec<Arc<AtomicUsize>> {
        values
            .iter()
            .map(|value| Arc::new(AtomicUsize::new(*value)))
            .collect()
    }

    fn test_handle(max_partitions: usize) -> (Arc<crate::client::Handle>, Arc<ManagedExecution>) {
        let holder = Arc::new(std::sync::OnceLock::new());
        let captured = holder.clone();
        let handle = crate::client::Handle::new_for_test_with_runtime(
            crate::Config::builder()
                .sdk_client(aws_smithy_mocks::mock_client!(aws_sdk_s3, []))
                .build()
                .expect("valid config"),
            Arc::new(crate::scheduler::FixedConcurrency::new(max_partitions)),
            move |weak| {
                let execution = Arc::new(ManagedExecution::for_test(weak, max_partitions));
                captured.set(execution.clone()).ok();
                execution
            },
        );
        let execution = holder.get().unwrap().clone();
        (handle, execution)
    }

    #[test]
    fn partitions_start_and_shutdown() {
        let (handle, execution) = test_handle(4);
        assert!(!execution.partitions.is_empty());
        assert!(execution.partitions.len() <= 4);
        let expected = execution
            .owner
            .lock()
            .unwrap()
            .as_ref()
            .unwrap()
            .handle()
            .topology()
            .placements()
            .len();
        assert_eq!(execution.partitions.len(), expected);
        execution.shutdown();
        drop(execution);
        drop(handle);
    }

    #[test]
    fn shutdown_is_idempotent() {
        let (handle, execution) = test_handle(2);
        execution.shutdown();
        execution.shutdown();
        assert!(execution.owner.lock().unwrap().is_none());
        drop(execution);
        drop(handle);
    }

    #[test]
    fn drop_without_shutdown() {
        let owner = ManagedRuntime::builder()
            .pin_threads(false)
            .build()
            .unwrap();
        let partition = owner.handle().partitions()[0].clone();
        let execution = ManagedExecution::new(Weak::new(), owner, RuntimeComponents::default());
        let (tx, rx) = std::sync::mpsc::channel();
        let finished = Completion(tx);
        let task = partition.spawn(async move {
            let _finished = finished;
            std::future::pending::<()>().await;
        });
        drop(execution);
        drop(task);
        rx.recv_timeout(Duration::from_secs(5)).unwrap();
    }

    struct Completion(std::sync::mpsc::Sender<()>);
    impl Drop for Completion {
        fn drop(&mut self) {
            let _ = self.0.send(());
        }
    }

    // ref: V2429410200
    /// Dropping the last client handle on a managed thread shuts the runtime
    /// down: the drop returns without panicking, and shutdown completion
    /// confirms that every managed thread, including the one that ran the
    /// drop, has been joined.
    ///
    /// A transfer's work item can hold the last handle, and once the scheduler
    /// releases finished transfers this drop runs on whichever managed thread
    /// retires that item, so the transfer manager depends on it.
    #[tokio::test]
    async fn last_handle_dropped_on_a_managed_thread_shuts_the_runtime_down() {
        const TIMEOUT: Duration = Duration::from_secs(5);
        let (handle, execution) = test_handle(2);
        let completion = execution
            .shutdown_completion()
            .expect("managed execution reports shutdown completion");
        let partition = execution.partitions[0].clone();
        drop(execution);

        let (dropped_tx, dropped_rx) = std::sync::mpsc::channel();
        drop(partition.spawn(async move {
            let dropped = std::panic::catch_unwind(AssertUnwindSafe(|| drop(handle)));
            dropped_tx.send(dropped.is_ok()).unwrap();
        }));
        assert!(
            dropped_rx
                .recv_timeout(TIMEOUT)
                .expect("the handle drop did not return"),
            "dropping the last handle on a managed thread panicked"
        );
        tokio::time::timeout(TIMEOUT, completion.wait())
            .await
            .expect("managed threads were not joined")
            .expect("managed thread shutdown failed");
    }

    #[test]
    fn router_selects_least_loaded() {
        let router = DispatchRouter;
        let loads = loads(&[5, 2, 8, 3]);
        let mut selected = [0usize; 4];
        for _ in 0..1000 {
            selected[router.select(&loads)] += 1;
        }
        assert_eq!(selected[2], 0);
        assert!(selected[1] > selected[2]);
    }

    #[test]
    fn router_single_partition() {
        assert_eq!(DispatchRouter.select(&loads(&[5])), 0);
    }

    #[test]
    fn router_two_partitions_prefers_lighter() {
        let loads = loads(&[10, 0]);
        for _ in 0..100 {
            assert_eq!(DispatchRouter.select(&loads), 1);
        }
    }

    #[test]
    fn cancelled_submission_releases_load() {
        let owner = ManagedRuntime::builder()
            .pin_threads(false)
            .build()
            .unwrap();
        let load = Arc::new(AtomicUsize::new(0));
        let flight = InFlight::acquire(load.clone());
        let task = owner.handle().partitions()[0].spawn(async move {
            let _flight = flight;
            std::future::pending::<()>().await;
        });
        assert_eq!(load.load(Ordering::Relaxed), 1);
        task.abort();
        tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap()
            .block_on(async {
                assert!(task.await.unwrap_err().is_cancelled());
            });
        assert_eq!(load.load(Ordering::Relaxed), 0);
    }
}