capsule_sdk/upload/advice.rs
1//! Server advice and a session's relative expiry, read leniently.
2//!
3//! The server tunes clients it cannot redeploy through one `X-Capsule-Advice` header on session
4//! create and `HEAD`: an [RFC 9651] structured-field dictionary of integers whose members are
5//! `chunk` (suggested chunk bytes), `sessions` (in-flight sessions per lane), `ranges`
6//! (in-flight ranges per session) and `ttl` (seconds the advice holds) — networking design doc,
7//! Server Advice. Advice is never an instruction, so reading it never fails:
8//!
9//! - **Clamped.** Every member is clamped into bounds compiled into this client. A window member
10//! can only lower the client's own cap: the effective window is the smaller of the two.
11//! - **Lenient.** A member this client does not know is ignored, a member whose value is not an
12//! integer is treated as absent, and an absent member — or an absent or malformed header — is
13//! the client's own default.
14//! - **Bounded in time.** Advice older than its `ttl` is dropped, except `ranges`, which is fixed
15//! for the session's life.
16//!
17//! The session's own expiry travels beside the advice as seconds remaining
18//! (`X-Capsule-Session-Expires-In`, `X-Capsule-Session-Idle-Expires-In`), never as an instant,
19//! so a skewed device clock still schedules correctly ([`SessionExpiry`]).
20//!
21//! [RFC 9651]: https://www.rfc-editor.org/rfc/rfc9651
22
23use std::time::Duration;
24
25use super::{ALIGNMENT, PROTOCOL_MAX_CHUNK, PROTOCOL_MIN_CHUNK};
26
27/// The advice header.
28pub const ADVICE_HEADER: &str = "X-Capsule-Advice";
29/// Seconds until the session's lifetime cap.
30pub const EXPIRES_IN_HEADER: &str = "X-Capsule-Session-Expires-In";
31/// Seconds until the session's survival floor.
32pub const IDLE_EXPIRES_IN_HEADER: &str = "X-Capsule-Session-Idle-Expires-In";
33
34/// The most in-flight sessions per lane any advice can grant.
35pub const MAX_ADVISED_SESSIONS: u32 = 16;
36/// The most in-flight ranges per session any advice can grant: the protocol's ceiling on a
37/// session's in-flight cap (transfer upload design doc, Bounded fan-in).
38pub const MAX_ADVISED_RANGES: u32 = 16;
39/// How long advice that names no usable `ttl` holds.
40pub const DEFAULT_ADVICE_TTL: Duration = Duration::from_secs(300);
41/// The longest any advice holds, whatever its `ttl` says.
42pub const MAX_ADVICE_TTL: Duration = Duration::from_secs(3600);
43/// A header longer than this is not read at all: advice is a handful of integers, and a header
44/// past this length is a server bug or a hostile one, either way the client's defaults.
45pub const MAX_ADVICE_LEN: usize = 1024;
46
47/// What one `X-Capsule-Advice` header said, already clamped into this client's bounds.
48///
49/// Every member is `None` where the header did not carry a usable value; the accessors then
50/// answer the caller's own default.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct ServerAdvice {
53 chunk: Option<u64>,
54 sessions: Option<u32>,
55 ranges: Option<u32>,
56 ttl: Duration,
57}
58
59impl Default for ServerAdvice {
60 fn default() -> Self {
61 Self::absent()
62 }
63}
64
65impl ServerAdvice {
66 /// No advice: every accessor answers the caller's default.
67 pub const fn absent() -> Self {
68 Self {
69 chunk: None,
70 sessions: None,
71 ranges: None,
72 ttl: Duration::ZERO,
73 }
74 }
75
76 /// Read a header value, which may be missing.
77 ///
78 /// Never fails: a missing, oversized or malformed header is [`Self::absent`], an unknown
79 /// member is skipped, and a known member whose value is not an integer is treated as absent.
80 /// Where a member repeats, the last one wins, as RFC 9651 dictionaries specify.
81 pub fn parse(header: Option<&str>) -> Self {
82 let Some(header) = header else {
83 return Self::absent();
84 };
85 if header.len() > MAX_ADVICE_LEN {
86 tracing::debug!(len = header.len(), "ignoring an oversized advice header");
87 return Self::absent();
88 }
89 let mut chunk = None;
90 let mut sessions = None;
91 let mut ranges = None;
92 let mut ttl = None;
93 for member in members(header) {
94 let Some((key, value)) = integer_member(member) else {
95 continue;
96 };
97 match key {
98 "chunk" => chunk = Some(clamp_chunk(value)),
99 "sessions" => sessions = Some(clamp_window(value, MAX_ADVISED_SESSIONS)),
100 "ranges" => ranges = Some(clamp_window(value, MAX_ADVISED_RANGES)),
101 "ttl" => ttl = Some(clamp_ttl(value)),
102 // Additive: a member a newer server sends is one this client ignores.
103 _ => {}
104 }
105 }
106 let advice = Self {
107 chunk,
108 sessions,
109 ranges,
110 ttl: ttl.unwrap_or(DEFAULT_ADVICE_TTL),
111 };
112 tracing::trace!(?advice, "read server advice");
113 advice
114 }
115
116 /// Whether advice received `age` ago still holds.
117 pub fn is_fresh(&self, age: Duration) -> bool {
118 age < self.ttl
119 }
120
121 /// How long the advice holds from receipt.
122 pub fn ttl(&self) -> Duration {
123 self.ttl
124 }
125
126 /// The suggested chunk size, 4 KiB-aligned and within the protocol bounds, or `None` when
127 /// the advice named none or is older than its `ttl`.
128 pub fn chunk(&self, age: Duration) -> Option<u64> {
129 self.chunk.filter(|_| self.is_fresh(age))
130 }
131
132 /// The in-flight sessions a lane may hold: the smaller of `own` and the advice, or `own`
133 /// when the advice named none or is older than its `ttl`. Never below one.
134 pub fn sessions_window(&self, own: u32, age: Duration) -> u32 {
135 let own = own.max(1);
136 match self.sessions {
137 Some(advised) if self.is_fresh(age) => own.min(advised),
138 _ => own,
139 }
140 }
141
142 /// The in-flight ranges a session may hold: the smaller of `own` and the advice, or `own`
143 /// when the advice named none. Never below one.
144 ///
145 /// Takes no age: the server fixes a session's in-flight cap at creation, so the `ranges` a
146 /// session was advised holds for that session's whole life.
147 pub fn ranges_window(&self, own: u32) -> u32 {
148 let own = own.max(1);
149 self.ranges.map_or(own, |advised| own.min(advised))
150 }
151}
152
153/// A session's remaining lifetime as the server stated it, relative to the response.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
155pub struct SessionExpiry {
156 /// Time left until the session's lifetime cap, when the server said.
157 pub expires_in: Option<Duration>,
158 /// Time left until the session's survival floor — after which it may be discarded under
159 /// pressure — when the server said. Never more than [`Self::expires_in`] once read.
160 pub idle_expires_in: Option<Duration>,
161}
162
163impl SessionExpiry {
164 /// Read the two header values, either of which may be missing or malformed.
165 ///
166 /// A value that is not a non-negative integer number of seconds is absent. An idle expiry
167 /// past the lifetime cap is cut back to it, because the cap ends a session whatever its
168 /// progress.
169 pub fn parse(expires_in: Option<&str>, idle_expires_in: Option<&str>) -> Self {
170 let seconds = |value: Option<&str>| {
171 value
172 .map(str::trim)
173 .filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()))
174 .and_then(|text| text.parse::<u64>().ok())
175 .map(Duration::from_secs)
176 };
177 let expires_in = seconds(expires_in);
178 let idle_expires_in = match (seconds(idle_expires_in), expires_in) {
179 (Some(idle), Some(cap)) => Some(idle.min(cap)),
180 (idle, _) => idle,
181 };
182 Self {
183 expires_in,
184 idle_expires_in,
185 }
186 }
187}
188
189/// The dictionary's members, split at the commas that separate them.
190///
191/// A comma inside a quoted string or an inner list belongs to that value, so the split tracks
192/// both rather than cutting at every comma: a hostile string value cannot smuggle in a member.
193fn members(header: &str) -> impl Iterator<Item = &str> {
194 let mut parts = Vec::new();
195 let mut start = 0;
196 let mut in_string = false;
197 let mut escaped = false;
198 let mut depth = 0_usize;
199 for (index, byte) in header.bytes().enumerate() {
200 if in_string {
201 match byte {
202 _ if escaped => escaped = false,
203 b'\\' => escaped = true,
204 b'"' => in_string = false,
205 _ => {}
206 }
207 continue;
208 }
209 match byte {
210 b'"' => in_string = true,
211 b'(' => depth += 1,
212 b')' => depth = depth.saturating_sub(1),
213 b',' if depth == 0 => {
214 parts.push(&header[start..index]);
215 start = index + 1;
216 }
217 _ => {}
218 }
219 }
220 parts.push(&header[start..]);
221 parts.into_iter().map(str::trim)
222}
223
224/// A `key=integer` member, its parameters ignored; `None` for anything else.
225fn integer_member(member: &str) -> Option<(&str, i64)> {
226 let (key, rest) = member.split_once('=')?;
227 if !is_key(key) {
228 return None;
229 }
230 let value = rest.split(';').next().unwrap_or_default();
231 Some((key, parse_integer(value)?))
232}
233
234/// An RFC 9651 key: a lowercase letter or `*`, then lowercase letters, digits, `_`, `-`, `.`
235/// or `*`.
236fn is_key(key: &str) -> bool {
237 let mut bytes = key.bytes();
238 bytes
239 .next()
240 .is_some_and(|first| first.is_ascii_lowercase() || first == b'*')
241 && bytes.all(|byte| {
242 byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"_-.*".contains(&byte)
243 })
244}
245
246/// An RFC 9651 integer: an optional `-`, then one to fifteen digits, nothing else.
247fn parse_integer(text: &str) -> Option<i64> {
248 let digits = text.strip_prefix('-').unwrap_or(text);
249 if digits.is_empty() || digits.len() > 15 || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
250 return None;
251 }
252 text.parse().ok()
253}
254
255/// A chunk size aligned down to the 4 KiB grid and clamped into the protocol bounds.
256fn clamp_chunk(value: i64) -> u64 {
257 let value = u64::try_from(value).unwrap_or(0);
258 ((value / ALIGNMENT) * ALIGNMENT).clamp(PROTOCOL_MIN_CHUNK, PROTOCOL_MAX_CHUNK)
259}
260
261/// A window clamped into `[1, ceiling]`.
262fn clamp_window(value: i64, ceiling: u32) -> u32 {
263 u32::try_from(value.clamp(1, i64::from(ceiling))).unwrap_or(1)
264}
265
266/// A time to live clamped into `[0, MAX_ADVICE_TTL]`.
267fn clamp_ttl(value: i64) -> Duration {
268 let seconds = u64::try_from(value).unwrap_or(0);
269 Duration::from_secs(seconds).min(MAX_ADVICE_TTL)
270}
271
272#[cfg(test)]
273mod tests;