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
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use tracing::debug;
use crate::constants;
use crate::selector::server_stat_man::ServerStatMan;
use crate::selector::uri_selector::UriSelector;
// ── Sub-modules ─────────────────────────────────────────────────────────
mod mirror_selection;
mod segment_lifecycle;
#[cfg(test)]
mod tests;
mod types;
// ── Public re-exports ───────────────────────────────────────────────────
pub use types::{MirrorState, Segment, SegmentStatus};
// ── Main struct ─────────────────────────────────────────────────────────
pub struct ConcurrentSegmentManager {
total_size: u64,
segments: Vec<Segment>,
/// Bytes already completed within each durable parent segment. These
/// offsets are kept in memory only; the control-file bitfield still marks
/// a parent complete only after every dynamic subrange has succeeded.
completed_lengths: Vec<u64>,
mirrors: Vec<MirrorState>,
/// URLs for mirror selection (used with UriSelector)
mirror_urls: Vec<String>,
completed_bytes: u64,
max_retries_per_segment: u32,
max_mirror_failures: usize,
mirror_cooldown: Duration,
mirror_disabled_until: Vec<Option<Instant>>,
/// Optional server statistics manager for intelligent mirror selection
stat_man: Option<Arc<ServerStatMan>>,
/// Optional URI selector for intelligent mirror selection
uri_selector: Option<Box<dyn UriSelector>>,
/// Atomic hint pointing at the next candidate segment index for allocation.
///
/// This enables O(1) amortized segment allocation: scans start from the last
/// assigned position instead of re-scanning already-assigned segments from
/// the beginning. Updated with `Ordering::Relaxed` since it is only a hint;
/// the linear scan with wraparound always preserves correctness even if the
/// hint races or points at an already-assigned segment.
next_segment_idx: AtomicU32,
}
impl ConcurrentSegmentManager {
/// Create a new segment manager with basic round-robin mirror selection.
///
/// This is the basic constructor that uses the built-in `MirrorState`
/// for mirror tracking. For intelligent mirror selection, use
/// `new_with_selector()` instead.
pub fn new(total_size: u64, urls: Vec<String>, segment_size: Option<u64>) -> Self {
let seg_size = segment_size.unwrap_or(constants::DEFAULT_SEGMENT_SIZE as u64);
let num_segments = if total_size == 0 {
0
} else {
total_size.div_ceil(seg_size) as usize
};
let mut segments = Vec::with_capacity(num_segments);
for i in 0..num_segments {
let offset = (i as u64) * seg_size;
let remaining = total_size.saturating_sub(offset);
let length = seg_size.min(remaining);
segments.push(Segment::new(i as u32, offset, length));
}
let mirrors = urls.iter().map(|_| MirrorState::new()).collect();
let mirror_disabled_until = vec![None; urls.len()];
Self {
total_size,
completed_lengths: vec![0; num_segments],
segments,
mirrors,
mirror_urls: urls,
completed_bytes: 0,
max_retries_per_segment: constants::MAX_RETRIES_PER_SEGMENT,
max_mirror_failures: constants::MAX_MIRROR_FAILURES as usize,
mirror_cooldown: Duration::from_secs(constants::MIRROR_COOLDOWN_SECS),
mirror_disabled_until,
stat_man: None,
uri_selector: None,
next_segment_idx: AtomicU32::new(0),
}
}
/// Create a new segment manager with intelligent mirror selection.
///
/// This constructor integrates with `ServerStatMan` and `UriSelector`
/// for intelligent mirror selection based on historical performance data.
///
/// # Arguments
///
/// * `total_size` - Total file size in bytes
/// * `urls` - List of mirror URLs
/// * `segment_size` - Optional segment size (default: 1 MB)
/// * `stat_man` - Shared server statistics manager
/// * `uri_selector` - URI selector for intelligent mirror selection
///
/// # Example
///
/// ```ignore
/// use std::sync::Arc;
/// use aria2_core::selector::server_stat_man::ServerStatMan;
/// use aria2_core::selector::adaptive_uri_selector::AdaptiveUriSelector;
/// use aria2_core::engine::concurrent_segment_manager::ConcurrentSegmentManager;
///
/// let stat_man = Arc::new(ServerStatMan::new());
/// let urls = vec!["http://mirror1.com/file".to_string()];
/// let selector = Box::new(AdaptiveUriSelector::new_with_uris(Arc::clone(&stat_man), urls.clone()));
///
/// let mgr = ConcurrentSegmentManager::new_with_selector(
/// 10_000_000,
/// urls,
/// Some(1_000_000),
/// stat_man,
/// selector,
/// );
/// ```
pub fn new_with_selector(
total_size: u64,
urls: Vec<String>,
segment_size: Option<u64>,
stat_man: Arc<ServerStatMan>,
uri_selector: Box<dyn UriSelector>,
) -> Self {
let seg_size = segment_size.unwrap_or(constants::DEFAULT_SEGMENT_SIZE as u64);
let num_segments = if total_size == 0 {
0
} else {
total_size.div_ceil(seg_size) as usize
};
let mut segments = Vec::with_capacity(num_segments);
for i in 0..num_segments {
let offset = (i as u64) * seg_size;
let remaining = total_size.saturating_sub(offset);
let length = seg_size.min(remaining);
segments.push(Segment::new(i as u32, offset, length));
}
let mirrors = urls.iter().map(|_| MirrorState::new()).collect();
let mirror_disabled_until = vec![None; urls.len()];
Self {
total_size,
completed_lengths: vec![0; num_segments],
segments,
mirrors,
mirror_urls: urls,
completed_bytes: 0,
max_retries_per_segment: constants::MAX_RETRIES_PER_SEGMENT,
max_mirror_failures: constants::MAX_MIRROR_FAILURES as usize,
mirror_cooldown: Duration::from_secs(constants::MIRROR_COOLDOWN_SECS),
mirror_disabled_until,
stat_man: Some(stat_man),
uri_selector: Some(uri_selector),
next_segment_idx: AtomicU32::new(0),
}
}
// ── Segment allocation ──────────────────────────────────────────────
pub fn allocate_segments(&mut self) {
for mirror_idx in 0..self.mirrors.len() {
while self.mirrors[mirror_idx].can_accept_more() {
if let Some(seg) = self.find_pending_segment() {
seg.status = SegmentStatus::Downloading;
seg.assigned_mirror = Some(mirror_idx);
self.mirrors[mirror_idx].active_segments += 1;
} else {
break;
}
}
}
}
fn find_pending_segment(&mut self) -> Option<&mut Segment> {
let len = self.segments.len();
if len == 0 {
return None;
}
// Start scanning from the atomic hint to skip already-assigned segments.
// The wraparound scan guarantees correctness even if the hint is stale.
let start = (self.next_segment_idx.load(Ordering::Relaxed) as usize) % len;
for i in 0..len {
let idx = (start + i) % len;
if self.segments[idx].status == SegmentStatus::Pending {
// Advance the hint past this segment; the caller marks it
// Downloading immediately so it won't be selected again.
self.next_segment_idx
.store((idx + 1) as u32, Ordering::Relaxed);
return Some(&mut self.segments[idx]);
}
}
None
}
pub fn next_pending_segment_for_mirror(
&mut self,
mirror_idx: usize,
) -> Option<(u32, u64, u64)> {
self.next_pending_range_for_mirror(mirror_idx, u64::MAX)
}
/// Claim a pending durable parent and return its next dynamic subrange.
///
/// The caller chooses the request size. Successfully completed prefixes
/// within a parent stay in memory for the current download attempt, while
/// the parent remains the unit recorded in the control-file bitfield.
pub fn next_pending_range_for_mirror(
&mut self,
mirror_idx: usize,
max_length: u64,
) -> Option<(u32, u64, u64)> {
if !self
.mirrors
.get(mirror_idx)
.is_some_and(|m| m.can_accept_more())
{
return None;
}
let len = self.segments.len();
if len == 0 {
return None;
}
// Start scanning from the atomic hint to skip already-assigned segments.
// This yields O(1) amortized allocation: each segment is visited at most
// once before the hint catches up to it.
let start = (self.next_segment_idx.load(Ordering::Relaxed) as usize) % len;
for i in 0..len {
let idx = (start + i) % len;
let seg = &mut self.segments[idx];
if seg.status == SegmentStatus::Pending {
let completed = self.completed_lengths[idx].min(seg.length);
let remaining = seg.length - completed;
if remaining == 0 {
seg.status = SegmentStatus::Done;
continue;
}
let offset = seg.offset.saturating_add(completed);
let length = remaining.min(max_length.max(1));
seg.status = SegmentStatus::Downloading;
seg.assigned_mirror = Some(mirror_idx);
self.next_segment_idx
.store((idx + 1) as u32, Ordering::Relaxed);
if let Some(m) = self.mirrors.get_mut(mirror_idx) {
m.active_segments += 1;
}
return Some((seg.index, offset, length));
}
}
None
}
/// Claim the next subrange of a specific pending parent segment.
///
/// The HTTP work scheduler owns parent selection, so it supplies the
/// segment index to this HTTP range planner when the lease is admitted.
pub(crate) fn next_pending_range_for_segment(
&mut self,
mirror_idx: usize,
segment_index: u32,
max_length: u64,
) -> Option<(u32, u64, u64)> {
if !self
.mirrors
.get(mirror_idx)
.is_some_and(|mirror| mirror.can_accept_more())
{
return None;
}
let index = segment_index as usize;
let segment = self.segments.get_mut(index)?;
if segment.status != SegmentStatus::Pending {
return None;
}
let completed = (*self.completed_lengths.get(index)?).min(segment.length);
let remaining = segment.length - completed;
if remaining == 0 {
segment.status = SegmentStatus::Done;
return None;
}
let offset = segment.offset.saturating_add(completed);
let length = remaining.min(max_length.max(1));
segment.status = SegmentStatus::Downloading;
segment.assigned_mirror = Some(mirror_idx);
self.next_segment_idx
.store((index + 1) as u32, Ordering::Relaxed);
if let Some(mirror) = self.mirrors.get_mut(mirror_idx) {
mirror.active_segments += 1;
}
Some((segment.index, offset, length))
}
pub fn next_pending_segment(&mut self) -> Option<(u32, u64, u64)> {
self.next_pending_segment_for_mirror(0)
}
/// Atomically allocate the next segment index for lock-free assignment.
///
/// Returns the index of the next segment to claim, or `None` if all segments
/// have been allocated. This uses `fetch_add` for O(1) lock-free allocation.
/// The caller is responsible for checking the segment status and claiming it.
///
/// Unlike [`next_pending_segment_for_mirror`](Self::next_pending_segment_for_mirror),
/// this method takes only `&self` and is therefore safe to call concurrently
/// from multiple threads through an `Arc<ConcurrentSegmentManager>`.
///
/// # Concurrency
///
/// Each successful call returns a distinct index. Once all segments have been
/// issued, subsequent calls return `None` (the counter keeps growing but is
/// bounded by the number of callers, so it cannot overflow in practice).
pub fn allocate_next_index(&self) -> Option<u32> {
let idx = self.next_segment_idx.fetch_add(1, Ordering::Relaxed);
if (idx as usize) < self.segments.len() {
Some(idx)
} else {
None
}
}
/// Reset the allocation index to 0.
///
/// This is useful for retry scenarios where segments that previously failed
/// need to be reconsidered for assignment from the beginning of the vector.
///
/// # Safety of use
///
/// This must not be called concurrently with [`allocate_next_index`](Self::allocate_next_index)
/// if unique indices are required; it is intended for reset points where the
/// caller has exclusive access (e.g. between download attempts).
pub fn reset_allocation_index(&self) {
self.next_segment_idx.store(0, Ordering::Relaxed);
}
// ── Query / inspection ──────────────────────────────────────────────
pub fn is_complete(&self) -> bool {
self.segments
.iter()
.all(|s| s.status == SegmentStatus::Done)
}
pub fn has_failed_segments(&self) -> bool {
self.segments
.iter()
.any(|s| s.status == SegmentStatus::Failed)
}
pub fn has_pending_segments(&self) -> bool {
self.segments
.iter()
.any(|s| s.status == SegmentStatus::Pending)
}
pub fn completed_ranges(&self) -> Vec<(u64, u64)> {
let mut ranges = Vec::new();
for seg in &self.segments {
if seg.status == SegmentStatus::Done {
ranges.push((seg.offset, seg.length));
}
}
ranges.sort_by_key(|r| r.0);
ranges
}
pub fn progress(&self) -> f64 {
if self.total_size == 0 {
return 100.0;
}
self.completed_bytes as f64 / self.total_size as f64 * 100.0
}
pub fn num_segments(&self) -> usize {
self.segments.len()
}
pub fn segment_status(&self, index: usize) -> Option<SegmentStatus> {
self.segments.get(index).map(|s| s.status.clone())
}
pub fn num_mirrors(&self) -> usize {
self.mirrors.len()
}
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn completed_bytes(&self) -> u64 {
self.completed_bytes
}
pub fn mirror_url(&self, index: usize) -> Option<&str> {
self.mirror_urls.get(index).map(String::as_str)
}
pub fn available_mirrors(&self) -> Vec<usize> {
self.mirrors
.iter()
.enumerate()
.filter(|(_, m)| m.is_available())
.map(|(i, _)| i)
.collect()
}
pub fn any_mirror_available(&self) -> bool {
self.mirrors.iter().any(|m| m.is_available())
}
/// Re-enable mirrors whose circuit-breaker cooldown has expired.
pub(crate) fn refresh_mirror_availability(&mut self) {
let now = Instant::now();
for (index, mirror) in self.mirrors.iter_mut().enumerate() {
if !mirror.disabled {
continue;
}
let cooldown_expired = self
.mirror_disabled_until
.get(index)
.and_then(|deadline| *deadline)
.is_none_or(|deadline| now >= deadline);
if cooldown_expired {
mirror.disabled = false;
mirror.consecutive_failures = 0;
self.mirror_disabled_until[index] = None;
}
}
}
/// Return the earliest remaining mirror circuit-breaker cooldown.
pub(crate) fn mirror_cooldown_remaining(&self) -> Option<Duration> {
let now = Instant::now();
self.mirrors
.iter()
.enumerate()
.filter(|(_, mirror)| mirror.disabled)
.filter_map(|(index, _)| {
self.mirror_disabled_until
.get(index)
.and_then(|deadline| *deadline)
})
.map(|deadline| deadline.saturating_duration_since(now))
.min()
}
pub fn segment_retry_count(&self, seg_idx: u32) -> u32 {
self.segments
.iter()
.find(|s| s.index == seg_idx)
.map(|s| s.retry_count)
.unwrap_or(0)
}
pub fn has_permanently_failed_segments(&self) -> bool {
self.segments.iter().any(|s| {
s.status == SegmentStatus::Failed
&& self.max_retries_per_segment != 0
&& s.retry_count >= self.max_retries_per_segment
})
}
pub fn mark_completed_up_to(&mut self, offset: u64, length: u64) {
let completed = self.restore_completed_prefix(offset);
debug!(
"Restored contiguous prefix at offset {} (observed local length {}): {} bytes",
offset, length, completed
);
}
pub fn segment_info(&self, index: usize) -> Option<(u64, u64, &SegmentStatus)> {
self.segments
.get(index)
.map(|s| (s.offset, s.length, &s.status))
}
// ── Mirror configuration ────────────────────────────────────────────
pub fn set_max_connections_per_mirror(&mut self, max: usize) {
for m in &mut self.mirrors {
m.max_connections = max;
}
}
/// Set the maximum connections for a specific mirror.
///
/// This is used for dynamic connection rebalancing based on mirror performance.
///
/// # Arguments
///
/// * `mirror_idx` - Index of the mirror
/// * `max` - New maximum connections for this mirror
pub fn set_mirror_max_connections(&mut self, mirror_idx: usize, max: usize) {
if let Some(mirror) = self.mirrors.get_mut(mirror_idx) {
mirror.max_connections = max;
}
}
/// Get the current maximum connections for a specific mirror.
///
/// # Arguments
///
/// * `mirror_idx` - Index of the mirror
pub fn get_mirror_max_connections(&self, mirror_idx: usize) -> Option<usize> {
self.mirrors.get(mirror_idx).map(|m| m.max_connections)
}
pub fn set_max_retries(&mut self, retries: u32) {
self.max_retries_per_segment = retries;
}
pub(crate) fn set_mirror_cooldown(&mut self, cooldown: Duration) {
self.mirror_cooldown = cooldown.max(Duration::from_secs(1));
}
}