1mod cache;
8mod fetch;
9mod location;
10mod protocol;
11mod reader;
12
13use std::collections::HashMap;
14use std::io::Read;
15use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex, PoisonError};
17use std::time::Duration;
18
19use alpha2_media::CancelToken;
20
21pub use location::{SourceLocation, decode_error};
22pub use reader::{RemoteReader, RemoteStream};
23
24use cache::BlockCache;
25use protocol::ObjectFacts;
26
27pub const BLOCK_BYTES: u64 = 256 * 1024;
29pub const MIN_CACHE_BYTES: u64 = 4 * 1024 * 1024;
31pub const DEFAULT_CACHE_BYTES: u64 = 64 * 1024 * 1024;
33pub const MAX_ATTEMPTS: usize = 5;
35pub const BACKOFF: [Duration; MAX_ATTEMPTS - 1] = [
37 Duration::from_millis(250),
38 Duration::from_millis(500),
39 Duration::from_secs(1),
40 Duration::from_secs(2),
41];
42pub const NO_PROGRESS_LIMIT: Duration = Duration::from_secs(30);
44pub const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);
46pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
48pub const HEAD_TIMEOUT: Duration = Duration::from_secs(15);
50pub const BODY_IDLE_TIMEOUT: Duration = Duration::from_secs(15);
52const WAIT_POLL: Duration = Duration::from_millis(5);
53
54#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct RangeRequest {
57 pub url: String,
59 pub first: u64,
61 pub last: u64,
63 pub precondition: Option<Precondition>,
65}
66
67impl RangeRequest {
68 #[must_use]
70 pub fn range_header(&self) -> String {
71 format!("bytes={}-{}", self.first, self.last)
72 }
73}
74
75#[derive(Clone, Debug, PartialEq, Eq)]
77pub enum Precondition {
78 IfMatch(String),
80 IfUnmodifiedSince(String),
82}
83
84impl Precondition {
85 #[must_use]
87 pub fn header(&self) -> (&'static str, &str) {
88 match self {
89 Self::IfMatch(tag) => ("If-Match", tag),
90 Self::IfUnmodifiedSince(date) => ("If-Unmodified-Since", date),
91 }
92 }
93}
94
95#[derive(Clone, Debug, Default, PartialEq, Eq)]
97pub struct ResponseHeaders {
98 pub content_range: Option<String>,
100 pub content_encoding: Option<String>,
102 pub content_type: Option<String>,
104 pub etag: Option<String>,
106 pub last_modified: Option<String>,
108 pub retry_after: Option<String>,
110}
111
112pub struct RangeResponse {
114 pub status: u16,
116 pub headers: ResponseHeaders,
118 pub body: Box<dyn Read + Send>,
120}
121
122impl RangeResponse {
123 fn retry_delay(&self) -> Option<Duration> {
124 self.headers
125 .retry_after
126 .as_deref()
127 .and_then(|value| protocol::retry_after(value, std::time::SystemTime::now()))
128 }
129}
130
131#[derive(Clone, Debug, PartialEq, Eq)]
133pub enum TransportFailure {
134 Refused {
136 policy: RefusalPolicy,
138 message: String,
140 },
141 Tls(String),
143 Unreachable(String),
145 Rejected(String),
148}
149
150#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub enum RefusalPolicy {
153 Origins,
155 Redirect,
157 Address,
159}
160
161impl RefusalPolicy {
162 #[must_use]
164 pub const fn name(self) -> &'static str {
165 match self {
166 Self::Origins => "origins",
167 Self::Redirect => "redirect",
168 Self::Address => "address",
169 }
170 }
171}
172
173pub trait RangeTransport: Send + Sync {
175 fn get(&self, request: &RangeRequest) -> Result<RangeResponse, TransportFailure>;
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum RemoteFailure {
185 Refused(RefusalPolicy),
187 TlsFailed,
189 Unreachable,
191 Busy {
193 retry_after_ms: u64,
195 },
196 RangeUnsupported,
198 Rejected,
200 Changed,
202 Offline,
204 Empty,
206 Cancelled,
208}
209
210impl RemoteFailure {
211 #[must_use]
213 pub const fn code(self) -> &'static str {
214 match self {
215 Self::Refused(_) => "MEDIA_REFUSED",
216 Self::TlsFailed => "MEDIA_TLS_FAILED",
217 Self::Unreachable => "MEDIA_UNREACHABLE",
218 Self::Busy { .. } => "MEDIA_BUSY",
219 Self::RangeUnsupported | Self::Empty => "MEDIA_RANGE_UNSUPPORTED",
220 Self::Rejected | Self::Offline => "MEDIA_REJECTED",
221 Self::Changed => "MEDIA_CHANGED",
222 Self::Cancelled => "CANCELLED",
223 }
224 }
225}
226
227#[derive(Clone, Debug, PartialEq, Eq)]
229pub struct RemoteError {
230 pub failure: RemoteFailure,
232 pub message: String,
234 pub status: Option<u16>,
236 pub url: Option<String>,
238}
239
240impl RemoteError {
241 pub fn new(failure: RemoteFailure, message: impl Into<String>) -> Self {
243 Self {
244 failure,
245 message: message.into(),
246 status: None,
247 url: None,
248 }
249 }
250
251 #[must_use]
253 pub fn with_url(mut self, shown: &str) -> Self {
254 self.url = Some(shown.to_owned());
255 self
256 }
257
258 #[must_use]
260 pub const fn with_status(mut self, status: u16) -> Self {
261 self.status = Some(status);
262 self
263 }
264
265 fn cancelled() -> Self {
266 Self::new(RemoteFailure::Cancelled, "the request was cancelled")
267 }
268
269 #[must_use]
271 pub fn of(error: &std::io::Error) -> Option<&Self> {
272 error.get_ref()?.downcast_ref()
273 }
274}
275
276impl std::fmt::Display for RemoteError {
277 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 formatter.write_str(&self.message)
279 }
280}
281
282impl std::error::Error for RemoteError {}
283
284impl From<TransportFailure> for RemoteError {
285 fn from(failure: TransportFailure) -> Self {
286 match failure {
287 TransportFailure::Refused { policy, message } => {
288 Self::new(RemoteFailure::Refused(policy), message)
289 }
290 TransportFailure::Tls(message) => Self::new(RemoteFailure::TlsFailed, message),
291 TransportFailure::Unreachable(message) => {
292 Self::new(RemoteFailure::Unreachable, message)
293 }
294 TransportFailure::Rejected(message) => Self::new(RemoteFailure::Rejected, message),
295 }
296 }
297}
298
299impl From<RemoteError> for std::io::Error {
300 fn from(error: RemoteError) -> Self {
301 Self::other(error)
302 }
303}
304
305#[must_use]
308pub fn shown_url(url: &str) -> String {
309 let Some((scheme, rest)) = url.split_once("://") else {
310 return url.to_owned();
311 };
312 if scheme.is_empty()
313 || !scheme
314 .bytes()
315 .all(|byte| byte.is_ascii_alphanumeric() || b"+-.".contains(&byte))
316 {
317 return url.to_owned();
318 }
319 let rest = rest.split(['?', '#']).next().unwrap_or_default();
320 let (authority, path) = rest.find('/').map_or((rest, ""), |at| rest.split_at(at));
321 let host = authority
322 .rsplit_once('@')
323 .map_or(authority, |(_, host)| host);
324 format!("{scheme}://{host}{path}")
325}
326
327pub(crate) trait Clock: Send + Sync {
328 fn now(&self) -> Duration;
329 fn sleep(&self, duration: Duration, stop: &dyn Fn() -> bool);
330}
331
332struct AwakeClock(alpha2_os::AwakeInstant);
333
334impl Clock for AwakeClock {
335 fn now(&self) -> Duration {
336 self.0.elapsed()
337 }
338
339 fn sleep(&self, duration: Duration, stop: &dyn Fn() -> bool) {
340 let until = self.now() + duration;
341 while !stop() {
342 let left = until.saturating_sub(self.now());
343 if left.is_zero() {
344 break;
345 }
346 std::thread::sleep(left.min(WAIT_POLL));
347 }
348 }
349}
350
351#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
353pub struct RemoteCounts {
354 pub bytes: u64,
356 pub requests: u64,
358 pub retries: u64,
360 pub read_wait_ms: u64,
362}
363
364#[derive(Default)]
365struct Counters {
366 bytes: AtomicU64,
367 requests: AtomicU64,
368 retries: AtomicU64,
369 read_wait_ns: AtomicU64,
370}
371
372struct Shared {
373 transport: Arc<dyn RangeTransport>,
374 cancel: CancelToken,
375 clock: Arc<dyn Clock>,
376 cache: Mutex<BlockCache>,
377 counters: Counters,
378 readers: AtomicUsize,
379 next_object: AtomicU64,
380}
381
382impl Shared {
383 fn cache(&self) -> std::sync::MutexGuard<'_, BlockCache> {
384 self.cache.lock().unwrap_or_else(PoisonError::into_inner)
385 }
386
387 fn window_cap(&self) -> u64 {
388 let readers = self.readers.load(Ordering::Acquire).max(1) as u64;
389 let share = self.cache().budget() / 2 / readers;
390 (share / BLOCK_BYTES).max(1) * BLOCK_BYTES
391 }
392
393 fn waiting(&self) -> Result<(), RemoteError> {
394 crate::request_watch::beat_request();
395 crate::recovery::report_decode_progress();
396 if self.cancel.is_cancelled() {
397 return Err(RemoteError::cancelled());
398 }
399 Ok(())
400 }
401
402 fn waited(&self, since: Duration) {
403 let waited = self.clock.now().saturating_sub(since);
404 crate::recovery::report_input_wait(waited);
405 self.counters.read_wait_ns.fetch_add(
406 u64::try_from(waited.as_nanos()).unwrap_or(u64::MAX),
407 Ordering::Relaxed,
408 );
409 }
410}
411
412pub struct RemoteSession {
416 shared: Arc<Shared>,
417 objects: Mutex<HashMap<String, Arc<RemoteObject>>>,
418}
419
420impl RemoteSession {
421 #[must_use]
424 pub fn new(transport: Arc<dyn RangeTransport>, cancel: CancelToken, cache_bytes: u64) -> Self {
425 Self::with_clock(
426 transport,
427 cancel,
428 cache_bytes,
429 Arc::new(AwakeClock(alpha2_os::AwakeInstant::now())),
430 )
431 }
432
433 pub(crate) fn with_clock(
434 transport: Arc<dyn RangeTransport>,
435 cancel: CancelToken,
436 cache_bytes: u64,
437 clock: Arc<dyn Clock>,
438 ) -> Self {
439 Self {
440 shared: Arc::new(Shared {
441 transport,
442 cancel,
443 clock,
444 cache: Mutex::new(BlockCache::new(cache_bytes)),
445 counters: Counters::default(),
446 readers: AtomicUsize::new(0),
447 next_object: AtomicU64::new(0),
448 }),
449 objects: Mutex::new(HashMap::new()),
450 }
451 }
452
453 pub fn open(&self, url: &str) -> Result<Arc<RemoteObject>, RemoteError> {
460 if let Some(object) = self
461 .objects
462 .lock()
463 .unwrap_or_else(PoisonError::into_inner)
464 .get(url)
465 {
466 return Ok(Arc::clone(object));
467 }
468 let id = self.shared.next_object.fetch_add(1, Ordering::Relaxed);
469 let (facts, first_block) = fetch::probe(&self.shared, url)?;
470 self.shared.cache().insert((id, 0), Arc::from(first_block));
471 let object = Arc::new(RemoteObject {
472 id,
473 url: url.to_owned(),
474 shown: shown_url(url),
475 facts,
476 shared: Arc::clone(&self.shared),
477 });
478 Ok(Arc::clone(
479 self.objects
480 .lock()
481 .unwrap_or_else(PoisonError::into_inner)
482 .entry(url.to_owned())
483 .or_insert(object),
484 ))
485 }
486
487 #[must_use]
489 pub fn counts(&self) -> RemoteCounts {
490 let counters = &self.shared.counters;
491 RemoteCounts {
492 bytes: counters.bytes.load(Ordering::Relaxed),
493 requests: counters.requests.load(Ordering::Relaxed),
494 retries: counters.retries.load(Ordering::Relaxed),
495 read_wait_ms: counters.read_wait_ns.load(Ordering::Relaxed) / 1_000_000,
496 }
497 }
498
499 #[must_use]
501 pub fn cached_bytes(&self) -> u64 {
502 self.shared.cache().held()
503 }
504}
505
506pub struct RemoteObject {
508 id: u64,
509 url: String,
510 shown: String,
511 facts: ObjectFacts,
512 shared: Arc<Shared>,
513}
514
515impl RemoteObject {
516 #[must_use]
518 pub const fn len(&self) -> u64 {
519 self.facts.total
520 }
521
522 #[must_use]
524 pub const fn is_empty(&self) -> bool {
525 self.facts.total == 0
526 }
527
528 #[must_use]
530 pub fn shown_url(&self) -> &str {
531 &self.shown
532 }
533
534 #[must_use]
536 pub fn etag(&self) -> Option<&str> {
537 self.facts.etag.as_deref()
538 }
539
540 #[must_use]
542 pub fn last_modified(&self) -> Option<&str> {
543 self.facts.last_modified.as_deref()
544 }
545
546 #[must_use]
548 pub fn last_modified_ms(&self) -> Option<i64> {
549 let date = protocol::http_date(self.last_modified()?)?;
550 let since = date
551 .duration_since(std::time::SystemTime::UNIX_EPOCH)
552 .ok()?;
553 i64::try_from(since.as_millis()).ok()
554 }
555
556 #[must_use]
559 pub fn validator(&self) -> &str {
560 self.etag()
561 .or_else(|| self.last_modified())
562 .unwrap_or_default()
563 }
564
565 #[must_use]
567 pub fn reader(self: &Arc<Self>) -> RemoteReader {
568 RemoteReader::new(Arc::clone(self))
569 }
570
571 #[must_use]
574 pub fn stream(self: &Arc<Self>) -> RemoteStream {
575 RemoteStream::new(Arc::clone(self))
576 }
577}
578
579#[cfg(test)]
580#[path = "../remote_tests.rs"]
581mod tests;