aria2-core 0.3.12

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
// HTTP client pool for connection reuse across multiple downloads.
//
// Provides a singleton HTTP client that can be shared across multiple
// DownloadCommand instances to reduce connection establishment overhead
// and improve memory efficiency.

use once_cell::sync::Lazy;
use reqwest::Client;
use std::net::IpAddr;
use std::sync::Arc;
use std::sync::Once;
use std::time::Duration;

use crate::http::HttpVersion;
use dashmap::DashMap;

const HTTP2_DOWNLOAD_STREAM_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
const HTTP2_DOWNLOAD_CONNECTION_WINDOW_SIZE: u32 = 16 * 1024 * 1024;

/// Configure receive flow control for HTTP/2 response bodies.
///
/// reqwest's default 64 KiB stream and connection windows throttle large
/// downloads on higher-latency links. Keep the connection window bounded at
/// 16 MiB while giving each response stream enough room to keep the transport
/// busy. Measurements against the issue's GitHub asset show that increasing
/// only one window does not remove the throughput limit.
pub(crate) fn configure_http2_download_client(
    builder: reqwest::ClientBuilder,
) -> reqwest::ClientBuilder {
    builder
        .http2_initial_stream_window_size(Some(HTTP2_DOWNLOAD_STREAM_WINDOW_SIZE))
        .http2_initial_connection_window_size(Some(HTTP2_DOWNLOAD_CONNECTION_WINDOW_SIZE))
}

/// Ensure the rustls ring crypto provider is installed.
///
/// Required when reqwest is built with `rustls-no-provider` (no aws-lc-rs).
/// Must be called before any `reqwest::Client` is constructed.
///
/// Note: `install_default()` returns Err if a provider is already installed
/// (e.g., by another module's initializer). That is fine — we only need to
/// ensure a provider is present, not that we installed it.
pub fn ensure_rustls_provider() {
    static INIT: Once = Once::new();
    INIT.call_once(|| {
        let _ = rustls::crypto::ring::default_provider().install_default();
    });
}

/// Global HTTP client instance for connection reuse.
///
/// Redirects are disabled (`Policy::none`) because we handle them
/// manually in the download flow, matching C++ aria2 behavior:
/// - Update the RequestGroup URI list with redirect targets
/// - Feed redirect results back to the URI selector
/// - Track redirect count per-request
/// - Apply method change rules (301/302/303 → GET; 307/308 → preserve)
static GLOBAL_CLIENT: Lazy<Arc<Client>> = Lazy::new(|| {
    ensure_rustls_provider();
    Arc::new(build_bound_client(None, false, HttpVersion::Auto))
});

/// Get the global shared HTTP client instance.
///
/// This client is shared across all downloads, enabling:
/// - TCP connection reuse
/// - Reduced memory footprint
/// - Better performance for concurrent downloads
pub fn get_global_client() -> Arc<Client> {
    GLOBAL_CLIENT.clone()
}

type BoundClientKey = (Option<IpAddr>, bool, HttpVersion);
type BoundClients = DashMap<BoundClientKey, Arc<Client>>;
type BoundDownloadClientKey = (Option<IpAddr>, bool, usize, HttpVersion);
type BoundDownloadClients = DashMap<BoundDownloadClientKey, Arc<Vec<Client>>>;

static BOUND_CLIENTS: Lazy<BoundClients> = Lazy::new(DashMap::new);
static BOUND_DOWNLOAD_CLIENTS: Lazy<BoundDownloadClients> = Lazy::new(DashMap::new);

/// Return a process-wide reusable reqwest client for a source address.
///
/// reqwest fixes `local_address` on a client, so each configured source gets
/// one lazily-created connection pool. Clients are reused by every download
/// using the same source and gzip mode.
pub fn get_bound_client(local_address: Option<IpAddr>, accept_gzip: bool) -> Arc<Client> {
    get_bound_client_with_version(local_address, accept_gzip, HttpVersion::Auto)
}

