Skip to main content

capsule_sdk/upload/
queue.rs

1//! The device-wide upload queue, keyed per server (transfer upload doc, §Queueing Across
2//! Servers).
3//!
4//! A client signed in to more than one server drives one **lane** per server. Each lane owns
5//! its own work and its own pacing: the jobs still to send, its two **in-flight windows**, its
6//! shared **retry budget**, and the time before which it must not be served (a backoff, or a
7//! server's `Retry-After`).
8//!
9//! - **W, the sessions window**: how many of the lane's sessions may be open at once. Several
10//!   sessions in flight, each on its own HTTP/1.1 connection, are what keep a high-latency or
11//!   lossy link busy, because one connection's throughput is bounded by its round trip.
12//! - **P, the ranges window**: how many ranges each session may hold in flight. A session's P is
13//!   fixed when it is granted and can only be narrowed afterwards, by the cap the server
14//!   advertised for that session ([`UploadQueue::set_session_ranges`]).
15//!
16//! Both are client-local caps ([`LaneWindows`], at most the compiled [`MAX_SESSIONS_WINDOW`] and
17//! [`MAX_RANGES_WINDOW`]) that the server's `X-Capsule-Advice` can only lower
18//! ([`UploadQueue::set_advice`]), and W never exceeds the account's live-session cap
19//! ([`UploadQueue::set_session_cap`]). They are not the protocol window, which says which
20//! protocol dates a server accepts and bounds nothing in flight.
21//!
22//! What the lanes share is one bounded **byte budget**. A session admitted to run reserves
23//! nothing; every *range* it sends reserves its length while in flight
24//! ([`UploadQueue::reserve_range`]), so the device never buffers more than the budget however
25//! many servers and sessions it drives, and a large blob costs no more than the windows it is
26//! sending. Ranges waiting for the budget are served first-come, so a lane sending originals
27//! cannot keep re-reserving it ahead of another lane's T0 range.
28//!
29//! [`UploadQueue::next`] serves the lanes **round-robin**, so one server's backlog cannot
30//! starve another's, and inside a lane it always takes the lowest [`UploadTier`] first, so the
31//! staged ladder (T0 → T1 → T2) holds per server. A lane whose transfers report no progress
32//! for the stall bound gives its sessions and their range reservations back
33//! ([`UploadQueue::reclaim_stalled`]); its jobs return to the front of their tiers and the lane
34//! waits out one stall bound before it is served again, so a dead server's lane cannot hold the
35//! budget every other lane needs. A job that failed and may run again spends one retry from its
36//! lane's shared budget ([`UploadQueue::retry`]), so a server that fails everything costs a
37//! bounded number of retries however many jobs are queued for it. On resume each lane is
38//! rebuilt from its own server's truth ([`UploadQueue::rebuild_lane`]); no lane's state is
39//! derived from another's. Deleting an asset withdraws its jobs from every lane at once
40//! ([`UploadQueue::withdraw`]), so no further byte of it is sent to any server.
41//!
42//! This is a pure scheduler over values: it sends nothing and reads no clock. The caller
43//! passes `now`, runs each [`Grant`] it is handed, and reports back with
44//! [`UploadQueue::progress`], [`UploadQueue::complete`], [`UploadQueue::requeue`] or
45//! [`UploadQueue::retry`]. With one lane and a sessions window of one it hands out exactly one
46//! job at a time, in tier order - the single-server sequential push.
47
48use std::collections::VecDeque;
49use std::fmt;
50use std::time::{Duration, Instant};
51
52use capsule_library::import::UploadTier;
53
54use super::advice::{MAX_ADVISED_RANGES, MAX_ADVISED_SESSIONS, ServerAdvice};
55use crate::net::{DEFAULT_LANE_RETRY_BUDGET, LaneRetries};
56
57/// The widest sessions window (W) any lane holds: the most advice can ever grant.
58pub const MAX_SESSIONS_WINDOW: u32 = MAX_ADVISED_SESSIONS;
59/// The widest ranges window (P) any session holds: the protocol's ceiling on a session's
60/// in-flight cap.
61pub const MAX_RANGES_WINDOW: u32 = MAX_ADVISED_RANGES;
62/// The sessions a lane holds open at once when nothing narrower applies. Four connections keep
63/// a 600 ms, lossy path busy without opening more sessions than a small server's live-session
64/// cap admits.
65pub const DEFAULT_SESSIONS_WINDOW: u32 = 4;
66/// The ranges a session holds in flight when nothing narrower applies.
67pub const DEFAULT_RANGES_WINDOW: u32 = 4;
68
69/// A lane's own in-flight caps, before the server's advice lowers them.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct LaneWindows {
72    /// W: sessions open at once on the lane.
73    pub sessions: u32,
74    /// P: ranges in flight per session.
75    pub ranges: u32,
76}
77
78impl Default for LaneWindows {
79    fn default() -> Self {
80        Self::new(DEFAULT_SESSIONS_WINDOW, DEFAULT_RANGES_WINDOW)
81    }
82}
83
84impl LaneWindows {
85    /// Caps of `sessions` and `ranges`, each clamped into `1..=` its compiled maximum.
86    #[must_use]
87    pub fn new(sessions: u32, ranges: u32) -> Self {
88        Self {
89            sessions: sessions.clamp(1, MAX_SESSIONS_WINDOW),
90            ranges: ranges.clamp(1, MAX_RANGES_WINDOW),
91        }
92    }
93}
94
95/// The key a lane is held under: the server's canonical origin (`scheme://host[:port]`), so
96/// one server reached through differently written endpoints shares one lane.
97#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
98pub struct ServerKey(String);
99
100impl ServerKey {
101    /// Key a lane under `origin`, which the caller has already canonicalized.
102    pub fn new(origin: impl Into<String>) -> Self {
103        Self(origin.into())
104    }
105
106    /// The origin this key was built from.
107    pub fn as_str(&self) -> &str {
108        &self.0
109    }
110}
111
112impl fmt::Display for ServerKey {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.write_str(&self.0)
115    }
116}
117
118/// One unit of upload work queued on a lane: a session to drive, at its tier. Queuing or
119/// running it reserves none of the byte budget; only the ranges it sends do.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct QueuedJob<J> {
122    /// The staged tier the job belongs to; a lane always serves its lowest tier first.
123    pub tier: UploadTier,
124    /// What the caller needs to run it.
125    pub job: J,
126}
127
128impl<J> QueuedJob<J> {
129    /// A job at `tier`.
130    pub fn new(tier: UploadTier, job: J) -> Self {
131        Self { tier, job }
132    }
133}
134
135/// The handle of one job in flight, unique for the life of the queue.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
137pub struct GrantId(u64);
138
139/// The handle of one range reservation, unique for the life of the queue.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
141pub struct RangeId(u64);
142
143/// A job the queue admitted: run it, then report on it by its [`GrantId`].
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct Grant<J> {
146    /// The handle every later report names.
147    pub id: GrantId,
148    /// The lane (server) the job belongs to.
149    pub server: ServerKey,
150    /// The job's tier.
151    pub tier: UploadTier,
152    /// P: the most ranges this session may hold in flight, fixed at the grant. The server's
153    /// own cap for the session can only narrow it ([`UploadQueue::set_session_ranges`]).
154    pub ranges: u32,
155    /// The work itself.
156    pub job: J,
157}
158
159/// Why [`UploadQueue::reserve_range`] reserved nothing.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum RangeRefused {
162    /// The grant is no longer in flight (completed, requeued, revoked or superseded): stop
163    /// sending for it.
164    NotInFlight,
165    /// The session already holds its P ranges in flight: wait for one to return.
166    WindowFull,
167    /// The shared byte budget cannot hold the range now, or an earlier grant waits for it
168    /// first: wait for a reservation to be released and ask again.
169    BudgetFull,
170}
171
172/// What [`UploadQueue::retry`] decided for a job that failed.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum RetryAdmission<J> {
175    /// The lane's budget paid for a retry: the job is back at the front of its tier.
176    Requeued,
177    /// The lane's retry budget is spent: the job leaves the queue, and the caller surfaces it as
178    /// the failure it is.
179    BudgetSpent(QueuedJob<J>),
180    /// The grant was no longer in flight; nothing changed.
181    NotInFlight,
182}
183
184/// A job in flight, kept so a revoked or requeued grant can return to its lane.
185#[derive(Debug, Clone)]
186struct InFlight<J> {
187    id: GrantId,
188    job: QueuedJob<J>,
189    /// P for this session.
190    ranges_window: u32,
191    /// The session's ranges in flight and the bytes each holds of the budget.
192    ranges: Vec<(RangeId, u64)>,
193}
194
195impl<J> InFlight<J> {
196    fn reserved(&self) -> u64 {
197        self.ranges.iter().map(|(_, bytes)| bytes).sum()
198    }
199}
200
201/// One server's lane.
202#[derive(Debug)]
203struct Lane<J> {
204    server: ServerKey,
205    /// The client's own caps for this lane.
206    windows: LaneWindows,
207    /// The last advice the server sent for this lane, and when it arrived.
208    advice: Option<(ServerAdvice, Instant)>,
209    /// The account's live-session cap on this server, when known.
210    session_cap: Option<u32>,
211    /// The lane's shared retry budget; the client driving the lane holds a clone.
212    retries: LaneRetries,
213    /// Queued jobs, one FIFO per tier, indexed in ladder order.
214    queued: [VecDeque<QueuedJob<J>>; 3],
215    in_flight: Vec<InFlight<J>>,
216    /// When this lane last made progress (a grant, a progress report, or a completion).
217    last_progress: Option<Instant>,
218    /// The lane is not served before this instant: a backoff, `Retry-After`, or a stall.
219    paused_until: Option<Instant>,
220}
221
222/// Where `tier` sits in a lane's per-tier queues.
223fn tier_slot(tier: UploadTier) -> usize {
224    match tier {
225        UploadTier::Index => 0,
226        UploadTier::Preview => 1,
227        UploadTier::Original => 2,
228    }
229}
230
231impl<J> Lane<J> {
232    fn new(server: ServerKey, windows: LaneWindows, retry_budget: u32) -> Self {
233        Self {
234            server,
235            windows,
236            advice: None,
237            session_cap: None,
238            retries: LaneRetries::new(retry_budget),
239            queued: [VecDeque::new(), VecDeque::new(), VecDeque::new()],
240            in_flight: Vec::new(),
241            last_progress: None,
242            paused_until: None,
243        }
244    }
245
246    /// W at `now`: the lane's own cap, lowered by advice still within its `ttl` and by the
247    /// account's live-session cap. Never below one.
248    fn sessions_window(&self, now: Instant) -> u32 {
249        let own = self.windows.sessions;
250        let advised = self.advice.map_or(own, |(advice, received)| {
251            advice.sessions_window(own, now.saturating_duration_since(received))
252        });
253        let capped = self.session_cap.map_or(advised, |cap| advised.min(cap));
254        capped.max(1)
255    }
256
257    /// P for a session granted now: the lane's own cap, lowered by the last `ranges` the server
258    /// advised. A session's own advice narrows it further once its create answers.
259    fn ranges_window(&self) -> u32 {
260        let own = self.windows.ranges;
261        self.advice
262            .map_or(own, |(advice, _)| advice.ranges_window(own))
263    }
264
265    /// Take the job this lane serves next: the front of its lowest non-empty tier.
266    fn pop_head(&mut self) -> Option<QueuedJob<J>> {
267        self.queued.iter_mut().find_map(VecDeque::pop_front)
268    }
269
270    fn queued_len(&self) -> usize {
271        self.queued.iter().map(VecDeque::len).sum()
272    }
273
274    fn paused_at(&self, now: Instant) -> bool {
275        self.paused_until.is_some_and(|until| now < until)
276    }
277}
278
279/// The per-server upload queue with one shared byte budget. See the module docs.
280#[derive(Debug)]
281pub struct UploadQueue<J> {
282    budget: u64,
283    in_use: u64,
284    stall_after: Duration,
285    /// The caps a newly opened lane starts with.
286    windows: LaneWindows,
287    /// The retry budget a newly opened lane starts with.
288    retry_budget: u32,
289    /// Lanes in the order they were opened; round-robin walks this order.
290    lanes: Vec<Lane<J>>,
291    /// The lane the next round-robin pass starts from.
292    cursor: usize,
293    /// Grants whose range the budget refused, in the order they first asked. The budget serves
294    /// them first-come: no range is reserved past the head of this line.
295    waiting: VecDeque<GrantId>,
296    next_grant: u64,
297    next_range: u64,
298}
299
300impl<J: Clone> UploadQueue<J> {
301    /// An empty queue whose lanes share `budget` bytes in flight (at least one byte), and give
302    /// their reservations up after `stall_after` without progress. Lanes open with the default
303    /// [`LaneWindows`] and a [`DEFAULT_LANE_RETRY_BUDGET`].
304    pub fn new(budget: u64, stall_after: Duration) -> Self {
305        Self {
306            budget: budget.max(1),
307            in_use: 0,
308            stall_after,
309            windows: LaneWindows::default(),
310            retry_budget: DEFAULT_LANE_RETRY_BUDGET,
311            lanes: Vec::new(),
312            cursor: 0,
313            waiting: VecDeque::new(),
314            next_grant: 0,
315            next_range: 0,
316        }
317    }
318
319    /// Open every lane after this with `windows` as its own caps. A lane already open keeps its
320    /// caps; [`Self::set_windows`] changes one.
321    #[must_use]
322    pub fn with_windows(mut self, windows: LaneWindows) -> Self {
323        self.windows = windows;
324        self
325    }
326
327    /// Open every lane after this with a retry budget of `retries`.
328    #[must_use]
329    pub fn with_retry_budget(mut self, retries: u32) -> Self {
330        self.retry_budget = retries;
331        self
332    }
333
334    /// The shared byte budget.
335    pub fn budget(&self) -> u64 {
336        self.budget
337    }
338
339    /// The bytes reserved by ranges in flight, across every lane.
340    pub fn in_use(&self) -> u64 {
341        self.in_use
342    }
343
344    /// `server`'s shared retry budget, opening its lane if it has none. Hand it to the client
345    /// that drives the lane's sessions ([`UploadClient::with_lane_retries`]) so the client's
346    /// request retries and this queue's [`Self::retry`] spend from one pool.
347    ///
348    /// [`UploadClient::with_lane_retries`]: crate::upload::UploadClient::with_lane_retries
349    pub fn lane_retries(&mut self, server: &ServerKey) -> LaneRetries {
350        self.lane_mut_or_open(server).retries.clone()
351    }
352
353    /// W for `server` at `now`: the lane's own cap lowered by fresh advice and the live-session
354    /// cap; the default cap for a server with no lane.
355    pub fn sessions_window(&self, server: &ServerKey, now: Instant) -> u32 {
356        self.lane(server)
357            .map_or(self.windows.sessions, |lane| lane.sessions_window(now))
358    }
359
360    /// The servers that hold a lane, in round-robin order.
361    pub fn servers(&self) -> impl Iterator<Item = &ServerKey> {
362        self.lanes.iter().map(|lane| &lane.server)
363    }
364
365    /// Jobs still queued (not in flight) on `server`'s lane; zero for a server with none.
366    pub fn queued(&self, server: &ServerKey) -> usize {
367        self.lane(server).map_or(0, Lane::queued_len)
368    }
369
370    /// Jobs in flight on `server`'s lane.
371    pub fn in_flight(&self, server: &ServerKey) -> usize {
372        self.lane(server).map_or(0, |lane| lane.in_flight.len())
373    }
374
375    /// Whether no lane holds any work, queued or in flight.
376    pub fn is_empty(&self) -> bool {
377        self.lanes
378            .iter()
379            .all(|lane| lane.queued_len() == 0 && lane.in_flight.is_empty())
380    }
381
382    /// Set `server`'s own caps (power saver or a thermal state lowers them), opening its lane if
383    /// it has none. A narrower window takes effect as work finishes; nothing in flight is
384    /// revoked, and a session already granted keeps its P.
385    pub fn set_windows(&mut self, server: &ServerKey, windows: LaneWindows) {
386        let lane = self.lane_mut_or_open(server);
387        lane.windows = LaneWindows::new(windows.sessions, windows.ranges);
388        tracing::debug!(
389            server = %server,
390            sessions = lane.windows.sessions,
391            ranges = lane.windows.ranges,
392            "upload queue: lane windows set"
393        );
394    }
395
396    /// Record the `X-Capsule-Advice` `server` sent at `received`, replacing any earlier advice.
397    /// Its `sessions` lowers W until its `ttl` runs out; its `ranges` lowers P for the sessions
398    /// granted after it. Advice can only lower the lane's own caps, never raise them.
399    pub fn set_advice(&mut self, server: &ServerKey, advice: ServerAdvice, received: Instant) {
400        let lane = self.lane_mut_or_open(server);
401        lane.advice = Some((advice, received));
402        tracing::debug!(
403            server = %server,
404            sessions = lane.sessions_window(received),
405            ranges = lane.ranges_window(),
406            ttl_s = advice.ttl().as_secs(),
407            "upload queue: lane advice applied"
408        );
409    }
410
411    /// Cap W at the account's live-session cap on `server` (at least one), so the lane never
412    /// opens a session the server would refuse for being one too many.
413    pub fn set_session_cap(&mut self, server: &ServerKey, cap: u32) {
414        let lane = self.lane_mut_or_open(server);
415        lane.session_cap = Some(cap.max(1));
416        tracing::debug!(server = %server, cap, "upload queue: live-session cap set");
417    }
418
419    /// Narrow grant `id`'s P to the in-flight cap its server advertised for that session (the
420    /// `ranges` of the advice on its create or `HEAD`). A session's P never widens. Returns the
421    /// session's P, or `None` when the grant is no longer in flight.
422    pub fn set_session_ranges(&mut self, id: GrantId, advice: &ServerAdvice) -> Option<u32> {
423        let (lane, at) = self.locate(id)?;
424        let flight = &mut self.lanes[lane].in_flight[at];
425        flight.ranges_window = advice.ranges_window(flight.ranges_window);
426        tracing::debug!(
427            grant = id.0,
428            ranges = flight.ranges_window,
429            "upload queue: session ranges window set"
430        );
431        Some(flight.ranges_window)
432    }
433
434    /// Queue `job` at the back of its tier on `server`'s lane, opening the lane if it has none.
435    pub fn enqueue(&mut self, server: &ServerKey, job: QueuedJob<J>) {
436        let lane = self.lane_mut_or_open(server);
437        tracing::trace!(server = %server, tier = ?job.tier, "upload queue: job queued");
438        lane.queued[tier_slot(job.tier)].push_back(job);
439    }
440
441    /// Replace everything `server`'s lane holds with `jobs`, derived from that server's own
442    /// truth on resume. Any job still in flight on the lane is superseded and its range
443    /// reservations released (the caller has stopped it); its id is returned and later reports
444    /// on it are ignored. The lane's windows, advice and retry budget are kept, and so is any
445    /// pause still running (a server's `Retry-After` binds whatever work the lane holds).
446    pub fn rebuild_lane(
447        &mut self,
448        server: &ServerKey,
449        jobs: impl IntoIterator<Item = QueuedJob<J>>,
450    ) -> Vec<GrantId> {
451        let lane = self.lane_mut_or_open(server);
452        let dropped_queued = lane.queued_len();
453        for tier in &mut lane.queued {
454            tier.clear();
455        }
456        let superseded: Vec<InFlight<J>> = lane.in_flight.drain(..).collect();
457        lane.last_progress = None;
458        for job in jobs {
459            lane.queued[tier_slot(job.tier)].push_back(job);
460        }
461        let queued = lane.queued_len();
462        let released: u64 = superseded.iter().map(InFlight::reserved).sum();
463        self.in_use -= released;
464        tracing::info!(
465            server = %server,
466            dropped_queued,
467            superseded = superseded.len(),
468            released,
469            queued,
470            "upload queue: lane rebuilt from server truth"
471        );
472        superseded.into_iter().map(|grant| grant.id).collect()
473    }
474
475    /// Remove every job `selects` picks from every lane, queued or in flight: the redaction a
476    /// delete makes of one asset's upload (Organization — Deletion State Machine), which spans
477    /// every server the asset was queued for. A job in flight is superseded and its range
478    /// reservations released (the caller stops it); its id is returned and later reports on it
479    /// are ignored. Every other job keeps its place, and no lane's windows or pause change.
480    pub fn withdraw(&mut self, selects: impl Fn(&J) -> bool) -> Vec<GrantId> {
481        let mut superseded = Vec::new();
482        let mut released = 0;
483        for lane in &mut self.lanes {
484            let mut dropped = 0;
485            for tier in &mut lane.queued {
486                let before = tier.len();
487                tier.retain(|queued| !selects(&queued.job));
488                dropped += before - tier.len();
489            }
490            let (stopped, kept): (Vec<InFlight<J>>, Vec<InFlight<J>>) = lane
491                .in_flight
492                .drain(..)
493                .partition(|flight| selects(&flight.job.job));
494            lane.in_flight = kept;
495            let lane_released: u64 = stopped.iter().map(InFlight::reserved).sum();
496            released += lane_released;
497            if dropped > 0 || !stopped.is_empty() {
498                tracing::info!(
499                    server = %lane.server,
500                    dropped_queued = dropped,
501                    superseded = stopped.len(),
502                    released = lane_released,
503                    "upload queue: jobs withdrawn"
504                );
505            }
506            superseded.extend(stopped.into_iter().map(|flight| flight.id));
507        }
508        self.in_use -= released;
509        superseded.sort_unstable();
510        superseded
511    }
512
513    /// Hold `server`'s lane until `until` (its backoff, or the server's `Retry-After`). Other
514    /// lanes are served meanwhile. A later deadline replaces an earlier one.
515    pub fn defer(&mut self, server: &ServerKey, until: Instant) {
516        let lane = self.lane_mut_or_open(server);
517        lane.paused_until = Some(lane.paused_until.map_or(until, |held| held.max(until)));
518        tracing::debug!(server = %server, "upload queue: lane deferred");
519    }
520
521    /// Admit the next job, if any lane can run one now. Admission reserves no bytes; the
522    /// session's ranges do, through [`Self::reserve_range`].
523    ///
524    /// Lanes are tried round-robin from the one after the lane served last. A lane is passed
525    /// over while it is paused, has no queued job, or already holds its W sessions in flight; a
526    /// lane never skips past its own head, so tier order holds inside it.
527    pub fn next(&mut self, now: Instant) -> Option<Grant<J>> {
528        let count = self.lanes.len();
529        for step in 0..count {
530            let index = (self.cursor + step) % count;
531            let lane = &mut self.lanes[index];
532            if lane.paused_at(now) || lane.in_flight.len() >= lane.sessions_window(now) as usize {
533                continue;
534            }
535            let Some(job) = lane.pop_head() else { continue };
536            let id = GrantId(self.next_grant);
537            self.next_grant += 1;
538            let ranges = lane.ranges_window();
539            lane.paused_until = None;
540            lane.last_progress = Some(now);
541            lane.in_flight.push(InFlight {
542                id,
543                job: job.clone(),
544                ranges_window: ranges,
545                ranges: Vec::new(),
546            });
547            let server = lane.server.clone();
548            let in_flight = lane.in_flight.len();
549            self.cursor = (index + 1) % count;
550            tracing::debug!(
551                server = %server,
552                grant = id.0,
553                tier = ?job.tier,
554                ranges,
555                in_flight,
556                "upload queue: job admitted"
557            );
558            return Some(Grant {
559                id,
560                server,
561                tier: job.tier,
562                ranges,
563                job: job.job,
564            });
565        }
566        None
567    }
568
569    /// Reserve `len` bytes of the shared budget for one range grant `id` is about to send.
570    ///
571    /// The reservation is the range's length clamped to the budget, so a range longer than the
572    /// whole budget still runs once the budget is otherwise free. It is refused while the
573    /// session holds its P ranges in flight ([`RangeRefused::WindowFull`]) or the budget left
574    /// cannot hold it ([`RangeRefused::BudgetFull`]); the caller waits for a release and asks
575    /// again. A reservation counts as progress on the lane.
576    ///
577    /// The budget serves waiting grants **first-come**: a grant refused for the budget joins a
578    /// line in the order it first asked, and while that line holds an earlier grant every later
579    /// ask is refused too, however little it wants. So a holder that releases its range and
580    /// asks for the next one in the same breath goes behind whoever was already waiting, and a
581    /// range clamped to the whole budget runs once the reservations ahead of it drain, rather
582    /// than waiting for every holder to stop on its own. A grant that leaves flight leaves the
583    /// line with it; a caller that stops asking for a grant it still holds must complete,
584    /// requeue or retry it, or the line waits on it.
585    pub fn reserve_range(
586        &mut self,
587        id: GrantId,
588        len: u64,
589        now: Instant,
590    ) -> Result<RangeId, RangeRefused> {
591        let Some((lane_at, at)) = self.locate(id) else {
592            return Err(RangeRefused::NotInFlight);
593        };
594        let reserved = len.min(self.budget);
595        let free = self.budget - self.in_use;
596        {
597            let flight = &self.lanes[lane_at].in_flight[at];
598            if flight.ranges.len() >= flight.ranges_window as usize {
599                tracing::trace!(
600                    grant = id.0,
601                    ranges = flight.ranges_window,
602                    "upload queue: session ranges window full"
603                );
604                return Err(RangeRefused::WindowFull);
605            }
606        }
607        self.prune_waiting();
608        let ahead = self
609            .waiting
610            .iter()
611            .take_while(|waiter| **waiter != id)
612            .count();
613        if ahead > 0 || reserved > free {
614            if !self.waiting.contains(&id) {
615                self.waiting.push_back(id);
616            }
617            tracing::trace!(
618                grant = id.0,
619                reserved,
620                free,
621                ahead,
622                "upload queue: range waits for the budget"
623            );
624            return Err(RangeRefused::BudgetFull);
625        }
626        if self.waiting.front() == Some(&id) {
627            self.waiting.pop_front();
628        }
629        let lane = &mut self.lanes[lane_at];
630        let flight = &mut lane.in_flight[at];
631        let range = RangeId(self.next_range);
632        self.next_range += 1;
633        flight.ranges.push((range, reserved));
634        lane.last_progress = Some(now);
635        self.in_use += reserved;
636        tracing::trace!(
637            server = %lane.server,
638            grant = id.0,
639            range = range.0,
640            reserved,
641            in_use = self.in_use,
642            "upload queue: range reserved"
643        );
644        Ok(range)
645    }
646
647    /// Range `range` returned (sent, refused or abandoned): release its bytes. It counts as
648    /// progress on its lane. Returns whether the reservation was still held; one released with
649    /// its session (a completion, requeue, revocation or rebuild) is already gone.
650    pub fn release_range(&mut self, range: RangeId, now: Instant) -> bool {
651        for lane in &mut self.lanes {
652            for flight in &mut lane.in_flight {
653                if let Some(at) = flight.ranges.iter().position(|(id, _)| *id == range) {
654                    let (_, reserved) = flight.ranges.remove(at);
655                    lane.last_progress = Some(now);
656                    self.in_use -= reserved;
657                    tracing::trace!(
658                        range = range.0,
659                        released = reserved,
660                        in_use = self.in_use,
661                        "upload queue: range released"
662                    );
663                    return true;
664                }
665            }
666        }
667        false
668    }
669
670    /// Grants still in flight that wait in the budget's line for a range, first-come. A caller
671    /// that wakes its waiters on a release wakes them again after a reservation while this is
672    /// not zero, so the next in line asks once the one ahead of it has been served.
673    pub fn waiting_for_budget(&self) -> usize {
674        self.waiting
675            .iter()
676            .filter(|waiter| self.locate(**waiter).is_some())
677            .count()
678    }
679
680    /// Ranges grant `id` holds in flight; zero for a grant no longer in flight.
681    pub fn ranges_in_flight(&self, id: GrantId) -> usize {
682        self.locate(id)
683            .map_or(0, |(lane, at)| self.lanes[lane].in_flight[at].ranges.len())
684    }
685
686    /// Record that grant `id` moved bytes, so its lane is not counted as stalled. Returns
687    /// whether the grant is still in flight.
688    pub fn progress(&mut self, id: GrantId, now: Instant) -> bool {
689        match self.locate(id) {
690            Some((lane, _)) => {
691                self.lanes[lane].last_progress = Some(now);
692                true
693            }
694            None => false,
695        }
696    }
697
698    /// Grant `id` finished (sent, merged, or failed for good): release every range it still
699    /// holds. Returns whether the grant was still in flight. The successes a lane's retry budget
700    /// earns back from are the requests that succeeded, which the client driving the lane
701    /// records on the shared budget ([`Self::lane_retries`]).
702    pub fn complete(&mut self, id: GrantId, now: Instant) -> bool {
703        let Some((lane, flight)) = self.take(id) else {
704            return false;
705        };
706        let lane = &mut self.lanes[lane];
707        lane.last_progress = Some(now);
708        tracing::debug!(
709            server = %lane.server,
710            grant = id.0,
711            released = flight.reserved(),
712            in_use = self.in_use,
713            "upload queue: job complete"
714        );
715        true
716    }
717
718    /// Grant `id` must run again because it was interrupted, not because it failed (a stall cut
719    /// or a cancelled task): release its ranges and return its job to the front of its tier.
720    /// Charges no retry. Returns whether the grant was still in flight.
721    pub fn requeue(&mut self, id: GrantId) -> bool {
722        let Some((lane, flight)) = self.take(id) else {
723            return false;
724        };
725        let lane = &mut self.lanes[lane];
726        tracing::debug!(server = %lane.server, grant = id.0, "upload queue: job requeued");
727        lane.queued[tier_slot(flight.job.tier)].push_front(flight.job);
728        true
729    }
730
731    /// Grant `id` failed with an error the classification permits retrying: release its ranges
732    /// and spend one retry from its lane's shared budget. While the budget holds, the job
733    /// returns to the front of its tier; once it is spent, the job leaves the queue and is
734    /// handed back, so a server that fails everything costs at most the lane's budget.
735    pub fn retry(&mut self, id: GrantId) -> RetryAdmission<J> {
736        let Some((lane, flight)) = self.take(id) else {
737            return RetryAdmission::NotInFlight;
738        };
739        let lane = &mut self.lanes[lane];
740        if lane.retries.try_spend() {
741            tracing::debug!(
742                server = %lane.server,
743                grant = id.0,
744                retries_left = lane.retries.remaining(),
745                "upload queue: job retried"
746            );
747            lane.queued[tier_slot(flight.job.tier)].push_front(flight.job);
748            RetryAdmission::Requeued
749        } else {
750            tracing::warn!(
751                server = %lane.server,
752                grant = id.0,
753                "upload queue: the lane's retry budget is spent; the job fails"
754            );
755            RetryAdmission::BudgetSpent(flight.job)
756        }
757    }
758
759    /// Take the budget back from every lane whose jobs in flight have made no progress for the
760    /// stall bound: their sessions and every range reservation they hold. Each such lane's jobs
761    /// return to the front of their tiers, charging no retry, and the lane is
762    /// not served for at least one more stall bound (longer where a later deadline is already
763    /// held), so the budget goes to the lanes still moving.
764    /// Returns the revoked grants, which the caller stops.
765    pub fn reclaim_stalled(&mut self, now: Instant) -> Vec<GrantId> {
766        let stall_after = self.stall_after;
767        let mut revoked = Vec::new();
768        let mut released = 0;
769        for lane in &mut self.lanes {
770            if lane.in_flight.is_empty() {
771                continue;
772            }
773            let stalled = lane
774                .last_progress
775                .is_none_or(|last| now.saturating_duration_since(last) >= stall_after);
776            if !stalled {
777                continue;
778            }
779            let flights: Vec<InFlight<J>> = lane.in_flight.drain(..).collect();
780            // Requeue in reverse so the earliest-granted job ends up at the front again.
781            for flight in flights.into_iter().rev() {
782                released += flight.reserved();
783                revoked.push(flight.id);
784                lane.queued[tier_slot(flight.job.tier)].push_front(flight.job);
785            }
786            // Keep a later deadline (a server's `Retry-After`) rather than shortening it.
787            let hold_off = now + stall_after;
788            lane.paused_until = Some(
789                lane.paused_until
790                    .map_or(hold_off, |held| held.max(hold_off)),
791            );
792            tracing::info!(
793                server = %lane.server,
794                stall_after_ms = stall_after.as_millis(),
795                "upload queue: lane made no progress; its budget is reclaimed"
796            );
797        }
798        self.in_use -= released;
799        revoked.sort_unstable();
800        revoked
801    }
802
803    fn lane(&self, server: &ServerKey) -> Option<&Lane<J>> {
804        self.lanes.iter().find(|lane| &lane.server == server)
805    }
806
807    fn lane_mut_or_open(&mut self, server: &ServerKey) -> &mut Lane<J> {
808        let index = if let Some(index) = self.lanes.iter().position(|lane| &lane.server == server) {
809            index
810        } else {
811            tracing::info!(server = %server, "upload queue: lane opened");
812            self.lanes
813                .push(Lane::new(server.clone(), self.windows, self.retry_budget));
814            self.lanes.len() - 1
815        };
816        &mut self.lanes[index]
817    }
818
819    /// The lane index and in-flight position of grant `id`.
820    fn locate(&self, id: GrantId) -> Option<(usize, usize)> {
821        self.lanes.iter().enumerate().find_map(|(lane, l)| {
822            l.in_flight
823                .iter()
824                .position(|flight| flight.id == id)
825                .map(|at| (lane, at))
826        })
827    }
828
829    /// Drop the grants that left flight from the budget's waiting line.
830    fn prune_waiting(&mut self) {
831        let mut waiting = std::mem::take(&mut self.waiting);
832        waiting.retain(|waiter| self.locate(*waiter).is_some());
833        self.waiting = waiting;
834    }
835
836    /// Remove grant `id` from flight and release every range it holds.
837    fn take(&mut self, id: GrantId) -> Option<(usize, InFlight<J>)> {
838        let (lane, at) = self.locate(id)?;
839        // `remove`, not `swap_remove`: flights stay in grant order for `reclaim_stalled`.
840        let flight = self.lanes[lane].in_flight.remove(at);
841        self.in_use -= flight.reserved();
842        Some((lane, flight))
843    }
844}
845
846#[cfg(test)]
847mod tests;