Skip to main content

file_storage/system/r2/
r2_path.rs

1use crate::StoragePath;
2use aws_config::{BehaviorVersion, Region};
3use aws_sdk_s3::{Client, Config};
4use dashmap::DashMap;
5use std::sync::LazyLock;
6use tokio::runtime::{Builder, Runtime};
7
8/// The global Cloudflare R2 `Client` map. `(account_id -> client)`.
9static R2_CLIENTS: LazyLock<DashMap<String, Client>> = LazyLock::new(DashMap::new);
10
11/// The runtime.
12pub(in crate::system::r2) static RUNTIME: LazyLock<Runtime> =
13    LazyLock::new(|| Builder::new_multi_thread().enable_all().build().expect("failed to build tokio runtime"));
14
15/// A Cloudflare R2 path.
16#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
17pub struct R2Path<'a> {
18    pub(crate) path: &'a StoragePath,
19    pub(crate) account_id: &'a str,
20    pub(crate) bucket: &'a str,
21    pub(crate) key: &'a str,
22}
23
24impl<'a> R2Path<'a> {
25    //! Constants
26
27    /// The `https://` path prefix. (all paths must use `https`)
28    pub const HTTPS_PREFIX: &'static str = "https://";
29
30    /// The Cloudflare R2 prefix.
31    pub const R2_PREFIX: &'static str = ".r2.cloudflarestorage.com/";
32}
33
34impl<'a> R2Path<'a> {
35    //! Parse
36
37    /// Parses the parts.
38    ///
39    /// Returns `Some(account_id, bucket, key)`.
40    /// Returns `None` if the `path` is not a Cloudflare R2 path.
41    fn parse_parts(path: &str) -> Option<(&str, &str, &str)> {
42        let s: &str = path;
43        if let Some(s) = s.strip_prefix(Self::HTTPS_PREFIX) {
44            if let Some(dot) = s.as_bytes().iter().position(|c| *c == b'.') {
45                let (account_id, s) = s.split_at(dot);
46                if let Some(s) = s.strip_prefix(Self::R2_PREFIX) {
47                    if let Some(slash) = s.as_bytes().iter().position(|c| *c == b'/') {
48                        let bucket: &str = &s[..slash];
49                        let key: &str = &s[(slash + 1)..];
50                        return Some((account_id, bucket, key));
51                    }
52                }
53            }
54        }
55        None
56    }
57
58    /// Gets the base length of the Cloudflare R2 `path`.
59    ///
60    /// Returns `Some(base_len)`.
61    /// Returns `None` if the Cloudflare R2 path is invalid.
62    pub fn base_len(path: &str) -> Option<usize> {
63        if let Some((account_id, bucket, _key)) = Self::parse_parts(path) {
64            Some(
65                Self::HTTPS_PREFIX.len()
66                    + account_id.len()
67                    + Self::R2_PREFIX.len()
68                    + bucket.len()
69                    + 1,
70            )
71        } else {
72            None
73        }
74    }
75
76    /// Parses a Cloudflare R2 path from the `path`.
77    pub fn new(path: &'a StoragePath) -> Option<Self> {
78        if let Some((account_id, bucket, key)) = Self::parse_parts(path.path()) {
79            Some(Self {
80                path,
81                account_id,
82                bucket,
83                key,
84            })
85        } else {
86            None
87        }
88    }
89}
90
91impl<'a> R2Path<'a> {
92    //! Path
93
94    /// Gets the full path with the given object `key`.
95    pub fn path_with_object_key(self, key: &str) -> String {
96        format!(
97            "{}{}{}{}/{}",
98            Self::HTTPS_PREFIX,
99            self.account_id,
100            Self::R2_PREFIX,
101            self.bucket,
102            key
103        )
104    }
105}
106
107impl<'a> R2Path<'a> {
108    //! Client
109
110    /// Gets the client for the `account_id`.
111    pub(crate) async fn get_client(account_id: &str) -> Client {
112        if let Some(client) = R2_CLIENTS.get(account_id) {
113            return client.value().clone();
114        }
115        let client: Client = Self::create_client(account_id).await;
116        R2_CLIENTS
117            .entry(account_id.to_string())
118            .or_insert(client)
119            .clone()
120    }
121
122    /// Creates a client for the `account_id`.
123    async fn create_client(account_id: &str) -> Client {
124        let endpoint: String = format!("https://{}.r2.cloudflarestorage.com", account_id);
125
126        let config: Config = aws_sdk_s3::config::Builder::from(
127            &aws_config::load_defaults(BehaviorVersion::latest()).await,
128        )
129        .endpoint_url(endpoint)
130        .region(Region::new("auto"))
131        .build();
132
133        Client::from_conf(config)
134    }
135}