fix(media): read payloads through migration candidates

Co-authored-by: Brad Seiler <seiler@squareup.com>
Signed-off-by: Brad Seiler <seiler@squareup.com>
This commit is contained in:
coder
2026-08-07 01:37:10 -04:00
parent 3b79c3d006
commit ea7aea55bb
3 changed files with 375 additions and 86 deletions

View File

@@ -25,7 +25,10 @@ pub use keys::{
legacy_blob_key, legacy_thumb_key, read_candidates, sharded_blob_key, sharded_thumb_key,
MediaKeyError, MediaReadCandidates,
};
pub use storage::{BlobHeadMeta, BlobMeta, ByteStream, MediaStorage};
pub use storage::{
BlobHeadMeta, BlobMeta, BlobStream, ByteStream, MediaStorage, PayloadByteRange,
PayloadRangeRead,
};
pub use types::BlobDescriptor;
pub use upload::{process_file_upload, process_upload, process_video_upload};
pub use upload_record::{

View File

@@ -15,6 +15,59 @@ use serde::{Deserialize, Serialize};
/// A stream of byte chunks from S3, usable with `axum::body::Body::from_stream()`.
pub type ByteStream = Pin<Box<dyn futures_core::Stream<Item = Result<Bytes, MediaError>> + Send>>;
/// Full-object stream plus metadata resolved from one migration candidate.
pub struct BlobStream {
pub size: u64,
pub stream: ByteStream,
}
/// Parsed single-range request independent of object size.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PayloadByteRange {
/// `bytes=START-END` or `bytes=START-`. `end` is inclusive when present.
Absolute { start: u64, end: Option<u64> },
/// `bytes=-N`, the final N bytes.
Suffix(u64),
}
impl PayloadByteRange {
/// Resolve this range against a known total object size.
pub fn bounds(self, total: u64) -> Option<(u64, u64)> {
match self {
Self::Absolute { start, end } => {
if let Some(end) = end {
if start > end {
return None;
}
Some((start, end))
} else {
Some((start, u64::MAX))
}
}
Self::Suffix(n) => {
if n == 0 || total == 0 {
return None;
}
let start = total.saturating_sub(n);
Some((start, total.saturating_sub(1)))
}
}
}
}
/// Result of a tenant-scoped byte-range read.
pub enum PayloadRangeRead {
Satisfiable {
total: u64,
start: u64,
end: u64,
bytes: Vec<u8>,
},
Unsatisfiable {
total: u64,
},
}
/// S3-compatible object storage client.
pub struct MediaStorage {
bucket: Box<Bucket>,
@@ -234,7 +287,12 @@ impl MediaStorage {
/// Intended for HTTP 206 range responses on large video blobs.
pub async fn get_range(&self, key: &str, start: u64, end: u64) -> Result<Vec<u8>, MediaError> {
match self.bucket.get_object_range(key, start, Some(end)).await {
Ok(response) => Ok(response.to_vec()),
Ok(response) if response.status_code() == 404 => Err(MediaError::NotFound),
Ok(response) if (200..300).contains(&response.status_code()) => Ok(response.to_vec()),
Ok(response) => Err(MediaError::StorageError(format!(
"S3 range GET returned status {}",
response.status_code()
))),
Err(s3::error::S3Error::HttpFailWithBody(404, _)) => Err(MediaError::NotFound),
Err(e) => Err(MediaError::StorageError(e.to_string())),
}
@@ -246,15 +304,23 @@ impl MediaStorage {
/// The full object is never buffered — intended for streaming large
/// blobs (video) directly into HTTP responses via `Body::from_stream()`.
pub async fn get_stream(&self, key: &str) -> Result<ByteStream, MediaError> {
let response = self
.bucket
.get_object_stream(key)
.await
.map_err(|e| MediaError::StorageError(e.to_string()))?;
let response = match self.bucket.get_object_stream(key).await {
Ok(response) => response,
Err(s3::error::S3Error::HttpFailWithBody(404, _)) => {
return Err(MediaError::NotFound);
}
Err(e) => return Err(MediaError::StorageError(e.to_string())),
};
if response.status_code == 404 {
return Err(MediaError::NotFound);
}
if !(200..300).contains(&response.status_code) {
return Err(MediaError::StorageError(format!(
"S3 GET returned status {}",
response.status_code
)));
}
let stream = futures_util::StreamExt::map(response.bytes, |chunk| {
chunk.map_err(|e| MediaError::StorageError(e.to_string()))
@@ -400,6 +466,180 @@ impl MediaStorage {
}
}
/// HEAD a media payload according to the configured read layout.
pub async fn head_payload(
&self,
ctx: &TenantContext,
payload_name: &str,
) -> Result<BlobHeadMeta, MediaError> {
for candidate in self.ordered_read_candidates(ctx, payload_name)? {
match self.head_with_metadata(&candidate.key).await {
Ok(Some(meta)) => {
self.record_read_resolution(candidate.result);
return Ok(meta);
}
Ok(None) => {
self.record_candidate_missing(candidate);
}
Err(error) => {
self.record_read_resolution(ReadResolution::StorageError);
return Err(error);
}
}
}
self.record_read_resolution(ReadResolution::Missing);
Err(MediaError::NotFound)
}
/// Stream a media payload by trying read-layout candidates with the real GET.
///
/// A candidate that disappears between its metadata lookup and GET falls
/// through to the next layout only on `NotFound`; storage/auth/transport
/// errors are surfaced so fallback cannot mask an unhealthy store.
pub async fn get_payload_stream(
&self,
ctx: &TenantContext,
payload_name: &str,
) -> Result<BlobStream, MediaError> {
for candidate in self.ordered_read_candidates(ctx, payload_name)? {
let meta = match self.head_with_metadata(&candidate.key).await {
Ok(Some(meta)) => meta,
Ok(None) => {
self.record_candidate_missing(candidate);
continue;
}
Err(error) => {
self.record_read_resolution(ReadResolution::StorageError);
return Err(error);
}
};
match self.get_stream(&candidate.key).await {
Ok(stream) => {
self.record_read_resolution(candidate.result);
return Ok(BlobStream {
size: meta.size,
stream,
});
}
Err(MediaError::NotFound) => {
self.record_candidate_missing(candidate);
}
Err(error) => {
self.record_read_resolution(ReadResolution::StorageError);
return Err(error);
}
}
}
self.record_read_resolution(ReadResolution::Missing);
Err(MediaError::NotFound)
}
/// Read a bounded byte range from a media payload by trying read-layout
/// candidates with the real range GET.
pub async fn get_payload_range(
&self,
ctx: &TenantContext,
payload_name: &str,
requested_range: PayloadByteRange,
max_len: u64,
) -> Result<PayloadRangeRead, MediaError> {
for candidate in self.ordered_read_candidates(ctx, payload_name)? {
let total = match self.head_with_metadata(&candidate.key).await {
Ok(Some(meta)) => meta.size,
Ok(None) => {
self.record_candidate_missing(candidate);
continue;
}
Err(error) => {
self.record_read_resolution(ReadResolution::StorageError);
return Err(error);
}
};
let Some((start, end)) = requested_range.bounds(total) else {
self.record_read_resolution(candidate.result);
return Ok(PayloadRangeRead::Unsatisfiable { total });
};
if start >= total {
self.record_read_resolution(candidate.result);
return Ok(PayloadRangeRead::Unsatisfiable { total });
}
let max_end = start.saturating_add(max_len.max(1).saturating_sub(1));
let end = end.min(total.saturating_sub(1)).min(max_end);
match self.get_range(&candidate.key, start, end).await {
Ok(bytes) => {
self.record_read_resolution(candidate.result);
return Ok(PayloadRangeRead::Satisfiable {
total,
start,
end,
bytes,
});
}
Err(MediaError::NotFound) => {
self.record_candidate_missing(candidate);
}
Err(error) => {
self.record_read_resolution(ReadResolution::StorageError);
return Err(error);
}
}
}
self.record_read_resolution(ReadResolution::Missing);
Err(MediaError::NotFound)
}
fn ordered_read_candidates(
&self,
ctx: &TenantContext,
payload_name: &str,
) -> Result<Vec<ReadCandidate>, MediaError> {
let candidates = crate::keys::read_candidates(ctx, payload_name).map_err(|_| {
self.record_read_resolution(ReadResolution::Missing);
MediaError::NotFound
})?;
let mut ordered = Vec::with_capacity(2);
if self.migration_phase.reads_sharded() {
ordered.push(ReadCandidate {
key: candidates.sharded,
result: ReadResolution::Sharded,
});
}
if self.migration_phase.reads_legacy() {
ordered.push(ReadCandidate {
key: candidates.legacy,
result: ReadResolution::Legacy,
});
}
Ok(ordered)
}
fn record_candidate_missing(&self, candidate: ReadCandidate) {
if matches!(candidate.result, ReadResolution::Sharded)
&& self.migration_phase.reads_legacy()
{
metrics::counter!("buzz_media_s3_read_fallbacks_total").increment(1);
}
}
fn record_read_resolution(&self, resolution: ReadResolution) {
let result = match resolution {
ReadResolution::Sharded => "sharded",
ReadResolution::Legacy => "legacy",
ReadResolution::Missing => "missing",
ReadResolution::StorageError => "storage_error",
};
metrics::counter!("buzz_media_s3_read_resolutions_total", "result" => result).increment(1);
}
/// Copy an object within the media bucket using an S3 server-side copy.
pub async fn copy(&self, source: &str, destination: &str) -> Result<(), MediaError> {
self.bucket
@@ -658,6 +898,20 @@ mod tests {
}
}
#[derive(Debug, Clone)]
struct ReadCandidate {
key: String,
result: ReadResolution,
}
#[derive(Debug, Clone, Copy)]
enum ReadResolution {
Sharded,
Legacy,
Missing,
StorageError,
}
/// Metadata returned by HEAD — just enough for BUD-01 response headers.
pub struct BlobHeadMeta {
pub size: u64,

View File

@@ -19,7 +19,10 @@ use axum::{
use base64::Engine;
use buzz_audit::{AuditAction, NewAuditEntry};
use buzz_core::tenant::TenantContext;
use buzz_media::{BlobDescriptor, MediaError, UploadAttribution, UploadNetworkInfo};
use buzz_media::{
BlobDescriptor, MediaError, PayloadByteRange, PayloadRangeRead, UploadAttribution,
UploadNetworkInfo,
};
use crate::state::AppState;
@@ -658,13 +661,7 @@ pub(crate) async fn serve_blob_for_tenant(
"attachment"
};
let key = state
.media_storage
.resolve_read_key(
tenant,
&resolve_payload_name(&state.media_storage, tenant, sha256_ext).await?,
)
.await?;
let payload_name = resolve_payload_name(&state.media_storage, tenant, sha256_ext).await?;
// Parse optional Range header.
let range_header = req_headers
@@ -679,71 +676,71 @@ pub(crate) async fn serve_blob_for_tenant(
match single_range {
None => {
// Full response — 200 OK. Stream from S3 — never loads full blob into RAM.
let total = state
let blob = state
.media_storage
.head_with_metadata(&key)
.await?
.ok_or(MediaError::NotFound)?
.size;
let stream = state.media_storage.get_stream(&key).await?;
.get_payload_stream(tenant, &payload_name)
.await?;
let resp = axum::response::Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, &content_type)
.header(header::CONTENT_LENGTH, total.to_string())
.header(header::CONTENT_LENGTH, blob.size.to_string())
.header(header::CONTENT_DISPOSITION, disposition)
.header(header::CACHE_CONTROL, cache_control)
.header(header::CONTENT_SECURITY_POLICY, "default-src 'none'")
.header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
.header(header::ACCEPT_RANGES, "bytes")
.body(axum::body::Body::from_stream(stream))
.body(axum::body::Body::from_stream(blob.stream))
.map_err(|_| MediaError::Internal)?;
Ok(resp)
}
Some(range_str) => {
// S3-native single-range response, capped to bound request memory.
let total = state
let Some(requested_range) = parse_byte_range(&range_str) else {
let total = state
.media_storage
.head_payload(tenant, &payload_name)
.await?
.size;
return axum::response::Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::CONTENT_RANGE, format!("bytes */{total}"))
.body(axum::body::Body::empty())
.map_err(|_| MediaError::Internal);
};
match state
.media_storage
.head_with_metadata(&key)
.get_payload_range(tenant, &payload_name, requested_range, MAX_RANGE_CHUNK)
.await?
.ok_or(MediaError::NotFound)?
.size;
let parsed = parse_byte_range(&range_str, total);
match parsed {
Some((start, end)) => {
if start >= total {
return axum::response::Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::CONTENT_RANGE, format!("bytes */{total}"))
.body(axum::body::Body::empty())
.map_err(|_| MediaError::Internal);
}
let end = end.min(total.saturating_sub(1));
let end = end
.min(start.saturating_add(MAX_RANGE_CHUNK - 1))
.min(total.saturating_sub(1));
let chunk = state.media_storage.get_range(&key, start, end).await?;
{
PayloadRangeRead::Satisfiable {
total,
start,
end,
bytes,
} => {
let content_range = format!("bytes {start}-{end}/{total}");
Ok(axum::response::Response::builder()
.status(StatusCode::PARTIAL_CONTENT)
.header(header::CONTENT_TYPE, &content_type)
.header(header::CONTENT_RANGE, content_range)
.header(header::CONTENT_LENGTH, chunk.len().to_string())
.header(header::CONTENT_LENGTH, bytes.len().to_string())
.header(header::CONTENT_DISPOSITION, disposition)
.header(header::ACCEPT_RANGES, "bytes")
.header(header::CACHE_CONTROL, cache_control)
.header(header::CONTENT_SECURITY_POLICY, "default-src 'none'")
.header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
.body(axum::body::Body::from(chunk))
.body(axum::body::Body::from(bytes))
.map_err(|_| MediaError::Internal)?)
}
PayloadRangeRead::Unsatisfiable { total } => {
Ok(axum::response::Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::CONTENT_RANGE, format!("bytes */{total}"))
.body(axum::body::Body::empty())
.map_err(|_| MediaError::Internal)?)
}
None => Ok(axum::response::Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::CONTENT_RANGE, format!("bytes */{total}"))
.body(axum::body::Body::empty())
.map_err(|_| MediaError::Internal)?),
}
}
}
@@ -751,41 +748,44 @@ pub(crate) async fn serve_blob_for_tenant(
/// Parse a `Range: bytes=START-END` header value.
///
/// Returns `Some((start, end))` for a valid absolute or suffix range.
/// Returns a syntactically valid single range. Object-size dependent validation
/// is deferred to the storage read so fallback candidates resolve against the
/// same object that is actually read.
/// Supported forms:
/// - `bytes=START-END` → absolute range
/// - `bytes=START-` → from START to end of file
/// - `bytes=-N` → last N bytes (suffix range, per RFC 9110 §14.1.2)
///
/// Returns `None` for malformed values or non-bytes units — callers respond with 416.
fn parse_byte_range(range: &str, total: u64) -> Option<(u64, u64)> {
fn parse_byte_range(range: &str) -> Option<PayloadByteRange> {
let range = range.strip_prefix("bytes=")?;
// Suffix range: "bytes=-N" → last N bytes of the file.
if let Some(suffix) = range.strip_prefix('-') {
let n: u64 = suffix.parse().ok()?;
if n == 0 || total == 0 {
if n == 0 {
return None;
}
let start = total.saturating_sub(n);
return Some((start, total - 1));
return Some(PayloadByteRange::Suffix(n));
}
let (start_str, end_str) = range.split_once('-')?;
let start: u64 = start_str.parse().ok()?;
// Open-ended range: "bytes=START-" → from start to end of file.
let end: u64 = if end_str.is_empty() {
u64::MAX
let end = if end_str.is_empty() {
None
} else {
end_str.parse().ok()?
Some(end_str.parse().ok()?)
};
if start > end {
return None;
if let Some(end) = end {
if start > end {
return None;
}
}
Some((start, end))
Some(PayloadByteRange::Absolute { start, end })
}
/// HEAD /media/{sha256_ext} — Blossom BUD-01 existence check.
@@ -832,15 +832,13 @@ pub async fn head_blob(
sidecar_mime
};
let key = state
let payload_name = resolve_payload_name(&state.media_storage, &tenant, &sha256_ext).await?;
match state
.media_storage
.resolve_read_key(
&tenant,
&resolve_payload_name(&state.media_storage, &tenant, &sha256_ext).await?,
)
.await?;
match state.media_storage.head_with_metadata(&key).await? {
Some(meta) => {
.head_payload(&tenant, &payload_name)
.await
{
Ok(meta) => {
let size_str = meta.size.to_string();
Ok((
StatusCode::OK,
@@ -853,7 +851,8 @@ pub async fn head_blob(
)
.into_response())
}
None => Ok(StatusCode::NOT_FOUND.into_response()),
Err(MediaError::NotFound) => Ok(StatusCode::NOT_FOUND.into_response()),
Err(error) => Err(error),
}
}
@@ -1300,60 +1299,93 @@ mod tests {
#[test]
fn test_parse_byte_range_basic() {
assert_eq!(parse_byte_range("bytes=0-499", 1000), Some((0, 499)));
assert_eq!(parse_byte_range("bytes=500-999", 1000), Some((500, 999)));
assert_eq!(
parse_byte_range("bytes=0-499"),
Some(PayloadByteRange::Absolute {
start: 0,
end: Some(499)
})
);
assert_eq!(
parse_byte_range("bytes=500-999"),
Some(PayloadByteRange::Absolute {
start: 500,
end: Some(999)
})
);
}
#[test]
fn test_parse_byte_range_open_ended() {
// "bytes=500-" means from 500 to end of file
assert_eq!(parse_byte_range("bytes=500-", 1000), Some((500, u64::MAX)));
assert_eq!(
parse_byte_range("bytes=500-"),
Some(PayloadByteRange::Absolute {
start: 500,
end: None
})
);
}
#[test]
fn test_parse_byte_range_suffix() {
// "bytes=-500" on a 1000-byte file → last 500 bytes
assert_eq!(parse_byte_range("bytes=-500", 1000), Some((500, 999)));
assert_eq!(
parse_byte_range("bytes=-500"),
Some(PayloadByteRange::Suffix(500))
);
}
#[test]
fn test_parse_byte_range_suffix_larger_than_file() {
// Suffix larger than file → clamp to start of file
assert_eq!(parse_byte_range("bytes=-5000", 1000), Some((0, 999)));
assert_eq!(
parse_byte_range("bytes=-5000"),
Some(PayloadByteRange::Suffix(5000))
);
}
#[test]
fn test_parse_byte_range_suffix_zero() {
// "bytes=-0" is nonsensical → None
assert_eq!(parse_byte_range("bytes=-0", 1000), None);
assert_eq!(parse_byte_range("bytes=-0"), None);
}
#[test]
fn test_parse_byte_range_suffix_empty_file() {
// Suffix on empty file → None
assert_eq!(parse_byte_range("bytes=-500", 0), None);
fn test_parse_byte_range_suffix_defers_empty_file_handling() {
// Empty-file handling needs object size, so storage resolves it after selecting a candidate.
assert_eq!(
parse_byte_range("bytes=-500"),
Some(PayloadByteRange::Suffix(500))
);
}
#[test]
fn test_parse_byte_range_rejects_inverted() {
// start > end is invalid
assert_eq!(parse_byte_range("bytes=999-0", 1000), None);
assert_eq!(parse_byte_range("bytes=999-0"), None);
}
#[test]
fn test_parse_byte_range_rejects_non_bytes_unit() {
assert_eq!(parse_byte_range("items=0-10", 1000), None);
assert_eq!(parse_byte_range("items=0-10"), None);
}
#[test]
fn test_parse_byte_range_rejects_malformed() {
assert_eq!(parse_byte_range("bytes=abc-def", 1000), None);
assert_eq!(parse_byte_range("garbage", 1000), None);
assert_eq!(parse_byte_range("bytes=", 1000), None);
assert_eq!(parse_byte_range("bytes=abc-def"), None);
assert_eq!(parse_byte_range("garbage"), None);
assert_eq!(parse_byte_range("bytes="), None);
}
#[test]
fn test_parse_byte_range_zero_start() {
assert_eq!(parse_byte_range("bytes=0-0", 1000), Some((0, 0)));
assert_eq!(
parse_byte_range("bytes=0-0"),
Some(PayloadByteRange::Absolute {
start: 0,
end: Some(0)
})
);
}
}