aria2-core 0.3.14

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
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Task spawner: creates tokio tasks from promoted download groups.
//!
//! When the engine promotes a group from reserved to active, it needs to
//! create the appropriate `Command` implementation (DownloadCommand,
//! BtDownloadCommand, etc.) and spawn it as a tokio task. This module
//! handles that dispatch, wiring up the completion channel so the engine
//! can track when tasks finish.

use std::sync::Arc;
use tracing::{debug, warn};

use super::command::Command;
use super::engine_command::TaskResult;
use super::protocol_adapter::{ProtocolAdapterRegistry, ProtocolCommandRequest, ProtocolServices};
use crate::error::Aria2Error;
use crate::network::ConnectionContext;
use crate::request::request_group::{DownloadOptions, GroupId, RequestGroup};
use crate::util::rwlock_ext::RwLockRecover;
use tokio_util::sync::CancellationToken;

/// Shared services required while constructing a command.
pub(crate) struct CommandDependencies {
    pub(crate) services: ProtocolServices,
    pub(crate) protocol_adapters: Arc<ProtocolAdapterRegistry>,
}

/// Spawns a download command as a tokio task and wires up the completion
/// channel. Returns the `JoinHandle` for task management.
///
/// The command is selected by `ProtocolAdapterRegistry` from the group's
/// metadata and first URI, then constructed with the shared engine services.
///
/// Before spawning, increments `RequestGroup::num_commands`
/// (mirrors C++ AbstractCommand constructor).
///
/// After the task completes, sends `(GID, generation, TaskResult)` via the completion
/// channel so the engine can decrement `num_commands` and check for demotion.
pub(crate) fn spawn_download_task(
    group: Arc<std::sync::RwLock<RequestGroup>>,
    dependencies: CommandDependencies,
    generation: u64,
    completion_tx: tokio::sync::mpsc::UnboundedSender<(GroupId, u64, TaskResult)>,
) -> Option<(tokio::task::JoinHandle<()>, CancellationToken)> {
    let gid = group.recover().gid();
    let uris = group.recover().uris().to_vec();
    let options = group.recover().options_arc();

    // Increment command counter BEFORE spawning.
    group.recover().inc_commands();

    // Determine the first URI to decide which command type to create.
    let first_uri = match uris.first() {
        Some(u) => u.clone(),
        None => {
            warn!(gid = gid.value(), "No URIs in group, cannot spawn task");
            group.recover().dec_commands();
            return None;
        }
    };

    let shutdown = CancellationToken::new();
    let task_shutdown = shutdown.clone();
    let completion_tx = completion_tx.clone();

    // Command construction may perform DNS resolution and build protocol
    // clients. Keep that work in the tracked task so the single-threaded
    // engine loop can continue processing pause/remove commands while a
    // resolver or a slow protocol constructor is waiting.
    let handle = tokio::spawn(async move {
        let (result, connection_context) = tokio::select! {
            command_result = create_command_for_group(
                Arc::clone(&group),
                first_uri.to_string(),
                options,
                dependencies,
            ) => {
                match command_result {
                    Ok(mut cmd) => {
                        // Once a command has been constructed, its protocol
                        // loop owns lifecycle cleanup. Force-halt and remove
                        // already update the RequestGroup, so dropping the
                        // execute future here would bypass writer flushing and
                        // protocol-specific checkpoints.
                        let result = cmd.execute().await;
                        if result.is_err() {
                            cmd.shutdown().await;
                        }
                        (result, cmd.connection_context())
                    }
                    Err(error) => (Err(error), None),
                }
            }
            _ = task_shutdown.cancelled() => {
                (Err(Aria2Error::DownloadFailed("download shutdown requested".into())), None)
            }
        };
        let task_result = match result {
            Ok(()) => {
                debug!(gid = gid.value(), "Download task completed successfully");
                TaskResult::Success
            }
            Err(Aria2Error::Recoverable(recoverable)) => {
                warn!(
                    gid = gid.value(),
                    "Download task failed with recoverable error"
                );
                failed_task_result(Aria2Error::Recoverable(recoverable), connection_context)
            }
            Err(e) => {
                warn!(gid = gid.value(), error = %e, "Download task failed");
                failed_task_result(e, connection_context)
            }
        };

        // Send completion notification. If the channel is closed, the engine
        // has already shut down; just log and move on.
        if completion_tx.send((gid, generation, task_result)).is_err() {
            debug!(
                gid = gid.value(),
                "Completion channel closed, engine likely shut down"
            );
        }
    });

    Some((handle, shutdown))
}

