capsule_sdk/upload/committed.rs
1//! A session's committed set and the range scheduler's plan over it.
2//!
3//! The server holds the only truth about what a session has made durable: its **committed
4//! set**, a list of coalesced byte ranges it spells on `X-Capsule-Committed` as comma-separated
5//! inclusive ranges (`0-1048575,2097152-4194303`). The client re-plans from that set, never from
6//! its own record of what it sent (transfer upload doc, §Idempotency and Resumption).
7//!
8//! [`next_range`] is the scheduler's one decision: the **lowest gap first**. It picks the lowest
9//! byte neither committed nor in flight, and plans a range from it of at most the chunk size,
10//! ending early where the next committed or in-flight range begins. Every start it picks is the
11//! end of a range the server committed or the client planned, so a range is on the 4 KiB grid by
12//! construction, and a sequential schedule is the case of a window of one.
13//!
14//! Everything here is a pure function over values, so the scheduler is tested without a server.
15
16/// The protocol's block grid: every range starts on it, and every range but the one ending at the
17/// declared size has a length on it.
18pub const GRID: u64 = 4096;
19
20/// The most fragments a committed set holds on the wire (the server's fragment bound). A header
21/// naming more is malformed.
22pub const MAX_FRAGMENTS: usize = 64;
23
24/// A session's committed set: sorted, disjoint, coalesced, half-open byte ranges inside
25/// `[0, size)`.
26#[derive(Debug, Clone, Default, PartialEq, Eq)]
27pub struct CommittedSet {
28 ranges: Vec<(u64, u64)>,
29}
30
31impl CommittedSet {
32 /// Nothing committed.
33 #[must_use]
34 pub const fn empty() -> Self {
35 Self { ranges: Vec::new() }
36 }
37
38 /// The prefix `[0, end)`: what an older server's bare `X-Capsule-Offset` says it holds.
39 #[must_use]
40 pub fn prefix(end: u64) -> Self {
41 let mut set = Self::empty();
42 set.insert(0, end);
43 set
44 }
45
46 /// Parse `X-Capsule-Committed` for a session of `size` bytes.
47 ///
48 /// Every range must be well formed (`start-end`, inclusive, `start <= end`), ascending and
49 /// disjoint, inside the declared size, start on the grid, and end on it or at the size. A
50 /// value that breaks any rule is `None`, so a malformed header is ignored rather than
51 /// trusted: planning from it could put a range off the grid or over committed bytes. The
52 /// empty value is the empty set.
53 #[must_use]
54 pub fn parse(header: &str, size: u64) -> Option<Self> {
55 let header = header.trim();
56 if header.is_empty() {
57 return Some(Self::empty());
58 }
59 let mut ranges: Vec<(u64, u64)> = Vec::new();
60 for part in header.split(',') {
61 let (first, last) = part.trim().split_once('-')?;
62 let first: u64 = first.trim().parse().ok()?;
63 let last: u64 = last.trim().parse().ok()?;
64 let end = last.checked_add(1)?;
65 let well_placed = first < end
66 && end <= size
67 && first.is_multiple_of(GRID)
68 && (end.is_multiple_of(GRID) || end == size)
69 && ranges.last().is_none_or(|&(_, prev)| prev <= first);
70 if !well_placed {
71 return None;
72 }
73 ranges.push((first, end));
74 }
75 if ranges.len() > MAX_FRAGMENTS {
76 return None;
77 }
78 let mut set = Self::empty();
79 for (start, end) in ranges {
80 set.insert(start, end);
81 }
82 Some(set)
83 }
84
85 /// The set as `X-Capsule-Committed` spells it.
86 #[must_use]
87 pub fn to_header(&self) -> String {
88 self.ranges
89 .iter()
90 .map(|(start, end)| format!("{start}-{}", end - 1))
91 .collect::<Vec<_>>()
92 .join(",")
93 }
94
95 /// The coalesced half-open ranges, ascending.
96 #[must_use]
97 pub fn ranges(&self) -> &[(u64, u64)] {
98 &self.ranges
99 }
100
101 /// How many fragments the set holds.
102 #[must_use]
103 pub fn fragments(&self) -> usize {
104 self.ranges.len()
105 }
106
107 /// The committed prefix: the end of the range starting at zero, or zero.
108 #[must_use]
109 pub fn prefix_end(&self) -> u64 {
110 match self.ranges.first() {
111 Some(&(0, end)) => end,
112 _ => 0,
113 }
114 }
115
116 /// The bytes the set holds.
117 #[must_use]
118 pub fn len(&self) -> u64 {
119 self.ranges.iter().map(|(start, end)| end - start).sum()
120 }
121
122 /// Whether the set holds nothing.
123 #[must_use]
124 pub fn is_empty(&self) -> bool {
125 self.ranges.is_empty()
126 }
127
128 /// Whether every byte of `[0, size)` is committed.
129 #[must_use]
130 pub fn covers(&self, size: u64) -> bool {
131 size == 0 || self.ranges.first() == Some(&(0, size))
132 }
133
134 /// Whether every byte of `[start, end)` is committed.
135 #[must_use]
136 pub fn contains(&self, start: u64, end: u64) -> bool {
137 start >= end
138 || self
139 .ranges
140 .iter()
141 .any(|&(from, to)| from <= start && end <= to)
142 }
143
144 /// Whether any byte of `[start, end)` is in the set.
145 #[must_use]
146 pub fn overlaps(&self, start: u64, end: u64) -> bool {
147 start < end
148 && self
149 .ranges
150 .iter()
151 .any(|&(from, to)| from < end && start < to)
152 }
153
154 /// Add `[start, end)`, coalescing with whatever it touches. An empty range adds nothing.
155 pub fn insert(&mut self, start: u64, end: u64) {
156 if start >= end {
157 return;
158 }
159 let (mut start, mut end) = (start, end);
160 let mut kept = Vec::with_capacity(self.ranges.len() + 1);
161 for &(from, to) in &self.ranges {
162 if to < start || end < from {
163 kept.push((from, to));
164 } else {
165 start = start.min(from);
166 end = end.max(to);
167 }
168 }
169 let at = kept.partition_point(|&(from, _)| from < start);
170 kept.insert(at, (start, end));
171 self.ranges = kept;
172 }
173
174 /// Add every range of `other`.
175 pub fn union(&mut self, other: &Self) {
176 for &(start, end) in &other.ranges {
177 self.insert(start, end);
178 }
179 }
180}
181
182/// The next range to send: the lowest byte of `[0, size)` that is neither committed nor in
183/// `in_flight`, and from it at most `want` bytes, ending where the next committed or in-flight
184/// range begins. `None` once every byte is committed or in flight.
185///
186/// `want` is the chunk size the adaptive strategy names, a multiple of the grid; a range shorter
187/// than it either ends at the declared size or at a range that starts on the grid, so the plan
188/// stays on the grid.
189#[must_use]
190pub fn next_range(
191 committed: &CommittedSet,
192 in_flight: &[(u64, u64)],
193 size: u64,
194 want: u64,
195) -> Option<(u64, u64)> {
196 let mut taken: Vec<(u64, u64)> = committed
197 .ranges()
198 .iter()
199 .copied()
200 .chain(in_flight.iter().copied().filter(|(start, end)| start < end))
201 .collect();
202 taken.sort_unstable();
203 let mut start = 0;
204 let mut limit = size;
205 for &(from, to) in &taken {
206 if from > start {
207 limit = from;
208 break;
209 }
210 start = start.max(to);
211 }
212 if start >= size {
213 return None;
214 }
215 let end = start.saturating_add(want.max(1)).min(limit).min(size);
216 Some((start, end))
217}
218
219#[cfg(test)]
220mod tests;