Skip to main content

aria2_core/request/request_group_man/
reserved.rs

1//! Reserved (waiting) download queue operations.
2//!
3//! Reserved groups are downloads that have been added but not yet activated.
4//! They are stored in a `VecDeque` behind a `std::sync::RwLock` to preserve
5//! FIFO insertion order for promotion. When an active slot frees up, the
6//! engine pops the front of this queue to activate the next download.
7
8use std::collections::VecDeque;
9use std::sync::Arc;
10
11use super::RequestGroup;
12use crate::util::rwlock_ext::RwLockRecover;
13
14/// The reserved (waiting) download queue.
15///
16/// Uses `VecDeque` for O(1) front removal during promotion.
17/// The `RwLock` allows concurrent reads from RPC status queries
18/// while the engine loop has write access for promotion.
19pub struct ReservedQueue {
20    groups: std::sync::RwLock<VecDeque<Arc<std::sync::RwLock<RequestGroup>>>>,
21}
22
23impl ReservedQueue {
24    /// Create an empty reserved queue.
25    pub fn new() -> Self {
26        Self {
27            groups: std::sync::RwLock::new(VecDeque::new()),
28        }
29    }
30
31    /// Add a group to the back of the reserved queue.
32    pub fn push_back(&self, group: Arc<std::sync::RwLock<RequestGroup>>) {
33        self.groups.recover_mut().push_back(group);
34    }
35
36    /// Add a group to the front of the reserved queue (used when re-queueing
37    /// a paused group so it gets priority when unpaused).
38    pub fn push_front(&self, group: Arc<std::sync::RwLock<RequestGroup>>) {
39        self.groups.recover_mut().push_front(group);
40    }
41
42    /// Insert a batch of groups at the front of the reserved queue.
43    ///
44    /// Mirrors C++ `RequestGroupMan::insertReservedGroup(0, nextGroups)`:
45    /// child groups from `postDownloadProcessing()` are inserted at position 0
46    /// so they are promoted before other waiting downloads.
47    ///
48    /// Groups are inserted in order: the first element of `groups` will be
49    /// at the front of the queue (promoted first).
50    pub fn insert_front_batch(&self, groups: Vec<Arc<std::sync::RwLock<RequestGroup>>>) {
51        let mut queue = self.groups.recover_mut();
52        for group in groups.into_iter().rev() {
53            queue.push_front(group);
54        }
55    }
56
57    /// Append multiple groups while holding the queue lock once.
58    #[cfg(all(feature = "metalink", feature = "bittorrent"))]
59    pub fn push_back_batch(
60        &self,
61        groups: impl IntoIterator<Item = Arc<std::sync::RwLock<RequestGroup>>>,
62    ) {
63        let mut queue = self.groups.recover_mut();
64        queue.extend(groups);
65    }
66
67    /// Pop the front group from the reserved queue.
68    /// Returns `None` if the queue is empty.
69    pub fn pop_front(&self) -> Option<Arc<std::sync::RwLock<RequestGroup>>> {
70        self.groups.recover_mut().pop_front()
71    }
72
73    /// Remove and return every group still waiting in the queue.
74    ///
75    /// Force shutdown uses this to discard work that has not acquired an
76    /// engine slot yet. Active groups remain owned by the engine so their
77    /// running commands can observe the force-halt request and finalize.
78    pub fn drain(&self) -> Vec<Arc<std::sync::RwLock<RequestGroup>>> {
79        self.groups.recover_mut().drain(..).collect()
80    }
81
82    /// Number of groups in the reserved queue.
83    pub fn len(&self) -> usize {
84        self.groups.recover().len()
85    }
86
87    /// Whether the reserved queue is empty.
88    pub fn is_empty(&self) -> bool {
89        self.groups.recover().is_empty()
90    }
91
92    /// Find a reserved group by GID.
93    pub fn find_by_gid(
94        &self,
95        gid: crate::request::request_group::GroupId,
96    ) -> Option<Arc<std::sync::RwLock<RequestGroup>>> {
97        self.groups
98            .recover()
99            .iter()
100            .find(|g| g.recover().gid() == gid)
101            .cloned()
102    }
103
104    /// Find a reserved group by hex GID string.
105    /// Used by RPC `tellWaiting` / `changePosition`.
106    #[allow(dead_code)]
107    pub fn find_by_hex(&self, hex: &str) -> Option<Arc<std::sync::RwLock<RequestGroup>>> {
108        let gid = crate::request::request_group::GroupId::from_hex_string(hex)?;
109        self.find_by_gid(gid)
110    }
111
112    /// Remove a group from the reserved queue by GID.
113    pub fn remove_by_gid(
114        &self,
115        gid: crate::request::request_group::GroupId,
116    ) -> Option<Arc<std::sync::RwLock<RequestGroup>>> {
117        let mut groups = self.groups.recover_mut();
118        let pos = groups.iter().position(|g| g.recover().gid() == gid)?;
119        groups.remove(pos)
120    }
121
122    /// Iterate over all reserved groups (read-only snapshot).
123    pub fn iter_snapshot(&self) -> Vec<Arc<std::sync::RwLock<RequestGroup>>> {
124        self.groups.recover().iter().cloned().collect()
125    }
126
127    /// Change the position of a group in the reserved queue.
128    /// Mirrors C++ `RequestGroupMan::changeReservedGroupPosition`.
129    #[allow(dead_code)]
130    pub fn change_position(
131        &self,
132        gid: crate::request::request_group::GroupId,
133        pos: i32,
134        how: PositionMode,
135    ) -> Option<usize> {
136        let mut groups = self.groups.recover_mut();
137        let current = groups.iter().position(|g| g.recover().gid() == gid)?;
138
139        let last = groups.len().saturating_sub(1) as i64;
140        let current = current as i64;
141        let new_pos = match how {
142            PositionMode::SetFromStart => pos as i64,
143            PositionMode::MoveFromStart => current.saturating_add(pos as i64),
144            PositionMode::SetFromEnd => last.saturating_sub(pos as i64),
145            PositionMode::MoveFromEnd => current.saturating_sub(pos as i64),
146        }
147        .clamp(0, last) as usize;
148
149        let item = groups.remove(current as usize)?;
150        groups.insert(new_pos, item);
151        Some(new_pos)
152    }
153}
154
155/// Position mode for `change_position`, matching C++ `OffsetMode`.
156#[allow(dead_code)]
157#[derive(Debug, Clone, Copy, PartialEq)]
158pub enum PositionMode {
159    /// Set position from the start of the queue.
160    SetFromStart,
161    /// Move position relative to current, from the start.
162    MoveFromStart,
163    /// Set position from the end of the queue.
164    SetFromEnd,
165    /// Move position relative to current, from the end.
166    MoveFromEnd,
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use crate::request::request_group::{DownloadOptions, GroupId};
173
174    fn make_group(id: u64) -> Arc<std::sync::RwLock<RequestGroup>> {
175        Arc::new(std::sync::RwLock::new(RequestGroup::new(
176            GroupId(id),
177            vec![format!("http://example.com/file{}.bin", id)],
178            DownloadOptions::default(),
179        )))
180    }
181
182    #[test]
183    fn test_push_pop_fifo() {
184        let q = ReservedQueue::new();
185        let g1 = make_group(1);
186        let g2 = make_group(2);
187        q.push_back(g1);
188        q.push_back(g2);
189        assert_eq!(q.len(), 2);
190        let first = q.pop_front().unwrap();
191        assert_eq!(first.recover().gid(), GroupId(1));
192        assert_eq!(q.len(), 1);
193    }
194
195    #[test]
196    fn test_find_by_gid() {
197        let q = ReservedQueue::new();
198        q.push_back(make_group(10));
199        q.push_back(make_group(20));
200        let found = q.find_by_gid(GroupId(20));
201        assert!(found.is_some());
202        assert_eq!(found.unwrap().recover().gid(), GroupId(20));
203        assert!(q.find_by_gid(GroupId(99)).is_none());
204    }
205
206    #[test]
207    fn test_remove_by_gid() {
208        let q = ReservedQueue::new();
209        q.push_back(make_group(1));
210        q.push_back(make_group(2));
211        q.push_back(make_group(3));
212        let removed = q.remove_by_gid(GroupId(2));
213        assert!(removed.is_some());
214        assert_eq!(q.len(), 2);
215        assert!(q.find_by_gid(GroupId(2)).is_none());
216    }
217}