fn failed_task_result(
    error: Aria2Error,
    connection_context: Option<ConnectionContext>,
) -> TaskResult {
    match connection_context {
        Some(connection_context) => TaskResult::FailedWithContext {
            error,
            connection_context,
        },
        None => TaskResult::Failed(error),
    }
}

/// Build the protocol command inside the tracked task.
///
/// The registry gives metadata adapters and URI adapters the same construction
/// seam. Keeping construction inside the tracked task ensures DNS and client
/// setup remain cancellable without blocking the engine loop.
async fn create_command_for_group(
    group: Arc<std::sync::RwLock<RequestGroup>>,
    first_uri: String,
    options: Arc<DownloadOptions>,
    dependencies: CommandDependencies,
) -> crate::error::Result<Box<dyn Command>> {
    create_command_for_uri(&first_uri, group, &options, dependencies).await
}

/// Select a registered adapter and preserve the engine-owned `RequestGroup`.
async fn create_command_for_uri(
    uri: &str,
    group: Arc<std::sync::RwLock<RequestGroup>>,
    options: &DownloadOptions,
    dependencies: CommandDependencies,
) -> crate::error::Result<Box<dyn Command>> {
    dependencies
        .protocol_adapters
        .create(
            ProtocolCommandRequest {
                group,
                first_uri: uri.to_string(),
                options: Arc::new(options.clone()),
            },
            &dependencies.services,
        )
        .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dns::dns_cache::DnsCache;
    use crate::network::OutboundNetworkPolicy;
    use crate::request::request_group::{DownloadOptions, GroupId, RequestGroup};

    fn dependencies(dns_cache: Arc<tokio::sync::Mutex<DnsCache>>) -> CommandDependencies {
        CommandDependencies {
            services: ProtocolServices {
                dns_cache,
                outbound_network_policy: Arc::new(OutboundNetworkPolicy::direct()),
                global_limiter: None,
            },
            protocol_adapters: Arc::new(ProtocolAdapterRegistry::builtins(
                Arc::new(crate::ftp::connection_pool::FtpConnectionPool::new(4)),
                #[cfg(feature = "bittorrent")]
                crate::engine::bittorrent::command_adapter::BtCommandServices {
                    public_tracker_catalog: Arc::new(
                        aria2_protocol::bittorrent::tracker::public_list::PublicTrackerList::new(),
                    ),
                    bt_registry: Arc::new(std::sync::RwLock::new(
                        crate::engine::bittorrent::registry::BtRegistry::new(),
                    )),
                    bt_listener: Arc::new(
                        crate::engine::bittorrent::peer::listener::BtPeerListenerManager::new(),
                    ),
                    lpd_manager: Arc::new(
                        crate::engine::bittorrent::discovery::lpd::LpdManager::new(),
                    ),
                    open_file_budget: crate::filesystem::open_file_budget::OpenFileBudget::new(100),
                },
            )),
        }
    }

    #[tokio::test]
    async fn async_dns_false_uses_the_protocol_default_resolver_path() {
        for scheme in ["http", "ftp"] {
            let cache = Arc::new(tokio::sync::Mutex::new(DnsCache::new()));
            let options = DownloadOptions {
                async_dns: false,
                ..DownloadOptions::default()
            };
            let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
                GroupId::new(70),
                vec![format!("{scheme}://localhost/file.bin")],
                options.clone(),
            )));

            let _command = create_command_for_uri(
                &format!("{scheme}://localhost/file.bin"),
                group,
                &options,
                dependencies(Arc::clone(&cache)),
            )
            .await
            .expect("command construction should not require the shared DNS cache");

            assert_eq!(
                cache.lock().await.len(),
                0,
                "async-dns=false must not pre-resolve {scheme} through the shared cache"
            );
        }

        let cache = Arc::new(tokio::sync::Mutex::new(DnsCache::new()));
        let options = DownloadOptions {
            async_dns: false,
            http_proxy: Some("http://localhost:8080".to_string()),
            ..DownloadOptions::default()
        };
        let uri = "http://origin.invalid/file.bin";
        let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(72),
            vec![uri.to_string()],
            options.clone(),
        )));
        let _command =
            create_command_for_uri(uri, group, &options, dependencies(Arc::clone(&cache)))
                .await
                .expect("proxy command construction should use the default resolver path");
        assert_eq!(
            cache.lock().await.len(),
            0,
            "async-dns=false must not query the shared resolver for a proxy or origin"
        );

        let cache = Arc::new(tokio::sync::Mutex::new(DnsCache::new()));
        let options = DownloadOptions {
            async_dns: false,
            http_proxy: Some("http://localhost:8080".to_string()),
            ..DownloadOptions::default()
        };
        let uri = "http://origin.invalid/file.bin";
        let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(74),
            vec![uri.to_string()],
            options.clone(),
        )));
        let mut deps = dependencies(Arc::clone(&cache));
        deps.services.outbound_network_policy =
            Arc::new(OutboundNetworkPolicy::single("127.0.0.1".parse().unwrap()));
        let _command = create_command_for_uri(uri, group, &options, deps)
            .await
            .expect("interface-bound proxy should use system DNS for source selection");
        assert_eq!(
            cache.lock().await.len(),
            0,
            "async-dns=false must not use the shared resolver when choosing a proxy source"
        );

        let socket = tokio::net::UdpSocket::bind("127.0.0.1:0")
            .await
            .expect("bind an unused explicit DNS endpoint");
        let dns_server = socket.local_addr().expect("read DNS endpoint");
        drop(socket);
        let cache = Arc::new(tokio::sync::Mutex::new(DnsCache::with_dns_servers(
            std::time::Duration::from_millis(300),
            vec![dns_server],
        )));
        let options = DownloadOptions {
            async_dns: false,
            ..DownloadOptions::default()
        };
        let uri = "http://localhost:8080/file.bin";
        let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(77),
            vec![uri.to_string()],
            options.clone(),
        )));
        let mut deps = dependencies(Arc::clone(&cache));
        deps.services.outbound_network_policy =
            Arc::new(OutboundNetworkPolicy::single("127.0.0.1".parse().unwrap()));
        let _command = create_command_for_uri(uri, group, &options, deps)
            .await
            .expect("direct interface binding should use system DNS for address-family selection");
        assert_eq!(
            cache.lock().await.len(),
            0,
            "async-dns=false direct binding must not query explicit async DNS servers"
        );
    }

    #[cfg(not(feature = "sftp"))]
    #[tokio::test]
    async fn sftp_uri_is_rejected_instead_of_falling_through_to_http() {
        let uri = "sftp://user@example.test/file.bin";
        let options = DownloadOptions::default();
        let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(79),
            vec![uri.to_string()],
            options.clone(),
        )));

        let result = create_command_for_uri(
            uri,
            group,
            &options,
            dependencies(Arc::new(tokio::sync::Mutex::new(DnsCache::new()))),
        )
        .await;

        assert!(matches!(
            result,
            Err(crate::error::Aria2Error::Fatal(
                crate::error::FatalError::UnsupportedProtocol { protocol }
            )) if protocol == "sftp"
        ));
    }

    #[tokio::test]
    async fn async_dns_true_populates_the_shared_cache_for_protocol_commands() {
        for scheme in ["http", "ftp"] {
            let cache = Arc::new(tokio::sync::Mutex::new(DnsCache::new()));
            let options = DownloadOptions::default();
            let uri = format!("{scheme}://localhost/file.bin");
            let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
                GroupId::new(71),
                vec![uri.clone()],
                options.clone(),
            )));

            let _command =
                create_command_for_uri(&uri, group, &options, dependencies(Arc::clone(&cache)))
                    .await
                    .expect("command construction should resolve localhost");

            assert_eq!(
                cache.lock().await.len(),
                1,
                "async-dns=true must use the shared cache for {scheme}"
            );
        }

        let cache = Arc::new(tokio::sync::Mutex::new(DnsCache::new()));
        let options = DownloadOptions {
            http_proxy: Some("http://localhost:8080".to_string()),
            ..DownloadOptions::default()
        };
        let uri = "http://origin.invalid/file.bin";
        let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(73),
            vec![uri.to_string()],
            options.clone(),
        )));
        let _command =
            create_command_for_uri(uri, group, &options, dependencies(Arc::clone(&cache)))
                .await
                .expect("proxied command should resolve the first-hop proxy");
        let cache = cache.lock().await;
        let proxy_addresses = cache
            .resolve_no_network("localhost", 8080)
            .expect("proxy endpoint must be in the DNS cache");
        assert!(
            !proxy_addresses.is_empty() && proxy_addresses.iter().all(|addr| addr.port() == 8080),
            "async-dns=true must resolve the proxy endpoint"
        );
        assert!(
            cache.resolve_no_network("origin.invalid", 80).is_err(),
            "a proxy must resolve the first hop rather than the origin"
        );
    }

    #[tokio::test]
    async fn explicit_dns_failure_aborts_http_command_setup() {
        let socket = tokio::net::UdpSocket::bind("127.0.0.1:0")
            .await
            .expect("bind an unused explicit DNS endpoint");
        let dns_server = socket.local_addr().expect("read DNS endpoint");
        drop(socket);

        let cache = Arc::new(tokio::sync::Mutex::new(DnsCache::with_dns_servers(
            std::time::Duration::from_millis(300),
            vec![dns_server],
        )));
        let options = DownloadOptions::default();
        let uri = "http://explicit-only.invalid/file.bin";
        let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(75),
            vec![uri.to_string()],
            options.clone(),
        )));

        let result = create_command_for_uri(uri, group, &options, dependencies(cache)).await;
        let error = match result {
            Ok(_) => {
                panic!("an explicit resolver failure must stop before reqwest system DNS fallback")
            }
            Err(error) => error,
        };
        assert!(
            error
                .to_string()
                .contains("using explicitly configured servers"),
            "unexpected command-construction error: {error}"
        );
    }

    #[tokio::test]
    async fn numeric_http_origin_bypasses_explicit_dns_servers() {
        let socket = tokio::net::UdpSocket::bind("127.0.0.1:0")
            .await
            .expect("bind an unused explicit DNS endpoint");
        let dns_server = socket.local_addr().expect("read DNS endpoint");
        drop(socket);

        let cache = Arc::new(tokio::sync::Mutex::new(DnsCache::with_dns_servers(
            std::time::Duration::from_millis(300),
            vec![dns_server],
        )));
        let options = DownloadOptions::default();
        let uri = "http://127.0.0.1:8080/file.bin";
        let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(76),
            vec![uri.to_string()],
            options.clone(),
        )));

        let _command =
            create_command_for_uri(uri, group, &options, dependencies(Arc::clone(&cache)))
                .await
                .expect("an IP literal must not require DNS");
        assert_eq!(
            cache.lock().await.len(),
            0,
            "an IP literal must not query explicitly configured DNS servers"
        );
    }
}