Sniff the file head separately when the browser probes a short range

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-20 15:12:38 +02:00
1 parent 404d9cc175
commit 2549e9e50d
2 files changed
+41 -7

No files matched your search

+12 -7
View File
@@ -357,8 +357,8 @@ impl AudioProxy {
/// Requests `audio_url` (from the database) with the browser's `Range`
/// (sanitized). A response with a generic binary type and no audio file
/// extension is passed through only when the file starts like audio
/// (read from this response when it starts at byte 0, otherwise from a
/// separate 16-byte range request).
/// (read from this response when it starts at byte 0 and is long
/// enough, otherwise from a separate 16-byte range request).
pub(crate) async fn fetch(
&self,
audio_url: &str,
@@ -428,12 +428,17 @@ impl AudioProxy {
let content_type = match check {
TypeCheck::Audio(content_type) => content_type,
TypeCheck::Content => {
let start = if starts_at_zero {
let mut start = Vec::new();
if starts_at_zero {
head = read_head(&mut upstream, SNIFF_BYTES).await?;
head_bytes(&head)
} else {
self.file_head(&final_url).await?
};
start = head_bytes(&head);
}
// A range past the start, or one that ends before the
// sniffed bytes (Safari and AVFoundation probe with
// `bytes=0-1`): the file's head comes from its own request.
if partial && start.len() < SNIFF_BYTES {
start = self.file_head(&final_url).await?;
}
sniff_audio(&start)
.ok_or_else(|| {
ProxyError::ContentType(format!(
+29
View File
@@ -259,6 +259,35 @@ async fn proxy_only_serves_audio() {
.map(|request| request["range"].clone())
.collect();
assert_eq!(ranges, ["bytes=100-199", "bytes=0-15"]);
// Safari and AVFoundation probe with a two-byte range from the start:
// too short to recognize the file, so its head is read separately.
let before = server.requests("/episode").len();
let probe = proxy
.fetch(&server.url("/episode"), Some("bytes=0-1"))
.await
.unwrap();
assert_eq!(probe.status, 206);
assert_eq!(probe.content_type.as_deref(), Some("audio/mpeg"));
assert_eq!(collect(probe.body).await, (mp3[..2].to_vec(), None));
let ranges: Vec<String> = server.requests("/episode")[before..]
.iter()
.map(|request| request["range"].clone())
.collect();
assert_eq!(ranges, ["bytes=0-1", "bytes=0-15"]);
// A long enough range from the start needs no second request.
let before = server.requests("/episode").len();
let start = proxy
.fetch(&server.url("/episode"), Some("bytes=0-99"))
.await
.unwrap();
assert_eq!(start.content_type.as_deref(), Some("audio/mpeg"));
assert_eq!(collect(start.body).await, (mp3[..100].to_vec(), None));
assert_eq!(server.requests("/episode").len(), before + 1);
// A probe of a file that is not audio is still refused.
assert!(matches!(
proxy.fetch(&server.url("/zip"), Some("bytes=0-1")).await,
Err(ProxyError::ContentType(_))
));
assert_eq!(
content_type("/binary.m4a", None).await.unwrap(),
"audio/mp4"