Skip to main content

objectstore_client/
head.rs

1use objectstore_types::metadata::Metadata;
2use reqwest::StatusCode;
3
4use crate::instrument::{OperationSpan, record_field};
5use crate::response::ResponseExt as _;
6use crate::{ObjectKey, Session};
7
8/// The result from a successful [`head()`](Session::head) call.
9///
10/// Returns `Some(metadata)` if the object exists, `None` otherwise.
11pub type HeadResponse = Option<Metadata>;
12
13impl Session {
14    /// Checks whether an object exists and retrieves its metadata.
15    ///
16    /// If the object exists and has a TTI expiration policy, this is considered an access, and
17    /// therefore bumps its expiration.
18    pub fn head(&self, key: &str) -> HeadBuilder {
19        HeadBuilder {
20            session: self.clone(),
21            key: key.to_owned(),
22        }
23    }
24}
25
26/// A [`head`](Session::head) request builder.
27#[derive(Debug)]
28pub struct HeadBuilder {
29    pub(crate) session: Session,
30    pub(crate) key: ObjectKey,
31}
32
33impl HeadBuilder {
34    /// Sends the head request.
35    pub async fn send(self) -> crate::Result<HeadResponse> {
36        let span = OperationSpan::storage("objectstore.head", &self.session, Some(&self.key));
37        span.instrument(self.execute()).await
38    }
39
40    async fn execute(self) -> crate::Result<HeadResponse> {
41        let response = self
42            .session
43            .request(reqwest::Method::HEAD, &self.key)?
44            .send()
45            .await?;
46        if response.status() == StatusCode::NOT_FOUND {
47            record_field("objectstore.found", false);
48            response.drain_body().await;
49            return Ok(None);
50        }
51        let response = response.error_for_status_and_drain().await?;
52        record_field("objectstore.found", true);
53        let metadata = Metadata::from_headers(response.headers(), "");
54        response.drain_body().await;
55        Ok(Some(metadata?))
56    }
57}