garage-unix-socket/src/api/s3_get.rs

257 lines
6.5 KiB
Rust
Raw Normal View History

2020-04-24 18:47:11 +00:00
use std::sync::Arc;
use std::time::{Duration, UNIX_EPOCH};
use futures::stream::*;
use hyper::body::Bytes;
2020-05-04 13:09:23 +00:00
use hyper::{Body, Request, Response, StatusCode};
2020-04-24 18:47:11 +00:00
use garage_util::error::Error;
use garage_table::EmptyKey;
2020-07-07 11:59:22 +00:00
use garage_model::garage::Garage;
use garage_model::object_table::*;
2020-04-24 18:47:11 +00:00
2020-07-08 15:34:37 +00:00
fn object_headers(
version: &ObjectVersion,
version_meta: &ObjectVersionMeta,
) -> http::response::Builder {
2020-04-24 18:47:11 +00:00
let date = UNIX_EPOCH + Duration::from_millis(version.timestamp);
let date_str = httpdate::fmt_http_date(date);
2020-07-09 15:04:43 +00:00
let mut resp = Response::builder()
2020-07-08 15:34:37 +00:00
.header(
"Content-Type",
version_meta.headers.content_type.to_string(),
)
2020-07-08 15:33:24 +00:00
.header("Content-Length", format!("{}", version_meta.size))
.header("ETag", version_meta.etag.to_string())
2020-04-24 18:47:11 +00:00
.header("Last-Modified", date_str)
2020-07-09 15:04:43 +00:00
.header("Accept-Ranges", format!("bytes"));
for (k, v) in version_meta.headers.other.iter() {
resp = resp.header(k, v.to_string());
}
2020-07-09 15:04:43 +00:00
resp
2020-04-24 18:47:11 +00:00
}
pub async fn handle_head(
garage: Arc<Garage>,
bucket: &str,
key: &str,
) -> Result<Response<Body>, Error> {
2020-04-24 18:47:11 +00:00
let object = match garage
.object_table
.get(&bucket.to_string(), &key.to_string())
.await?
{
None => return Err(Error::NotFound),
Some(o) => o,
};
let version = match object
.versions()
.iter()
.rev()
2020-04-26 18:55:13 +00:00
.filter(|v| v.is_data())
2020-04-24 18:47:11 +00:00
.next()
{
Some(v) => v,
None => return Err(Error::NotFound),
};
2020-07-08 15:34:37 +00:00
let version_meta = match &version.state {
ObjectVersionState::Complete(ObjectVersionData::Inline(meta, _)) => meta,
ObjectVersionState::Complete(ObjectVersionData::FirstBlock(meta, _)) => meta,
_ => unreachable!(),
};
2020-04-24 18:47:11 +00:00
let body: Body = Body::from(vec![]);
2020-07-08 15:33:24 +00:00
let response = object_headers(&version, version_meta)
2020-04-24 18:47:11 +00:00
.status(StatusCode::OK)
.body(body)
.unwrap();
Ok(response)
}
pub async fn handle_get(
garage: Arc<Garage>,
2020-05-04 13:09:23 +00:00
req: &Request<Body>,
2020-04-24 18:47:11 +00:00
bucket: &str,
key: &str,
) -> Result<Response<Body>, Error> {
2020-04-24 18:47:11 +00:00
let object = match garage
.object_table
.get(&bucket.to_string(), &key.to_string())
.await?
{
None => return Err(Error::NotFound),
Some(o) => o,
};
let last_v = match object
.versions()
.iter()
.rev()
2020-04-26 18:55:13 +00:00
.filter(|v| v.is_complete())
2020-04-24 18:47:11 +00:00
.next()
{
Some(v) => v,
None => return Err(Error::NotFound),
};
2020-07-08 15:34:37 +00:00
let last_v_data = match &last_v.state {
ObjectVersionState::Complete(x) => x,
_ => unreachable!(),
};
let last_v_meta = match last_v_data {
ObjectVersionData::DeleteMarker => return Err(Error::NotFound),
ObjectVersionData::Inline(meta, _) => meta,
ObjectVersionData::FirstBlock(meta, _) => meta,
};
2020-04-24 18:47:11 +00:00
2020-05-04 13:09:23 +00:00
let range = match req.headers().get("range") {
Some(range) => {
let range_str = range
.to_str()
.map_err(|e| Error::BadRequest(format!("Invalid range header: {}", e)))?;
2020-07-08 15:33:24 +00:00
let mut ranges = http_range::HttpRange::parse(range_str, last_v_meta.size)
2020-05-04 13:09:23 +00:00
.map_err(|_e| Error::BadRequest(format!("Invalid range")))?;
if ranges.len() > 1 {
return Err(Error::BadRequest(format!("Multiple ranges not supported")));
} else {
ranges.pop()
}
}
None => None,
};
if let Some(range) = range {
2020-07-08 15:34:37 +00:00
return handle_get_range(
garage,
last_v,
last_v_data,
last_v_meta,
range.start,
range.start + range.length,
)
.await;
2020-05-04 13:09:23 +00:00
}
2020-07-08 15:33:24 +00:00
let resp_builder = object_headers(&last_v, last_v_meta).status(StatusCode::OK);
2020-04-24 18:47:11 +00:00
2020-07-08 15:33:24 +00:00
match &last_v_data {
ObjectVersionData::DeleteMarker => unreachable!(),
ObjectVersionData::Inline(_, bytes) => {
let body: Body = Body::from(bytes.to_vec());
2020-04-24 18:47:11 +00:00
Ok(resp_builder.body(body)?)
}
2020-07-08 15:33:24 +00:00
ObjectVersionData::FirstBlock(_, first_block_hash) => {
2020-04-24 18:47:11 +00:00
let read_first_block = garage.block_manager.rpc_get_block(&first_block_hash);
let get_next_blocks = garage.version_table.get(&last_v.uuid, &EmptyKey);
let (first_block, version) = futures::try_join!(read_first_block, get_next_blocks)?;
let version = match version {
Some(v) => v,
None => return Err(Error::NotFound),
};
let mut blocks = version
.blocks()
.iter()
.map(|vb| (vb.hash, None))
.collect::<Vec<_>>();
blocks[0].1 = Some(first_block);
let body_stream = futures::stream::iter(blocks)
.map(move |(hash, data_opt)| {
let garage = garage.clone();
async move {
if let Some(data) = data_opt {
Ok(Bytes::from(data))
} else {
garage
.block_manager
.rpc_get_block(&hash)
.await
.map(Bytes::from)
}
}
})
.buffered(2);
//let body: Body = Box::new(StreamBody::new(Box::pin(body_stream)));
let body = hyper::body::Body::wrap_stream(body_stream);
2020-04-24 18:47:11 +00:00
Ok(resp_builder.body(body)?)
}
}
}
2020-05-04 13:09:23 +00:00
pub async fn handle_get_range(
garage: Arc<Garage>,
version: &ObjectVersion,
2020-07-08 15:34:37 +00:00
version_data: &ObjectVersionData,
version_meta: &ObjectVersionMeta,
2020-05-04 13:09:23 +00:00
begin: u64,
end: u64,
) -> Result<Response<Body>, Error> {
2020-07-08 15:33:24 +00:00
if end > version_meta.size {
2020-05-04 13:09:23 +00:00
return Err(Error::BadRequest(format!("Range not included in file")));
}
2020-07-08 15:33:24 +00:00
let resp_builder = object_headers(version, version_meta)
2020-05-04 13:09:23 +00:00
.header(
"Content-Range",
2020-07-08 15:33:24 +00:00
format!("bytes {}-{}/{}", begin, end, version_meta.size),
2020-05-04 13:09:23 +00:00
)
.status(StatusCode::PARTIAL_CONTENT);
2020-07-08 15:33:24 +00:00
match &version_data {
ObjectVersionData::DeleteMarker => unreachable!(),
ObjectVersionData::Inline(_meta, bytes) => {
2020-05-04 13:09:23 +00:00
if end as usize <= bytes.len() {
let body: Body = Body::from(bytes[begin as usize..end as usize].to_vec());
2020-05-04 13:09:23 +00:00
Ok(resp_builder.body(body)?)
} else {
Err(Error::Message(format!("Internal error: requested range not present in inline bytes when it should have been")))
}
}
2020-07-08 15:33:24 +00:00
ObjectVersionData::FirstBlock(_meta, _first_block_hash) => {
2020-05-04 13:09:23 +00:00
let version = garage.version_table.get(&version.uuid, &EmptyKey).await?;
let version = match version {
Some(v) => v,
None => return Err(Error::NotFound),
};
let blocks = version
.blocks()
.iter()
.cloned()
.filter(|block| block.offset + block.size > begin && block.offset < end)
.collect::<Vec<_>>();
let body_stream = futures::stream::iter(blocks)
.map(move |block| {
let garage = garage.clone();
async move {
let data = garage.block_manager.rpc_get_block(&block.hash).await?;
let start_in_block = if block.offset > begin {
0
} else {
begin - block.offset
};
let end_in_block = if block.offset + block.size < end {
block.size
} else {
end - block.offset
};
Result::<Bytes, Error>::Ok(Bytes::from(
2020-05-04 13:09:23 +00:00
data[start_in_block as usize..end_in_block as usize].to_vec(),
))
}
})
.buffered(2);
//let body: Body = Box::new(StreamBody::new(Box::pin(body_stream)));
let body = hyper::body::Body::wrap_stream(body_stream);
2020-05-04 13:09:23 +00:00
Ok(resp_builder.body(body)?)
}
}
}