/// Return a reusable client configured for the requested HTTP version.
pub(crate) fn get_bound_client_with_version(
    local_address: Option<IpAddr>,
    accept_gzip: bool,
    http_version: HttpVersion,
) -> Arc<Client> {
    if local_address.is_none() && !accept_gzip && http_version == HttpVersion::Auto {
        return get_global_client();
    }
    let key = (local_address, accept_gzip, http_version);
    if let Some(client) = BOUND_CLIENTS.get(&key) {
        return Arc::clone(client.value());
    }

    let client = Arc::new(build_bound_client(local_address, accept_gzip, http_version));
    let entry = BOUND_CLIENTS
        .entry(key)
        .or_insert_with(|| Arc::clone(&client));
    Arc::clone(entry.value())
}

/// Return independent clients for concurrent Range traffic using one
/// consistent protocol selection across every pool.
pub(crate) fn get_bound_download_clients_with_version(
    local_address: Option<IpAddr>,
    accept_gzip: bool,
    session_count: usize,
    http_version: HttpVersion,
) -> Arc<Vec<Client>> {
    let session_count = session_count.clamp(1, crate::constants::DEFAULT_MAX_CONNECTION_PER_SERVER);
    let key = (local_address, accept_gzip, session_count, http_version);
    if let Some(clients) = BOUND_DOWNLOAD_CLIENTS.get(&key) {
        return Arc::clone(clients.value());
    }

    let primary = get_bound_client_with_version(local_address, accept_gzip, http_version);
    let mut clients = Vec::with_capacity(session_count);
    clients.push(primary.as_ref().clone());
    clients.extend(
        (1..session_count).map(|_| build_bound_client(local_address, accept_gzip, http_version)),
    );
    let clients = Arc::new(clients);
    let entry = BOUND_DOWNLOAD_CLIENTS
        .entry(key)
        .or_insert_with(|| Arc::clone(&clients));
    Arc::clone(entry.value())
}

/// Create a custom HTTP client with specific configuration.
///
/// Use this when you need client settings different from the global defaults.
/// Redirects are disabled — they are handled manually in the download flow
/// matching C++ aria2 behavior.
pub fn create_custom_client(
    connect_timeout: Duration,
    timeout: Duration,
    pool_max_idle_per_host: usize,
) -> Arc<Client> {
    ensure_rustls_provider();
    let builder = Client::builder()
        .connect_timeout(connect_timeout)
        .timeout(timeout)
        .gzip(false)
        .user_agent(crate::constants::USER_AGENT)
        .redirect(reqwest::redirect::Policy::none())
        .pool_max_idle_per_host(pool_max_idle_per_host)
        .pool_idle_timeout(Some(Duration::from_secs(
            crate::constants::HTTP_CLIENT_POOL_IDLE_TIMEOUT_SECS,
        )))
        .tcp_keepalive(Some(Duration::from_secs(
            crate::constants::HTTP_DEFAULT_TCP_KEEPALIVE_SECS,
        )))
        .tcp_nodelay(true);
    let client = HttpVersion::Auto
        .configure(configure_http2_download_client(builder))
        .build()
        .expect("Failed to create custom HTTP client");

    Arc::new(client)
}

