aria2-core 0.3.13

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
use std::sync::Arc;

use tokio::sync::mpsc;

use super::DownloadEngine;
use crate::engine::command::{ProgressMessage, ProgressUpdate};
use crate::request::request_group::RequestGroup;
use crate::util::speed_smooth::SpeedSmoother;

impl DownloadEngine {
    /// Spawn a progress aggregator task that receives [`ProgressUpdate`]s from
    /// download commands and applies them to the shared [`RequestGroup`].
    ///
    /// This eliminates per-chunk write-lock contention on the download hot
    /// path: each `DownloadCommand` sends through a bounded `mpsc` queue and
    /// this aggregator applies the resulting progress fields.
    ///
    /// The aggregator deduplicates consecutive updates with identical
    /// `completed_bytes` values and derives an EMA speed from byte deltas.
    /// The command-owned channel also supports length-only updates for paths
    /// that publish their speed through a separate sampler.
    ///
    /// The task exits cleanly when all senders are dropped (the receiver
    /// returns `None`).
    ///
    /// This is intentionally an associated function (not `&self`): it is
    /// called automatically by
    /// [`DownloadCommand::spawn_progress_aggregator`](crate::engine::http::download_command::DownloadCommand::spawn_progress_aggregator)
    /// during `execute()`, since every `DownloadCommand` now auto-creates a
    /// progress channel in its constructor. External callers rarely need to
    /// invoke this directly.
    pub fn spawn_progress_aggregator(
        _group: Arc<std::sync::RwLock<RequestGroup>>,
        progress: Arc<crate::request::request_group::AtomicProgress>,
        mut receiver: mpsc::Receiver<ProgressUpdate>,
    ) -> tokio::task::JoinHandle<()> {
        tokio::spawn(async move {
            let mut last_bytes: u64 = 0;
            let mut smoother = SpeedSmoother::with_default_window(); // EMA N=10
            while let Some(update) = receiver.recv().await {
                apply_progress_update(update, &progress, &mut smoother, &mut last_bytes, true);
            }
        })
    }

    pub(crate) fn spawn_progress_message_aggregator(
        _group: Arc<std::sync::RwLock<RequestGroup>>,
        progress: Arc<crate::request::request_group::AtomicProgress>,
        mut receiver: mpsc::Receiver<ProgressMessage>,
    ) -> tokio::task::JoinHandle<()> {
        tokio::spawn(async move {
            let mut last_bytes: u64 = 0;
            let mut smoother = SpeedSmoother::with_default_window(); // EMA N=10
            while let Some(message) = receiver.recv().await {
                let (update, update_speed) = match message {
                    ProgressMessage::Update(update) => (update, true),
                    ProgressMessage::LengthOnly(update) => (update, false),
                };
                apply_progress_update(
                    update,
                    &progress,
                    &mut smoother,
                    &mut last_bytes,
                    update_speed,
                );
            }
        })
    }
}

