Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(presign): support presign head method for s3 and oss #1049

Merged
merged 6 commits into from
Dec 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/object/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1475,6 +1475,36 @@ impl Object {
},
}
}
/// Presign an operation for stat(head).
///
/// # Example
///
/// ```no_run
/// use anyhow::Result;
/// use futures::io;
/// use opendal::services::memory;
/// use opendal::Operator;
/// use time::Duration;
/// # use opendal::Scheme;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
/// # let op = Operator::from_env(Scheme::Memory)?;
/// let signed_req = op.object("test").presign_stat(Duration::hours(1))?;
/// let req = http::Request::builder()
/// .method(signed_req.method())
/// .uri(signed_req.uri())
/// .body(())?;
///
/// # Ok(())
/// # }
/// ```
pub fn presign_stat(&self, expire: Duration) -> Result<PresignedRequest> {
let op = OpPresign::new(OpStat::new(), expire);

let rp = self.acc.presign(self.path(), op)?;
Ok(rp.into_presigned_request())
}

/// Presign an operation for read.
///
Expand Down
8 changes: 8 additions & 0 deletions src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ impl OpPresign {
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PresignOperation {
/// Presign a stat(head) operation.
Stat(OpStat),
/// Presign a read operation.
Read(OpRead),
/// Presign a write operation.
Expand All @@ -194,6 +196,12 @@ pub enum PresignOperation {
WriteMultipart(OpWriteMultipart),
}

impl From<OpStat> for PresignOperation {
fn from(op: OpStat) -> Self {
Self::Stat(op)
}
}

impl From<OpRead> for PresignOperation {
fn from(v: OpRead) -> Self {
Self::Read(v)
Expand Down
1 change: 1 addition & 0 deletions src/services/oss/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ impl Accessor for Backend {
fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
// We will not send this request out, just for signing.
let mut req = match args.operation() {
PresignOperation::Stat(_) => self.oss_head_object_request(path)?,
PresignOperation::Read(v) => self.oss_get_object_request(path, v.range())?,
PresignOperation::Write(_) => {
self.oss_put_object_request(path, None, None, AsyncBody::Empty)?
Expand Down
17 changes: 17 additions & 0 deletions src/services/s3/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,7 @@ impl Accessor for Backend {
fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
// We will not send this request out, just for signing.
let mut req = match args.operation() {
PresignOperation::Stat(_) => self.s3_head_object_request(path)?,
PresignOperation::Read(v) => self.s3_get_object_request(path, v.range())?,
PresignOperation::Write(_) => {
self.s3_put_object_request(path, None, None, AsyncBody::Empty)?
Expand Down Expand Up @@ -1014,6 +1015,22 @@ impl Accessor for Backend {
}

impl Backend {
fn s3_head_object_request(&self, path: &str) -> Result<Request<AsyncBody>> {
let p = build_abs_path(&self.root, path);

let url = format!("{}/{}", self.endpoint, percent_encode_path(&p));

let mut req = Request::head(&url);

req = self.insert_sse_headers(req, false);

let req = req
.body(AsyncBody::Empty)
.map_err(new_request_build_error)?;

Ok(req)
}

fn s3_get_object_request(&self, path: &str, range: BytesRange) -> Result<Request<AsyncBody>> {
let p = build_abs_path(&self.root, path);

Expand Down
39 changes: 39 additions & 0 deletions tests/behavior/presign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ macro_rules! behavior_presign_tests {

test_presign_write,
test_presign_read,
test_presign_stat,
);
)*
};
Expand Down Expand Up @@ -113,6 +114,44 @@ pub async fn test_presign_write(op: Operator) -> Result<()> {
Ok(())
}

pub async fn test_presign_stat(op: Operator) -> Result<()> {
let path = uuid::Uuid::new_v4().to_string();
debug!("Generate a random file: {}", &path);
let (content, size) = gen_bytes();
op.object(&path)
.write(content.clone())
.await
.expect("write must succeed");
let signed_req = op.object(&path).presign_stat(Duration::hours(1))?;
debug!("Generated request: {signed_req:?}");
let client = reqwest::Client::new();
let mut req = client.request(
signed_req.method().clone(),
Url::from_str(&signed_req.uri().to_string()).expect("must be valid url"),
);
for (k, v) in signed_req.header() {
req = req.header(k, v);
}
let resp = req.send().await.expect("send request must succeed");
assert_eq!(resp.status(), http::StatusCode::OK, "status ok",);
// response headers default content_length method cannot get the correct value
let content_length = resp
.headers()
.get(header::CONTENT_LENGTH)
.expect("content length must exist")
.to_str()
.expect("content length must be valid str")
.parse::<u64>()
.expect("content length must be valid u64");
assert_eq!(content_length, size as u64);

op.object(&path)
.delete()
.await
.expect("delete must succeed");
Ok(())
}

// Presign read should read content successfully.
pub async fn test_presign_read(op: Operator) -> Result<()> {
let path = uuid::Uuid::new_v4().to_string();
Expand Down