Line data Source code
1 : use std::fmt::Debug;
2 : use std::num::NonZeroUsize;
3 : use std::str::FromStr;
4 : use std::time::Duration;
5 :
6 : use aws_sdk_s3::types::StorageClass;
7 : use camino::Utf8PathBuf;
8 : use serde::{Deserialize, Serialize};
9 :
10 : use crate::{
11 : DEFAULT_MAX_KEYS_PER_LIST_RESPONSE, DEFAULT_REMOTE_STORAGE_AZURE_CONCURRENCY_LIMIT,
12 : DEFAULT_REMOTE_STORAGE_LOCALFS_CONCURRENCY_LIMIT, DEFAULT_REMOTE_STORAGE_S3_CONCURRENCY_LIMIT,
13 : };
14 :
15 : /// External backup storage configuration, enough for creating a client for that storage.
16 : #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
17 : pub struct RemoteStorageConfig {
18 : /// The storage connection configuration.
19 : #[serde(flatten)]
20 : pub storage: RemoteStorageKind,
21 : /// A common timeout enforced for all requests after concurrency limiter permit has been
22 : /// acquired.
23 : #[serde(
24 : with = "humantime_serde",
25 : default = "default_timeout",
26 : skip_serializing_if = "is_default_timeout"
27 : )]
28 : pub timeout: Duration,
29 : /// Alternative timeout used for metadata objects which are expected to be small
30 : #[serde(
31 : with = "humantime_serde",
32 : default = "default_small_timeout",
33 : skip_serializing_if = "is_default_small_timeout"
34 : )]
35 : pub small_timeout: Duration,
36 : }
37 :
38 : impl RemoteStorageKind {
39 0 : pub fn bucket_name(&self) -> Option<&str> {
40 0 : match self {
41 0 : RemoteStorageKind::LocalFs { .. } => None,
42 0 : RemoteStorageKind::AwsS3(config) => Some(&config.bucket_name),
43 0 : RemoteStorageKind::AzureContainer(config) => Some(&config.container_name),
44 : }
45 0 : }
46 : }
47 :
48 : impl RemoteStorageConfig {
49 : /// Helper to fetch the configured concurrency limit.
50 0 : pub fn concurrency_limit(&self) -> usize {
51 0 : match &self.storage {
52 0 : RemoteStorageKind::LocalFs { .. } => DEFAULT_REMOTE_STORAGE_LOCALFS_CONCURRENCY_LIMIT,
53 0 : RemoteStorageKind::AwsS3(c) => c.concurrency_limit.into(),
54 0 : RemoteStorageKind::AzureContainer(c) => c.concurrency_limit.into(),
55 : }
56 0 : }
57 : }
58 :
59 1 : fn default_timeout() -> Duration {
60 1 : RemoteStorageConfig::DEFAULT_TIMEOUT
61 1 : }
62 :
63 10 : fn default_small_timeout() -> Duration {
64 10 : RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT
65 10 : }
66 :
67 0 : fn is_default_timeout(d: &Duration) -> bool {
68 0 : *d == RemoteStorageConfig::DEFAULT_TIMEOUT
69 0 : }
70 :
71 0 : fn is_default_small_timeout(d: &Duration) -> bool {
72 0 : *d == RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT
73 0 : }
74 :
75 : /// A kind of a remote storage to connect to, with its connection configuration.
76 0 : #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
77 : #[serde(untagged)]
78 : pub enum RemoteStorageKind {
79 : /// Storage based on local file system.
80 : /// Specify a root folder to place all stored files into.
81 : LocalFs { local_path: Utf8PathBuf },
82 : /// AWS S3 based storage, storing all files in the S3 bucket
83 : /// specified by the config
84 : AwsS3(S3Config),
85 : /// Azure Blob based storage, storing all files in the container
86 : /// specified by the config
87 : AzureContainer(AzureConfig),
88 : }
89 :
90 0 : #[derive(Deserialize)]
91 : #[serde(tag = "type")]
92 : /// Version of RemoteStorageKind which deserializes with type: LocalFs | AwsS3 | AzureContainer
93 : /// Needed for endpoint storage service
94 : pub enum TypedRemoteStorageKind {
95 : LocalFs { local_path: Utf8PathBuf },
96 : AwsS3(S3Config),
97 : AzureContainer(AzureConfig),
98 : }
99 :
100 : impl From<TypedRemoteStorageKind> for RemoteStorageKind {
101 0 : fn from(value: TypedRemoteStorageKind) -> Self {
102 0 : match value {
103 0 : TypedRemoteStorageKind::LocalFs { local_path } => {
104 0 : RemoteStorageKind::LocalFs { local_path }
105 : }
106 0 : TypedRemoteStorageKind::AwsS3(v) => RemoteStorageKind::AwsS3(v),
107 0 : TypedRemoteStorageKind::AzureContainer(v) => RemoteStorageKind::AzureContainer(v),
108 : }
109 0 : }
110 : }
111 :
112 : /// AWS S3 bucket coordinates and access credentials to manage the bucket contents (read and write).
113 : #[derive(Clone, PartialEq, Eq, Deserialize, Serialize)]
114 : pub struct S3Config {
115 : /// Name of the bucket to connect to.
116 : pub bucket_name: String,
117 : /// The region where the bucket is located at.
118 : pub bucket_region: String,
119 : /// A "subfolder" in the bucket, to use the same bucket separately by multiple remote storage users at once.
120 : pub prefix_in_bucket: Option<String>,
121 : /// A base URL to send S3 requests to.
122 : /// By default, the endpoint is derived from a region name, assuming it's
123 : /// an AWS S3 region name, erroring on wrong region name.
124 : /// Endpoint provides a way to support other S3 flavors and their regions.
125 : ///
126 : /// Example: `http://127.0.0.1:5000`
127 : pub endpoint: Option<String>,
128 : /// AWS S3 has various limits on its API calls, we need not to exceed those.
129 : /// See [`DEFAULT_REMOTE_STORAGE_S3_CONCURRENCY_LIMIT`] for more details.
130 : #[serde(default = "default_remote_storage_s3_concurrency_limit")]
131 : pub concurrency_limit: NonZeroUsize,
132 : #[serde(default = "default_max_keys_per_list_response")]
133 : pub max_keys_per_list_response: Option<i32>,
134 : #[serde(
135 : deserialize_with = "deserialize_storage_class",
136 : serialize_with = "serialize_storage_class",
137 : default
138 : )]
139 : pub upload_storage_class: Option<StorageClass>,
140 : }
141 :
142 7 : fn default_remote_storage_s3_concurrency_limit() -> NonZeroUsize {
143 : DEFAULT_REMOTE_STORAGE_S3_CONCURRENCY_LIMIT
144 7 : .try_into()
145 7 : .unwrap()
146 7 : }
147 :
148 7 : fn default_max_keys_per_list_response() -> Option<i32> {
149 7 : DEFAULT_MAX_KEYS_PER_LIST_RESPONSE
150 7 : }
151 :
152 0 : fn default_azure_conn_pool_size() -> usize {
153 : // By default, the Azure SDK does no connection pooling, due to historic reports of hard-to-reproduce issues
154 : // (https://github.com/hyperium/hyper/issues/2312)
155 : //
156 : // However, using connection pooling is important to avoid exhausting client ports when
157 : // doing huge numbers of requests (https://github.com/neondatabase/cloud/issues/20971)
158 : //
159 : // We therefore enable a modest pool size by default: this may be configured to zero if
160 : // issues like the alleged upstream hyper issue appear.
161 0 : 8
162 0 : }
163 :
164 : impl Debug for S3Config {
165 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166 0 : f.debug_struct("S3Config")
167 0 : .field("bucket_name", &self.bucket_name)
168 0 : .field("bucket_region", &self.bucket_region)
169 0 : .field("prefix_in_bucket", &self.prefix_in_bucket)
170 0 : .field("concurrency_limit", &self.concurrency_limit)
171 0 : .field(
172 0 : "max_keys_per_list_response",
173 0 : &self.max_keys_per_list_response,
174 0 : )
175 0 : .finish()
176 0 : }
177 : }
178 :
179 : /// Azure bucket coordinates and access credentials to manage the bucket contents (read and write).
180 0 : #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
181 : pub struct AzureConfig {
182 : /// Name of the container to connect to.
183 : pub container_name: String,
184 : /// Name of the storage account the container is inside of
185 : pub storage_account: Option<String>,
186 : /// The region where the bucket is located at.
187 : pub container_region: String,
188 : /// A "subfolder" in the container, to use the same container separately by multiple remote storage users at once.
189 : pub prefix_in_container: Option<String>,
190 : /// Azure has various limits on its API calls, we need not to exceed those.
191 : /// See [`DEFAULT_REMOTE_STORAGE_AZURE_CONCURRENCY_LIMIT`] for more details.
192 : #[serde(default = "default_remote_storage_azure_concurrency_limit")]
193 : pub concurrency_limit: NonZeroUsize,
194 : #[serde(default = "default_max_keys_per_list_response")]
195 : pub max_keys_per_list_response: Option<i32>,
196 : #[serde(default = "default_azure_conn_pool_size")]
197 : pub conn_pool_size: usize,
198 : }
199 :
200 6 : fn default_remote_storage_azure_concurrency_limit() -> NonZeroUsize {
201 6 : NonZeroUsize::new(DEFAULT_REMOTE_STORAGE_AZURE_CONCURRENCY_LIMIT).unwrap()
202 6 : }
203 :
204 : impl Debug for AzureConfig {
205 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206 0 : f.debug_struct("AzureConfig")
207 0 : .field("bucket_name", &self.container_name)
208 0 : .field("storage_account", &self.storage_account)
209 0 : .field("bucket_region", &self.container_region)
210 0 : .field("prefix_in_container", &self.prefix_in_container)
211 0 : .field("concurrency_limit", &self.concurrency_limit)
212 0 : .field(
213 0 : "max_keys_per_list_response",
214 0 : &self.max_keys_per_list_response,
215 0 : )
216 0 : .finish()
217 0 : }
218 : }
219 :
220 15 : fn deserialize_storage_class<'de, D: serde::Deserializer<'de>>(
221 15 : deserializer: D,
222 15 : ) -> Result<Option<StorageClass>, D::Error> {
223 15 : Option::<String>::deserialize(deserializer).and_then(|s| {
224 15 : if let Some(s) = s {
225 : use serde::de::Error;
226 12 : let storage_class = StorageClass::from_str(&s).expect("infallible");
227 : #[allow(deprecated)]
228 12 : if matches!(storage_class, StorageClass::Unknown(_)) {
229 0 : return Err(D::Error::custom(format!(
230 0 : "Specified storage class unknown to SDK: '{s}'. Allowed values: {:?}",
231 0 : StorageClass::values()
232 0 : )));
233 12 : }
234 12 : Ok(Some(storage_class))
235 : } else {
236 3 : Ok(None)
237 : }
238 15 : })
239 15 : }
240 :
241 9 : fn serialize_storage_class<S: serde::Serializer>(
242 9 : val: &Option<StorageClass>,
243 9 : serializer: S,
244 9 : ) -> Result<S::Ok, S::Error> {
245 9 : let val = val.as_ref().map(StorageClass::as_str);
246 9 : Option::<&str>::serialize(&val, serializer)
247 9 : }
248 :
249 : impl RemoteStorageConfig {
250 : pub const DEFAULT_TIMEOUT: Duration = std::time::Duration::from_secs(120);
251 : pub const DEFAULT_SMALL_TIMEOUT: Duration = std::time::Duration::from_secs(30);
252 :
253 10 : pub fn from_toml(toml: &toml_edit::Item) -> anyhow::Result<RemoteStorageConfig> {
254 10 : Ok(utils::toml_edit_ext::deserialize_item(toml)?)
255 10 : }
256 :
257 9 : pub fn from_toml_str(input: &str) -> anyhow::Result<RemoteStorageConfig> {
258 9 : let toml_document = toml_edit::DocumentMut::from_str(input)?;
259 9 : if let Some(item) = toml_document.get("remote_storage") {
260 0 : return Self::from_toml(item);
261 9 : }
262 9 : Self::from_toml(toml_document.as_item())
263 9 : }
264 : }
265 :
266 : #[cfg(test)]
267 : mod tests {
268 : use super::*;
269 :
270 9 : fn parse(input: &str) -> anyhow::Result<RemoteStorageConfig> {
271 9 : RemoteStorageConfig::from_toml_str(input)
272 9 : }
273 :
274 : #[test]
275 3 : fn parse_localfs_config_with_timeout() {
276 3 : let input = "local_path = '.'
277 3 : timeout = '5s'";
278 :
279 3 : let config = parse(input).unwrap();
280 :
281 3 : assert_eq!(
282 : config,
283 3 : RemoteStorageConfig {
284 3 : storage: RemoteStorageKind::LocalFs {
285 3 : local_path: Utf8PathBuf::from(".")
286 3 : },
287 3 : timeout: Duration::from_secs(5),
288 3 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT
289 3 : }
290 : );
291 3 : }
292 :
293 : #[test]
294 3 : fn test_s3_parsing() {
295 3 : let toml = "\
296 3 : bucket_name = 'foo-bar'
297 3 : bucket_region = 'eu-central-1'
298 3 : upload_storage_class = 'INTELLIGENT_TIERING'
299 3 : timeout = '7s'
300 3 : ";
301 :
302 3 : let config = parse(toml).unwrap();
303 :
304 3 : assert_eq!(
305 : config,
306 3 : RemoteStorageConfig {
307 3 : storage: RemoteStorageKind::AwsS3(S3Config {
308 3 : bucket_name: "foo-bar".into(),
309 3 : bucket_region: "eu-central-1".into(),
310 3 : prefix_in_bucket: None,
311 3 : endpoint: None,
312 3 : concurrency_limit: default_remote_storage_s3_concurrency_limit(),
313 3 : max_keys_per_list_response: DEFAULT_MAX_KEYS_PER_LIST_RESPONSE,
314 3 : upload_storage_class: Some(StorageClass::IntelligentTiering),
315 3 : }),
316 3 : timeout: Duration::from_secs(7),
317 3 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT
318 3 : }
319 : );
320 3 : }
321 :
322 : #[test]
323 3 : fn test_storage_class_serde_roundtrip() {
324 3 : let classes = [
325 3 : None,
326 3 : Some(StorageClass::Standard),
327 3 : Some(StorageClass::IntelligentTiering),
328 3 : ];
329 12 : for class in classes {
330 : #[derive(Serialize, Deserialize)]
331 : struct Wrapper {
332 : #[serde(
333 : deserialize_with = "deserialize_storage_class",
334 : serialize_with = "serialize_storage_class"
335 : )]
336 : class: Option<StorageClass>,
337 : }
338 9 : let wrapped = Wrapper {
339 9 : class: class.clone(),
340 9 : };
341 9 : let serialized = serde_json::to_string(&wrapped).unwrap();
342 9 : let deserialized: Wrapper = serde_json::from_str(&serialized).unwrap();
343 9 : assert_eq!(class, deserialized.class);
344 : }
345 3 : }
346 :
347 : #[test]
348 3 : fn test_azure_parsing() {
349 3 : let toml = "\
350 3 : container_name = 'foo-bar'
351 3 : container_region = 'westeurope'
352 3 : upload_storage_class = 'INTELLIGENT_TIERING'
353 3 : timeout = '7s'
354 3 : conn_pool_size = 8
355 3 : ";
356 :
357 3 : let config = parse(toml).unwrap();
358 :
359 3 : assert_eq!(
360 : config,
361 3 : RemoteStorageConfig {
362 3 : storage: RemoteStorageKind::AzureContainer(AzureConfig {
363 3 : container_name: "foo-bar".into(),
364 3 : storage_account: None,
365 3 : container_region: "westeurope".into(),
366 3 : prefix_in_container: None,
367 3 : concurrency_limit: default_remote_storage_azure_concurrency_limit(),
368 3 : max_keys_per_list_response: DEFAULT_MAX_KEYS_PER_LIST_RESPONSE,
369 3 : conn_pool_size: 8,
370 3 : }),
371 3 : timeout: Duration::from_secs(7),
372 3 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT
373 3 : }
374 : );
375 3 : }
376 : }
|