fn apply_progress_update(
    update: ProgressUpdate,
    progress: &crate::request::request_group::AtomicProgress,
    smoother: &mut SpeedSmoother,
    last_bytes: &mut u64,
    update_speed: bool,
) {
    if !update_speed {
        smoother.reset();
    }
    if update.completed_bytes == *last_bytes {
        return;
    }

    let delta = update.completed_bytes.saturating_sub(*last_bytes);
    if update_speed {
        smoother.record_bytes(delta);
    }

    // Lock-free progress update -- no RwLock acquisition needed.
    progress.set_completed_length(update.completed_bytes);

    if update_speed {
        // Speed: use EMA-smoothed speed when available. Preserve the current
        // value when no sample has completed yet.
        let smoothed = smoother.smoothed_speed() as u64;
        if smoothed > 0 {
            progress.set_download_speed(smoothed);
            progress.set_upload_speed(update.upload_speed);
        } else if update.download_speed > 0 {
            progress.set_download_speed(update.download_speed);
            progress.set_upload_speed(update.upload_speed);
        }
    }
    *last_bytes = update.completed_bytes;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::command::{ProgressMessage, ProgressUpdate};
    use crate::request::request_group::{DownloadOptions, GroupId, RequestGroup};
    #[cfg(test)]
    use crate::util::rwlock_ext::RwLockRecover;

    /// Helper: build a fresh `RequestGroup` wrapped in an `Arc<std::sync::RwLock<..>>`,
    /// the same shape `DownloadCommand` and the aggregator use.
    fn make_group() -> Arc<std::sync::RwLock<RequestGroup>> {
        Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(1),
            vec!["http://example.com/file.bin".to_string()],
            DownloadOptions::default(),
        )))
    }

    /// Verify the aggregator receives `ProgressUpdate`s sent through the
    /// channel and applies them to the `RequestGroup` (both the RwLock-backed
    /// `completed_length` via `update_progress` and the atomic mirror via
    /// `set_completed_length`).
    #[tokio::test]
    async fn test_progress_channel_updates_request_group() {
        let group = make_group();
        let (tx, rx) = mpsc::channel::<ProgressUpdate>(16);

        let group_clone = Arc::clone(&group);
        let handle = DownloadEngine::spawn_progress_aggregator(
            group_clone,
            group.recover().progress.clone(),
            rx,
        );

        // Send a sequence of strictly increasing updates.
        tx.send(ProgressUpdate {
            completed_bytes: 1000,
            download_speed: 0,
            upload_speed: 0,
        })
        .await
        .unwrap();
        tx.send(ProgressUpdate {
            completed_bytes: 5000,
            download_speed: 0,
            upload_speed: 0,
        })
        .await
        .unwrap();

        // Drop the sender: the aggregator drains all queued messages (bounded
        // channel recv only returns None after the queue is empty and all
        // senders are gone), then exits. Awaiting the handle is therefore a
        // deterministic synchronization point -- no sleep-based polling needed.
        drop(tx);
        handle.await.expect("aggregator task should exit cleanly");

        // The atomic mirror is set by `set_completed_length`; verify final value.
        let atomic_val = { group.recover().get_completed_length() };
        assert_eq!(
            atomic_val, 5000,
            "aggregator should have applied the latest completed_bytes (5000)"
        );
    }

    #[tokio::test]
    async fn length_only_updates_preserve_the_external_speed_sample() {
        let group = make_group();
        let progress = Arc::clone(&group.recover().progress);
        progress.set_download_speed(12_345);
        let (tx, rx) = mpsc::channel::<ProgressMessage>(4);
        let handle = DownloadEngine::spawn_progress_message_aggregator(
            Arc::clone(&group),
            Arc::clone(&progress),
            rx,
        );

        tx.send(ProgressMessage::LengthOnly(ProgressUpdate {
            completed_bytes: 4096,
            download_speed: 999_999,
            upload_speed: 0,
        }))
        .await
        .unwrap();
        drop(tx);
        handle
            .await
            .expect("progress aggregator should exit cleanly");

        assert_eq!(progress.completed_length(), 4096);
        assert_eq!(progress.download_speed(), 12_345);
    }

    /// Verify the aggregator skips no-op updates with identical
    /// `completed_bytes` (deduplication), so a flood of stale in-flight sends
    /// does not cause redundant write-lock acquisitions.
    #[tokio::test]
    async fn test_progress_aggregator_dedupes_identical_bytes() {
        let group = make_group();
        let (tx, rx) = mpsc::channel::<ProgressUpdate>(16);

        let group_clone = Arc::clone(&group);
        let handle = DownloadEngine::spawn_progress_aggregator(
            group_clone,
            group.recover().progress.clone(),
            rx,
        );

        // First real update.
        tx.send(ProgressUpdate {
            completed_bytes: 2048,
            download_speed: 0,
            upload_speed: 0,
        })
        .await
        .unwrap();
        // Several duplicates with the same completed_bytes (and a speed that
        // must NOT be applied because the dedup `continue`s before reaching
        // the speed branch).
        for _ in 0..5 {
            tx.send(ProgressUpdate {
                completed_bytes: 2048,
                download_speed: 9999,
                upload_speed: 0,
            })
            .await
            .unwrap();
        }
        // A real advance with a speed sample that SHOULD be applied.
        tx.send(ProgressUpdate {
            completed_bytes: 4096,
            download_speed: 1234,
            upload_speed: 0,
        })
        .await
        .unwrap();

        // Deterministic drain: drop sender + await handle guarantees all
        // queued messages have been processed by the aggregator.
        drop(tx);
        handle.await.expect("aggregator task should exit cleanly");

        let g = group.recover();
        assert_eq!(
            g.get_completed_length(),
            4096,
            "final completed_bytes should be 4096"
        );
        // Speed is now EMA-smoothed by the aggregator's SpeedSmoother.
        // We cannot predict the exact EMA value in a unit test, but it must
        // be > 0 (a positive delta was recorded).
        assert!(
            g.get_download_speed_cached() > 0,
            "smoothed speed should be > 0 after positive delta, got {}",
            g.get_download_speed_cached()
        );
    }

    /// Verify that the aggregator applies EMA-smoothed speed whenever a
    /// positive byte delta is recorded, regardless of the sender's raw
    /// `download_speed` sample.
    #[tokio::test]
    async fn test_progress_aggregator_applies_smoothed_speed_on_delta() {
        let group = make_group();
        let (tx, rx) = mpsc::channel::<ProgressUpdate>(16);

        // Seed the group with a known cached speed before starting the aggregator.
        {
            let g = group.recover();
            g.set_download_speed_cached(5555);
        }

        let group_clone = Arc::clone(&group);
        let handle = DownloadEngine::spawn_progress_aggregator(
            group_clone,
            group.recover().progress.clone(),
            rx,
        );

        // Advance bytes but send a 0 speed sample (no fresh measurement).
        tx.send(ProgressUpdate {
            completed_bytes: 8192,
            download_speed: 0,
            upload_speed: 0,
        })
        .await
        .unwrap();

        // Deterministic drain.
        drop(tx);
        handle.await.expect("aggregator task should exit cleanly");

        let g = group.recover();
        assert_eq!(g.get_completed_length(), 8192, "bytes should advance");
        // The smoothed speed is always computed from the byte delta and
        // applied to the cached speed (replacing the seeded 5555).
        assert!(
            g.get_download_speed_cached() > 0,
            "smoothed speed should be applied when delta > 0, got {}",
            g.get_download_speed_cached()
        );
    }

    /// Verify the aggregator task exits cleanly (JoinHandle resolves) once all
    /// senders are dropped, with no hang or resource leak.
    #[tokio::test]
    async fn test_progress_aggregator_exits_on_sender_drop() {
        let group = make_group();
        let (tx, rx) = mpsc::channel::<ProgressUpdate>(16);

        let handle = DownloadEngine::spawn_progress_aggregator(
            group.clone(),
            group.recover().progress.clone(),
            rx,
        );

        // Drop the only sender; the aggregator's `recv().await` returns None.
        drop(tx);

        // The handle should resolve promptly without needing to abort.
        let result = tokio::time::timeout(std::time::Duration::from_millis(500), handle).await;
        assert!(
            result.is_ok(),
            "aggregator should exit within 500ms after senders are dropped"
        );
        result
            .expect("aggregator task should exit cleanly")
            .expect("aggregator task should not panic");
    }

    /// Verify that EMA smoothing produces a stable, finite, positive speed
    /// value after a sequence of positive byte deltas.
    ///
    /// This test avoids asserting exact speed bounds because the EMA's
    /// instantaneous speed depends on real elapsed time (`delta / duration`),
    /// which varies with scheduler timing. The detailed EMA convergence and
    /// reaction behavior is covered by `speed_smooth::tests`.
    #[tokio::test]
    async fn test_progress_aggregator_smooths_speed() {
        let group = make_group();
        let (tx, rx) = mpsc::channel::<ProgressUpdate>(16);

        let group_clone = Arc::clone(&group);
        let handle = DownloadEngine::spawn_progress_aggregator(
            group_clone,
            group.recover().progress.clone(),
            rx,
        );

        // Send a sequence of strictly increasing byte deltas, waiting long
        // enough between sends to cross the smoother's SAMPLE_INTERVAL_MS
        // (500ms) boundary so each delta triggers an EMA update.
        let deltas: [u64; 3] = [10000, 5000, 20000];
        for delta in &deltas {
            let current = {
                let g = group.recover();
                g.get_completed_length()
            };
            tx.send(ProgressUpdate {
                completed_bytes: current + delta,
                download_speed: 0, // Ignored -- smoother computes from delta
                upload_speed: 0,
            })
            .await
            .unwrap();

            // Wait long enough for the smoother's SAMPLE_INTERVAL_MS to elapse
            // so the next record_bytes triggers an EMA update.
            tokio::time::sleep(std::time::Duration::from_millis(
                crate::constants::HTTP_SPEED_UPDATE_INTERVAL_MS + 100,
            ))
            .await;
        }

        // Drain the channel.
        drop(tx);
        handle.await.expect("aggregator task should exit cleanly");

        let g = group.recover();
        let final_speed = g.get_download_speed_cached();

        // The EMA-smoothed speed must be positive and finite after recording
        // positive deltas. We do not assert upper/lower bounds against the
        // raw delta values because the smoother divides by real elapsed time
        // (varies with scheduler jitter), not a fixed 1s window.
        assert!(
            final_speed > 0,
            "EMA-smoothed speed should be > 0 after positive deltas, got {}",
            final_speed
        );
        assert!(
            final_speed < u64::MAX / 2,
            "EMA-smoothed speed should be finite, got {}",
            final_speed
        );
    }
}