fn build_bound_client(
    local_address: Option<IpAddr>,
    accept_gzip: bool,
    http_version: HttpVersion,
) -> Client {
    ensure_rustls_provider();
    let mut builder = Client::builder()
        .connect_timeout(Duration::from_secs(
            crate::constants::HTTP_DEFAULT_CONNECT_TIMEOUT_SECS,
        ))
        .gzip(accept_gzip)
        .user_agent(crate::constants::USER_AGENT)
        .redirect(reqwest::redirect::Policy::none())
        .pool_max_idle_per_host(crate::constants::HTTP_CLIENT_POOL_MAX_IDLE_PER_HOST)
        .pool_idle_timeout(Some(Duration::from_secs(
            crate::constants::HTTP_CLIENT_POOL_IDLE_TIMEOUT_SECS,
        )))
        .tcp_keepalive(Some(Duration::from_secs(
            crate::constants::HTTP_DEFAULT_TCP_KEEPALIVE_SECS,
        )))
        .tcp_nodelay(true);
    if let Some(address) = local_address {
        builder = builder.local_address(address);
    }
    http_version
        .configure(configure_http2_download_client(builder))
        .build()
        .expect("bound HTTP client construction should be infallible")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_global_client_is_shared() {
        let client1 = get_global_client();
        let client2 = get_global_client();

        // Both should point to the same client instance
        assert!(Arc::ptr_eq(&client1, &client2));
    }

    #[test]
    fn test_custom_client_is_different() {
        let global = get_global_client();
        let custom = create_custom_client(Duration::from_secs(10), Duration::from_secs(60), 8);

        // Should be different instances
        assert!(!Arc::ptr_eq(&global, &custom));
    }

    #[test]
    fn bound_clients_are_reused_per_source_and_gzip_mode() {
        let source = Some("127.0.0.1".parse().unwrap());
        let first = get_bound_client(source, false);
        let second = get_bound_client(source, false);
        let gzip = get_bound_client(source, true);
        assert!(Arc::ptr_eq(&first, &second));
        assert!(!Arc::ptr_eq(&first, &gzip));
    }

    #[test]
    fn download_client_pool_cache_is_keyed_by_session_count() {
        let source = Some("127.0.0.55".parse().unwrap());
        let two_sessions =
            get_bound_download_clients_with_version(source, false, 2, HttpVersion::Auto);
        let two_sessions_again =
            get_bound_download_clients_with_version(source, false, 2, HttpVersion::Auto);
        let four_sessions =
            get_bound_download_clients_with_version(source, false, 4, HttpVersion::Auto);

        assert_eq!(two_sessions.len(), 2);
        assert_eq!(four_sessions.len(), 4);
        assert!(Arc::ptr_eq(&two_sessions, &two_sessions_again));
        assert!(!Arc::ptr_eq(&two_sessions, &four_sessions));
    }

    #[tokio::test]
    async fn bound_client_reuses_one_real_tcp_connection() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let source = "127.0.0.3".parse().unwrap();
        let listener = TcpListener::bind((source, 0)).await.unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut stream, peer) = listener.accept().await.unwrap();
            for _ in 0..2 {
                let mut request = Vec::new();
                loop {
                    let mut byte = [0u8; 1];
                    stream.read_exact(&mut byte).await.unwrap();
                    request.push(byte[0]);
                    if request.ends_with(b"\r\n\r\n") {
                        break;
                    }
                }
                stream
                    .write_all(
                        b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: keep-alive\r\n\r\nok",
                    )
                    .await
                    .unwrap();
            }
            peer
        });

        let client = get_bound_client(Some(source), false);
        for path in ["/one", "/two"] {
            let response = client
                .get(format!("http://{address}{path}"))
                .send()
                .await
                .unwrap();
            assert_eq!(response.text().await.unwrap(), "ok");
        }
        assert_eq!(server.await.unwrap().ip(), source);
    }

    #[tokio::test]
    async fn configured_download_client_receives_concurrent_http2_ranges() {
        use std::convert::Infallible;
        use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

        use bytes::Bytes;
        use http_body_util::Full;
        use hyper::{
            Request, Response,
            body::Incoming,
            header::{CONTENT_RANGE, RANGE},
            server::conn::http2,
            service::service_fn,
        };
        use hyper_util::rt::{TokioExecutor, TokioIo};
        use tokio::net::TcpListener;

        const SESSION_COUNT: usize = 4;
        const SEGMENT_COUNT: usize = 16;
        const SEGMENT_SIZE: usize = 1024 * 1024;
        const TOTAL_SIZE: usize = SEGMENT_COUNT * SEGMENT_SIZE;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let expected = Bytes::from((0..TOTAL_SIZE).map(|i| (i % 251) as u8).collect::<Vec<_>>());
        let server_expected = expected.clone();
        let served_per_connection = Arc::new(
            (0..SESSION_COUNT)
                .map(|_| AtomicUsize::new(0))
                .collect::<Vec<_>>(),
        );
        let server_served_per_connection = Arc::clone(&served_per_connection);
        let accepted_connections = Arc::new(AtomicUsize::new(0));
        let server_accepted_connections = Arc::clone(&accepted_connections);
        let server = tokio::spawn(async move {
            let mut connections = tokio::task::JoinSet::new();
            for connection_index in 0..SESSION_COUNT {
                let (stream, _) = listener.accept().await.unwrap();
                server_accepted_connections.fetch_add(1, AtomicOrdering::Relaxed);
                let body = server_expected.clone();
                let served_per_connection = Arc::clone(&server_served_per_connection);
                let service = service_fn(move |request: Request<Incoming>| {
                    let body = body.clone();
                    let served_per_connection = Arc::clone(&served_per_connection);
                    async move {
                        let index = request
                            .uri()
                            .path()
                            .rsplit('/')
                            .next()
                            .unwrap()
                            .parse::<usize>()
                            .unwrap();
                        let start = index * SEGMENT_SIZE;
                        let end = start + SEGMENT_SIZE - 1;
                        let expected_range = format!("bytes={start}-{end}");
                        assert_eq!(
                            request.headers().get(RANGE).unwrap(),
                            &expected_range,
                            "each HTTP/2 stream should carry its assigned byte range"
                        );
                        served_per_connection[connection_index]
                            .fetch_add(1, AtomicOrdering::Relaxed);
                        let response_body = body.slice(start..end + 1);
                        Ok::<_, Infallible>(
                            Response::builder()
                                .status(reqwest::StatusCode::PARTIAL_CONTENT)
                                .header(CONTENT_RANGE, format!("bytes {start}-{end}/{TOTAL_SIZE}"))
                                .body(Full::new(response_body))
                                .unwrap(),
                        )
                    }
                });
                connections.spawn(async move {
                    http2::Builder::new(TokioExecutor::new())
                        .serve_connection(TokioIo::new(stream), service)
                        .await
                        .unwrap();
                });
            }
            while let Some(connection) = connections.join_next().await {
                connection.unwrap();
            }
        });

        ensure_rustls_provider();
        let clients = (0..SESSION_COUNT)
            .map(|_| {
                configure_http2_download_client(Client::builder().http2_prior_knowledge())
                    .build()
                    .unwrap()
            })
            .collect::<Vec<_>>();
        let initial_responses = futures::future::join_all((0..SESSION_COUNT).map(|index| {
            let client = clients[index].clone();
            async move {
                let start = index * SEGMENT_SIZE;
                let end = start + SEGMENT_SIZE - 1;
                let response = client
                    .get(format!("http://{address}/segment/{index}"))
                    .header(RANGE, format!("bytes={start}-{end}"))
                    .send()
                    .await
                    .unwrap();
                assert_eq!(response.version(), reqwest::Version::HTTP_2);
                assert_eq!(response.status(), reqwest::StatusCode::PARTIAL_CONTENT);
                response
            }
        }))
        .await;

        let transfers = (SESSION_COUNT..SEGMENT_COUNT).map(|index| {
            let client = clients[index % SESSION_COUNT].clone();
            let expected = expected.clone();
            async move {
                let start = index * SEGMENT_SIZE;
                let end = start + SEGMENT_SIZE - 1;
                let response = client
                    .get(format!("http://{address}/segment/{index}"))
                    .header(RANGE, format!("bytes={start}-{end}"))
                    .send()
                    .await
                    .unwrap();
                assert_eq!(response.version(), reqwest::Version::HTTP_2);
                assert_eq!(response.status(), reqwest::StatusCode::PARTIAL_CONTENT);
                let received = response.bytes().await.unwrap();
                assert_eq!(received.as_ref(), &expected[start..=end]);
            }
        });
        tokio::time::timeout(
            std::time::Duration::from_secs(10),
            futures::future::join_all(transfers),
        )
        .await
        .expect("concurrent HTTP/2 range responses should not stall");
        for (index, response) in initial_responses.into_iter().enumerate() {
            let start = index * SEGMENT_SIZE;
            let end = start + SEGMENT_SIZE;
            let received = response.bytes().await.unwrap();
            assert_eq!(received.as_ref(), &expected[start..end]);
        }
        drop(clients);
        tokio::time::timeout(std::time::Duration::from_secs(10), server)
            .await
            .expect("HTTP/2 sessions should shut down after clients are dropped")
            .unwrap();
        assert_eq!(
            accepted_connections.load(AtomicOrdering::Relaxed),
            SESSION_COUNT,
            "four independent clients should establish exactly four TCP sessions"
        );
        assert_eq!(
            served_per_connection
                .iter()
                .map(|count| count.load(AtomicOrdering::Relaxed))
                .collect::<Vec<_>>(),
            vec![SEGMENT_COUNT / SESSION_COUNT; SESSION_COUNT],
            "each HTTP/2 TCP session should multiplex four Range streams"
        );
    }
}