| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | | mod aws; |
| 16 | | mod azure; |
| 17 | | mod gcp; |
| 18 | | mod http; |
| 19 | | mod ini; |
| 20 | |
|
| 21 | | use futures::TryStreamExt; |
| 22 | | use object_store::path::Path as ObjectPath; |
| 23 | | use object_store::{ |
| 24 | | GetOptions, ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload, UpdateVersion, |
| 25 | | }; |
| 26 | | use oxy_core::strata::{check_key, Entry, Error, Result, Store, Version}; |
| 27 | | use std::collections::BTreeMap; |
| 28 | | use std::future::Future; |
| 29 | | use std::ops::Range; |
| 30 | | use std::sync::{Arc, Mutex}; |
| 31 | |
|
| 32 | |
|
| 33 | |
|
| 34 | 148× | pub fn register() { |
| 35 | | |
| 36 | | |
| 37 | 148× | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 38 | 148× | oxy_core::protocol::register_store_opener(open_url); |
| 39 | 148× | } |
| 40 | |
|
| 41 | 17× | fn open_url( |
| 42 | 17× | url: &str, |
| 43 | 17× | _options: &oxy_core::protocol::RemoteOptions, |
| 44 | 17× | ) -> Option<Result<Box<dyn Store>>> { |
| 45 | 17× | let scheme = url.split_once("://")?.0; |
| 46 | 0× | if !matches!(scheme, "s3" | "gs" | "az") { |
| 47 | 0× | return None; |
| 48 | 0× | } |
| 49 | 0× | let lookup = *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner()); |
| 50 | 0× | let given = lookup.and_then(|f| f(url)); |
| 51 | 0× | Some(shared(url, given).map(|s| Box::new(Shared(s)) as Box<dyn Store>)) |
| 52 | 17× | } |
| 53 | |
|
| 54 | |
|
| 55 | |
|
| 56 | |
|
| 57 | |
|
| 58 | | type OpenStores = std::collections::HashMap<(String, Option<Credentials>), Arc<CloudStore>>; |
| 59 | |
|
| 60 | 3× | fn shared(url: &str, given: Option<Credentials>) -> Result<Arc<CloudStore>> { |
| 61 | | static OPEN: Mutex<Option<OpenStores>> = Mutex::new(None); |
| 62 | 3× | let key = (url.to_string(), given); |
| 63 | 3× | let mut open = OPEN.lock().unwrap_or_else(|p| p.into_inner()); |
| 64 | 3× | let map = open.get_or_insert_with(Default::default); |
| 65 | 3× | if let Some(s) = map.get(&key) { |
| 66 | 1× | return Ok(s.clone()); |
| 67 | 2× | } |
| 68 | 2× | let store = Arc::new(CloudStore::open_with(url, key.1.as_ref())?); |
| 69 | 2× | map.insert(key, store.clone()); |
| 70 | 2× | Ok(store) |
| 71 | 3× | } |
| 72 | |
|
| 73 | |
|
| 74 | | struct Shared(Arc<CloudStore>); |
| 75 | |
|
| 76 | | impl Store for Shared { |
| 77 | 0× | fn describe(&self) -> String { |
| 78 | 0× | self.0.describe() |
| 79 | 0× | } |
| 80 | 0× | fn has(&self, key: &str) -> Result<bool> { |
| 81 | 0× | self.0.has(key) |
| 82 | 0× | } |
| 83 | 0× | fn get(&self, key: &str) -> Result<Vec<u8>> { |
| 84 | 0× | self.0.get(key) |
| 85 | 0× | } |
| 86 | 0× | fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> { |
| 87 | 0× | self.0.get_range(key, range) |
| 88 | 0× | } |
| 89 | 0× | fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> { |
| 90 | 0× | self.0.put_new(key, bytes) |
| 91 | 0× | } |
| 92 | 0× | fn list(&self, prefix: &str) -> Result<Vec<Entry>> { |
| 93 | 0× | self.0.list(prefix) |
| 94 | 0× | } |
| 95 | 0× | fn delete(&self, key: &str) -> Result<()> { |
| 96 | 0× | self.0.delete(key) |
| 97 | 0× | } |
| 98 | 0× | fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> { |
| 99 | 0× | self.0.read_ref(key) |
| 100 | 0× | } |
| 101 | 0× | fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> { |
| 102 | 0× | self.0.write_ref(key, bytes, expected) |
| 103 | 0× | } |
| 104 | | } |
| 105 | |
|
| 106 | | static OPENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 107 | | static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 108 | | static MICROS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 109 | |
|
| 110 | |
|
| 111 | |
|
| 112 | |
|
| 113 | | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 114 | | pub struct Stats { |
| 115 | | pub opens: u64, |
| 116 | | pub calls: u64, |
| 117 | | pub millis: u64, |
| 118 | | } |
| 119 | |
|
| 120 | 2× | pub fn stats() -> Stats { |
| 121 | | use std::sync::atomic::Ordering::Relaxed; |
| 122 | 2× | Stats { |
| 123 | 2× | opens: OPENS.load(Relaxed), |
| 124 | 2× | calls: CALLS.load(Relaxed), |
| 125 | 2× | millis: MICROS.load(Relaxed) / 1000, |
| 126 | 2× | } |
| 127 | 2× | } |
| 128 | |
|
| 129 | |
|
| 130 | |
|
| 131 | |
|
| 132 | |
|
| 133 | | #[derive(Clone, PartialEq, Eq, Hash)] |
| 134 | | pub enum Credentials { |
| 135 | | |
| 136 | | Aws { |
| 137 | | access_key_id: String, |
| 138 | | secret_access_key: String, |
| 139 | | session_token: Option<String>, |
| 140 | | }, |
| 141 | | |
| 142 | | Gcp { service_account_key: String }, |
| 143 | | |
| 144 | | Azure { |
| 145 | | tenant_id: String, |
| 146 | | client_id: String, |
| 147 | | client_secret: String, |
| 148 | | }, |
| 149 | | } |
| 150 | |
|
| 151 | | impl std::fmt::Debug for Credentials { |
| 152 | | |
| 153 | 3× | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 154 | 3× | match self { |
| 155 | 1× | Credentials::Aws { access_key_id, .. } => { |
| 156 | 1× | write!(f, "Aws({access_key_id}, secret hidden)") |
| 157 | | } |
| 158 | 1× | Credentials::Gcp { .. } => write!(f, "Gcp(service account key hidden)"), |
| 159 | 1× | Credentials::Azure { client_id, .. } => write!(f, "Azure({client_id}, secret hidden)"), |
| 160 | | } |
| 161 | 3× | } |
| 162 | | } |
| 163 | |
|
| 164 | | impl Credentials { |
| 165 | | |
| 166 | 4× | pub fn scheme(&self) -> &'static str { |
| 167 | 4× | match self { |
| 168 | 4× | Credentials::Aws { .. } => "s3", |
| 169 | 0× | Credentials::Gcp { .. } => "gs", |
| 170 | 0× | Credentials::Azure { .. } => "az", |
| 171 | | } |
| 172 | 4× | } |
| 173 | |
|
| 174 | | |
| 175 | 3× | pub fn to_json(&self) -> String { |
| 176 | 3× | let v = match self { |
| 177 | | Credentials::Aws { |
| 178 | 1× | access_key_id, |
| 179 | 1× | secret_access_key, |
| 180 | 1× | session_token, |
| 181 | 1× | } => serde_json::json!({ |
| 182 | 1× | "kind": "aws", "access_key_id": access_key_id, "secret_access_key": secret_access_key, |
| 183 | 1× | "session_token": session_token, |
| 184 | | }), |
| 185 | | Credentials::Gcp { |
| 186 | 1× | service_account_key, |
| 187 | | } => { |
| 188 | 1× | serde_json::json!({ "kind": "gcp", "service_account_key": service_account_key }) |
| 189 | | } |
| 190 | | Credentials::Azure { |
| 191 | 1× | tenant_id, |
| 192 | 1× | client_id, |
| 193 | 1× | client_secret, |
| 194 | 1× | } => serde_json::json!({ |
| 195 | 1× | "kind": "azure", "tenant_id": tenant_id, "client_id": client_id, "client_secret": client_secret, |
| 196 | | }), |
| 197 | | }; |
| 198 | 3× | v.to_string() |
| 199 | 3× | } |
| 200 | |
|
| 201 | 7× | pub fn from_json(text: &str) -> Result<Credentials> { |
| 202 | 7× | let v: serde_json::Value = serde_json::from_str(text) |
| 203 | 7× | .map_err(|e| Error::Backend(format!("credentials are not JSON: {e}")))?; |
| 204 | 10× | let field = |k: &str| -> Result<String> { |
| 205 | 10× | v.get(k) |
| 206 | 10× | .and_then(|x| x.as_str()) |
| 207 | 10× | .filter(|x| !x.trim().is_empty()) |
| 208 | 10× | .map(|x| x.trim().to_string()) |
| 209 | 10× | .ok_or_else(|| Error::Backend(format!("credentials need {k}"))) |
| 210 | 10× | }; |
| 211 | 6× | match v.get("kind").and_then(|k| k.as_str()) { |
| 212 | 6× | Some("aws") => Ok(Credentials::Aws { |
| 213 | 2× | access_key_id: field("access_key_id")?, |
| 214 | 2× | secret_access_key: field("secret_access_key")?, |
| 215 | 1× | session_token: field("session_token").ok(), |
| 216 | | }), |
| 217 | 4× | Some("gcp") => { |
| 218 | 2× | let key = field("service_account_key")?; |
| 219 | 2× | let parsed: serde_json::Value = serde_json::from_str(&key).map_err(|_| { |
| 220 | 0× | Error::Backend("the service account key is not the JSON Google issues".into()) |
| 221 | 0× | })?; |
| 222 | 2× | if parsed.get("type").and_then(|t| t.as_str()) != Some("service_account") { |
| 223 | 1× | return Err(Error::Backend( |
| 224 | 1× | "the key is not a service account key (its type is not service_account)" |
| 225 | 1× | .into(), |
| 226 | 1× | )); |
| 227 | 1× | } |
| 228 | 1× | Ok(Credentials::Gcp { |
| 229 | 1× | service_account_key: key, |
| 230 | 1× | }) |
| 231 | | } |
| 232 | 2× | Some("azure") => Ok(Credentials::Azure { |
| 233 | 1× | tenant_id: field("tenant_id")?, |
| 234 | 1× | client_id: field("client_id")?, |
| 235 | 1× | client_secret: field("client_secret")?, |
| 236 | | }), |
| 237 | 1× | _ => Err(Error::Backend( |
| 238 | 1× | "credentials need a kind: aws, gcp or azure".into(), |
| 239 | 1× | )), |
| 240 | | } |
| 241 | 7× | } |
| 242 | | } |
| 243 | |
|
| 244 | |
|
| 245 | | pub type CredentialsLookup = fn(&str) -> Option<Credentials>; |
| 246 | |
|
| 247 | | static CREDENTIALS: Mutex<Option<CredentialsLookup>> = Mutex::new(None); |
| 248 | |
|
| 249 | |
|
| 250 | |
|
| 251 | 0× | pub fn set_credentials_lookup(lookup: CredentialsLookup) { |
| 252 | 0× | *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner()) = Some(lookup); |
| 253 | 0× | } |
| 254 | |
|
| 255 | |
|
| 256 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 257 | | pub struct StoreUrl { |
| 258 | | pub scheme: String, |
| 259 | | |
| 260 | | pub host: String, |
| 261 | | |
| 262 | | |
| 263 | | pub path: String, |
| 264 | | pub params: BTreeMap<String, String>, |
| 265 | | } |
| 266 | |
|
| 267 | | impl StoreUrl { |
| 268 | 9× | pub fn parse(url: &str) -> Result<StoreUrl> { |
| 269 | 9× | let bad = |why: &str| Error::Backend(format!("{url}: {why}")); |
| 270 | 9× | let (scheme, rest) = url.split_once("://").ok_or_else(|| bad("not a URL"))?; |
| 271 | 8× | let (rest, query) = match rest.split_once('?') { |
| 272 | 5× | Some((r, q)) => (r, Some(q)), |
| 273 | 3× | None => (rest, None), |
| 274 | | }; |
| 275 | 8× | let (host, path) = match rest.split_once('/') { |
| 276 | 6× | Some((h, p)) => (h, p.trim_matches('/')), |
| 277 | 2× | None => (rest, ""), |
| 278 | | }; |
| 279 | 8× | if host.is_empty() { |
| 280 | 1× | return Err(bad("names no bucket")); |
| 281 | 7× | } |
| 282 | 7× | let mut params = BTreeMap::new(); |
| 283 | 9× | for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) { |
| 284 | 7× | let (k, v) = pair.split_once('=').unwrap_or((pair, "")); |
| 285 | 7× | params.insert(k.to_string(), percent_decode(v)); |
| 286 | 7× | } |
| 287 | 7× | Ok(StoreUrl { |
| 288 | 7× | scheme: scheme.to_string(), |
| 289 | 7× | host: host.to_string(), |
| 290 | 7× | path: path.to_string(), |
| 291 | 7× | params, |
| 292 | 7× | }) |
| 293 | 9× | } |
| 294 | |
|
| 295 | | |
| 296 | 6× | pub fn plain(&self) -> String { |
| 297 | 6× | if self.path.is_empty() { |
| 298 | 1× | format!("{}://{}", self.scheme, self.host) |
| 299 | | } else { |
| 300 | 5× | format!("{}://{}/{}", self.scheme, self.host, self.path) |
| 301 | | } |
| 302 | 6× | } |
| 303 | |
|
| 304 | 10× | pub fn param(&self, name: &str) -> Option<&str> { |
| 305 | 10× | self.params.get(name).map(String::as_str) |
| 306 | 10× | } |
| 307 | | } |
| 308 | |
|
| 309 | 7× | fn percent_decode(s: &str) -> String { |
| 310 | 7× | let bytes = s.as_bytes(); |
| 311 | 7× | let mut out = Vec::with_capacity(bytes.len()); |
| 312 | 7× | let mut i = 0; |
| 313 | 87× | while i < bytes.len() { |
| 314 | 80× | if bytes[i] == b'%' && i + 2 < bytes.len() { |
| 315 | 4× | if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) { |
| 316 | 4× | out.push(v); |
| 317 | 4× | i += 3; |
| 318 | 4× | continue; |
| 319 | 0× | } |
| 320 | 76× | } |
| 321 | 76× | out.push(bytes[i]); |
| 322 | 76× | i += 1; |
| 323 | | } |
| 324 | 7× | String::from_utf8_lossy(&out).into_owned() |
| 325 | 7× | } |
| 326 | |
|
| 327 | |
|
| 328 | |
|
| 329 | | pub struct CloudStore { |
| 330 | | inner: Arc<dyn ObjectStore>, |
| 331 | | prefix: String, |
| 332 | | name: String, |
| 333 | | hint: &'static str, |
| 334 | | |
| 335 | | |
| 336 | | runtime: Option<tokio::runtime::Runtime>, |
| 337 | | } |
| 338 | |
|
| 339 | | impl Drop for CloudStore { |
| 340 | | |
| 341 | 1× | fn drop(&mut self) { |
| 342 | 1× | if let Some(rt) = self.runtime.take() { |
| 343 | 1× | rt.shutdown_background(); |
| 344 | 1× | } |
| 345 | 1× | } |
| 346 | | } |
| 347 | |
|
| 348 | | impl CloudStore { |
| 349 | | |
| 350 | | |
| 351 | 1× | pub fn open(url: &str) -> Result<CloudStore> { |
| 352 | 1× | Self::open_with(url, None) |
| 353 | 1× | } |
| 354 | |
|
| 355 | | |
| 356 | | |
| 357 | 4× | pub fn open_with(url: &str, given: Option<&Credentials>) -> Result<CloudStore> { |
| 358 | 4× | let parsed = StoreUrl::parse(url)?; |
| 359 | 4× | if let Some(c) = given.filter(|c| c.scheme() != parsed.scheme) { |
| 360 | 1× | return Err(Error::Backend(format!( |
| 361 | 1× | "{}: the credentials given are for {}:// stores", |
| 362 | 1× | parsed.plain(), |
| 363 | 1× | c.scheme() |
| 364 | 1× | ))); |
| 365 | 3× | } |
| 366 | 3× | let aws_keys = match given { |
| 367 | | Some(Credentials::Aws { |
| 368 | 2× | access_key_id, |
| 369 | 2× | secret_access_key, |
| 370 | 2× | session_token, |
| 371 | 2× | }) => Some(( |
| 372 | 2× | access_key_id.as_str(), |
| 373 | 2× | secret_access_key.as_str(), |
| 374 | 2× | session_token.as_deref(), |
| 375 | 2× | )), |
| 376 | 1× | _ => None, |
| 377 | | }; |
| 378 | 3× | let gcp_key = match given { |
| 379 | | Some(Credentials::Gcp { |
| 380 | 0× | service_account_key, |
| 381 | 0× | }) => Some(service_account_key.as_str()), |
| 382 | 3× | _ => None, |
| 383 | | }; |
| 384 | 3× | let principal = match given { |
| 385 | | Some(Credentials::Azure { |
| 386 | 0× | tenant_id, |
| 387 | 0× | client_id, |
| 388 | 0× | client_secret, |
| 389 | 0× | }) => Some(( |
| 390 | 0× | tenant_id.as_str(), |
| 391 | 0× | client_id.as_str(), |
| 392 | 0× | client_secret.as_str(), |
| 393 | 0× | )), |
| 394 | 3× | _ => None, |
| 395 | | }; |
| 396 | 3× | OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 397 | 3× | let runtime = tokio::runtime::Builder::new_multi_thread() |
| 398 | 3× | .worker_threads(2) |
| 399 | 3× | .thread_name("oxy-strata") |
| 400 | 3× | .enable_all() |
| 401 | 3× | .build() |
| 402 | 3× | .map_err(|e| Error::Backend(format!("starting the HTTP runtime: {e}")))?; |
| 403 | 3× | let (inner, prefix, hint): (Arc<dyn ObjectStore>, String, &'static str) = |
| 404 | 3× | match parsed.scheme.as_str() { |
| 405 | 3× | "s3" => ( |
| 406 | 3× | Arc::new(aws::open(&parsed, aws_keys)?), |
| 407 | 3× | parsed.path.clone(), |
| 408 | | aws::HINT, |
| 409 | | ), |
| 410 | 0× | "gs" => ( |
| 411 | 0× | Arc::new(gcp::open(&parsed, gcp_key)?), |
| 412 | 0× | parsed.path.clone(), |
| 413 | | gcp::HINT, |
| 414 | | ), |
| 415 | 0× | "az" => { |
| 416 | 0× | let (store, prefix) = azure::open(&parsed, principal)?; |
| 417 | 0× | (Arc::new(store), prefix, azure::HINT) |
| 418 | | } |
| 419 | 0× | other => { |
| 420 | 0× | return Err(Error::Backend(format!( |
| 421 | 0× | "{url}: {other}:// is not a store oxy knows (s3://, gs://, az://, dir://)" |
| 422 | 0× | ))) |
| 423 | | } |
| 424 | | }; |
| 425 | 3× | Ok(CloudStore { |
| 426 | 3× | inner, |
| 427 | 3× | prefix, |
| 428 | 3× | name: parsed.plain(), |
| 429 | 3× | hint, |
| 430 | 3× | runtime: Some(runtime), |
| 431 | 3× | }) |
| 432 | 4× | } |
| 433 | |
|
| 434 | | |
| 435 | | |
| 436 | | |
| 437 | 1× | fn block<F>(&self, f: F) -> F::Output |
| 438 | 1× | where |
| 439 | 1× | F: Future + Send, |
| 440 | 1× | F::Output: Send, |
| 441 | | { |
| 442 | 1× | let runtime = self |
| 443 | 1× | .runtime |
| 444 | 1× | .as_ref() |
| 445 | 1× | .expect("the runtime lives as long as the store"); |
| 446 | 1× | let started = std::time::Instant::now(); |
| 447 | 1× | let out = if tokio::runtime::Handle::try_current().is_ok() { |
| 448 | 1× | std::thread::scope(|s| { |
| 449 | 1× | s.spawn(|| runtime.block_on(f)) |
| 450 | 1× | .join() |
| 451 | 1× | .unwrap_or_else(|p| std::panic::resume_unwind(p)) |
| 452 | 1× | }) |
| 453 | | } else { |
| 454 | 0× | runtime.block_on(f) |
| 455 | | }; |
| 456 | 1× | CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 457 | 1× | MICROS.fetch_add( |
| 458 | 1× | started.elapsed().as_micros() as u64, |
| 459 | 1× | std::sync::atomic::Ordering::Relaxed, |
| 460 | | ); |
| 461 | 1× | out |
| 462 | 1× | } |
| 463 | |
|
| 464 | 0× | fn path(&self, key: &str) -> Result<ObjectPath> { |
| 465 | 0× | check_key(key)?; |
| 466 | 0× | let full = if self.prefix.is_empty() { |
| 467 | 0× | key.to_string() |
| 468 | | } else { |
| 469 | 0× | format!("{}/{key}", self.prefix) |
| 470 | | }; |
| 471 | 0× | ObjectPath::parse(&full).map_err(|e| Error::Backend(format!("{full}: {e}"))) |
| 472 | 0× | } |
| 473 | |
|
| 474 | | |
| 475 | 0× | fn map(&self, e: object_store::Error, key: &str) -> Error { |
| 476 | | use object_store::Error as E; |
| 477 | 0× | match e { |
| 478 | 0× | E::NotFound { .. } => Error::NotFound(key.to_string()), |
| 479 | 0× | E::AlreadyExists { .. } => Error::Exists(key.to_string()), |
| 480 | 0× | E::Precondition { .. } | E::NotModified { .. } => Error::Conflict(key.to_string()), |
| 481 | 0× | other => { |
| 482 | 0× | let text = other.to_string(); |
| 483 | 0× | let lower = text.to_ascii_lowercase(); |
| 484 | 0× | let advice = if lower.contains("403") |
| 485 | 0× | || lower.contains("accessdenied") |
| 486 | 0× | || lower.contains("forbidden") |
| 487 | 0× | || lower.contains("authorizationpermissionmismatch") |
| 488 | | { |
| 489 | 0× | format!( |
| 490 | | ": access denied; the credentials in use may not do this on {}: {}", |
| 491 | | self.name, self.hint |
| 492 | | ) |
| 493 | 0× | } else if lower.contains("credential") || lower.contains("no valid credentials") { |
| 494 | 0× | format!(": no usable credentials: {}", self.hint) |
| 495 | 0× | } else if lower.contains("nosuchbucket") |
| 496 | 0× | || lower.contains("bucketnotfound") |
| 497 | 0× | || lower.contains("containernotfound") |
| 498 | | { |
| 499 | 0× | format!( |
| 500 | | ": {} does not exist, or the credentials cannot see it", |
| 501 | | self.name |
| 502 | | ) |
| 503 | 0× | } else if lower.contains("dns") |
| 504 | 0× | || lower.contains("connect") |
| 505 | 0× | || lower.contains("timed out") |
| 506 | | { |
| 507 | 0× | ": cannot reach the service; check the network, the endpoint and the region" |
| 508 | 0× | .to_string() |
| 509 | | } else { |
| 510 | 0× | String::new() |
| 511 | | }; |
| 512 | 0× | Error::Backend(format!("{}: {text}{advice}", self.name)) |
| 513 | | } |
| 514 | | } |
| 515 | 0× | } |
| 516 | |
|
| 517 | 2× | fn version_of(e_tag: Option<String>, version: Option<String>) -> Version { |
| 518 | 2× | Version(format!( |
| 519 | 2× | "{}\t{}", |
| 520 | 2× | e_tag.unwrap_or_default(), |
| 521 | 2× | version.unwrap_or_default() |
| 522 | 2× | )) |
| 523 | 2× | } |
| 524 | |
|
| 525 | 2× | fn update_version(v: &Version) -> UpdateVersion { |
| 526 | 2× | let (e_tag, version) = v.0.split_once('\t').unwrap_or((v.0.as_str(), "")); |
| 527 | | UpdateVersion { |
| 528 | 2× | e_tag: (!e_tag.is_empty()).then(|| e_tag.to_string()), |
| 529 | 2× | version: (!version.is_empty()).then(|| version.to_string()), |
| 530 | | } |
| 531 | 2× | } |
| 532 | | } |
| 533 | |
|
| 534 | | impl Store for CloudStore { |
| 535 | 0× | fn describe(&self) -> String { |
| 536 | 0× | self.name.clone() |
| 537 | 0× | } |
| 538 | |
|
| 539 | 0× | fn has(&self, key: &str) -> Result<bool> { |
| 540 | 0× | let path = self.path(key)?; |
| 541 | 0× | match self.block(self.inner.head(&path)) { |
| 542 | 0× | Ok(_) => Ok(true), |
| 543 | 0× | Err(object_store::Error::NotFound { .. }) => Ok(false), |
| 544 | 0× | Err(e) => Err(self.map(e, key)), |
| 545 | | } |
| 546 | 0× | } |
| 547 | |
|
| 548 | 0× | fn get(&self, key: &str) -> Result<Vec<u8>> { |
| 549 | 0× | let path = self.path(key)?; |
| 550 | 0× | self.block(async { |
| 551 | 0× | let r = self.inner.get(&path).await?; |
| 552 | 0× | r.bytes().await |
| 553 | 0× | }) |
| 554 | 0× | .map(|b| b.to_vec()) |
| 555 | 0× | .map_err(|e| self.map(e, key)) |
| 556 | 0× | } |
| 557 | |
|
| 558 | 0× | fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> { |
| 559 | 0× | let path = self.path(key)?; |
| 560 | 0× | if range.start > range.end { |
| 561 | 0× | return Err(Error::Backend(format!( |
| 562 | 0× | "{key}: bytes {}..{} is not a range", |
| 563 | 0× | range.start, range.end |
| 564 | 0× | ))); |
| 565 | 0× | } |
| 566 | 0× | if range.is_empty() { |
| 567 | 0× | return Ok(Vec::new()); |
| 568 | 0× | } |
| 569 | 0× | let want = (range.end - range.start) as usize; |
| 570 | 0× | let bytes = self |
| 571 | 0× | .block(self.inner.get_range(&path, range.clone())) |
| 572 | 0× | .map_err(|e| self.map(e, key))?; |
| 573 | 0× | if bytes.len() != want { |
| 574 | 0× | return Err(Error::Backend(format!( |
| 575 | 0× | "{key}: bytes {}..{} asked, {} returned: the object is shorter", |
| 576 | 0× | range.start, |
| 577 | 0× | range.end, |
| 578 | 0× | bytes.len() |
| 579 | 0× | ))); |
| 580 | 0× | } |
| 581 | 0× | Ok(bytes.to_vec()) |
| 582 | 0× | } |
| 583 | |
|
| 584 | 0× | fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> { |
| 585 | 0× | let path = self.path(key)?; |
| 586 | 0× | let opts = PutOptions { |
| 587 | 0× | mode: PutMode::Create, |
| 588 | 0× | ..Default::default() |
| 589 | 0× | }; |
| 590 | 0× | self.block( |
| 591 | 0× | self.inner |
| 592 | 0× | .put_opts(&path, PutPayload::from(bytes.to_vec()), opts), |
| 593 | | ) |
| 594 | 0× | .map(|_| ()) |
| 595 | 0× | .map_err(|e| self.map(e, key)) |
| 596 | 0× | } |
| 597 | |
|
| 598 | 0× | fn list(&self, prefix: &str) -> Result<Vec<Entry>> { |
| 599 | | |
| 600 | | |
| 601 | 0× | let dir = prefix.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); |
| 602 | 0× | let full_dir = match (self.prefix.as_str(), dir) { |
| 603 | 0× | ("", "") => None, |
| 604 | 0× | ("", d) => Some(d.to_string()), |
| 605 | 0× | (p, "") => Some(p.to_string()), |
| 606 | 0× | (p, d) => Some(format!("{p}/{d}")), |
| 607 | | }; |
| 608 | 0× | let full_dir = full_dir |
| 609 | 0× | .map(|d| ObjectPath::parse(&d).map_err(|e| Error::Backend(format!("{d}: {e}")))) |
| 610 | 0× | .transpose()?; |
| 611 | 0× | let metas: Vec<object_store::ObjectMeta> = self |
| 612 | 0× | .block(self.inner.list(full_dir.as_ref()).try_collect()) |
| 613 | 0× | .map_err(|e| self.map(e, prefix))?; |
| 614 | 0× | let strip = if self.prefix.is_empty() { |
| 615 | 0× | String::new() |
| 616 | | } else { |
| 617 | 0× | format!("{}/", self.prefix) |
| 618 | | }; |
| 619 | 0× | let mut out: Vec<Entry> = metas |
| 620 | 0× | .into_iter() |
| 621 | 0× | .filter_map(|m| { |
| 622 | 0× | let loc = m.location.to_string(); |
| 623 | 0× | let key = loc.strip_prefix(&strip)?; |
| 624 | 0× | key.starts_with(prefix).then(|| Entry { |
| 625 | 0× | key: key.to_string(), |
| 626 | 0× | size: m.size, |
| 627 | 0× | modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(), |
| 628 | 0× | }) |
| 629 | 0× | }) |
| 630 | 0× | .collect(); |
| 631 | 0× | out.sort_by(|a, b| a.key.cmp(&b.key)); |
| 632 | 0× | Ok(out) |
| 633 | 0× | } |
| 634 | |
|
| 635 | 0× | fn delete(&self, key: &str) -> Result<()> { |
| 636 | 0× | let path = self.path(key)?; |
| 637 | 0× | match self.block(self.inner.delete(&path)) { |
| 638 | 0× | Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), |
| 639 | 0× | Err(e) => Err(self.map(e, key)), |
| 640 | | } |
| 641 | 0× | } |
| 642 | |
|
| 643 | 0× | fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> { |
| 644 | 0× | let path = self.path(key)?; |
| 645 | 0× | let got = self.block(async { |
| 646 | 0× | let r = self.inner.get_opts(&path, GetOptions::default()).await?; |
| 647 | 0× | let meta = r.meta.clone(); |
| 648 | 0× | let bytes = r.bytes().await?; |
| 649 | 0× | Ok::<_, object_store::Error>((bytes, meta)) |
| 650 | 0× | }); |
| 651 | 0× | match got { |
| 652 | 0× | Ok((bytes, meta)) => Ok(Some(( |
| 653 | 0× | bytes.to_vec(), |
| 654 | 0× | Self::version_of(meta.e_tag, meta.version), |
| 655 | 0× | ))), |
| 656 | 0× | Err(object_store::Error::NotFound { .. }) => Ok(None), |
| 657 | 0× | Err(e) => Err(self.map(e, key)), |
| 658 | | } |
| 659 | 0× | } |
| 660 | |
|
| 661 | 0× | fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> { |
| 662 | 0× | let path = self.path(key)?; |
| 663 | 0× | let mode = match expected { |
| 664 | 0× | None => PutMode::Create, |
| 665 | 0× | Some(v) => PutMode::Update(Self::update_version(v)), |
| 666 | | }; |
| 667 | 0× | let opts = PutOptions { |
| 668 | 0× | mode, |
| 669 | 0× | ..Default::default() |
| 670 | 0× | }; |
| 671 | 0× | let put = self |
| 672 | 0× | .block( |
| 673 | 0× | self.inner |
| 674 | 0× | .put_opts(&path, PutPayload::from(bytes.to_vec()), opts), |
| 675 | | ) |
| 676 | 0× | .map_err(|e| match self.map(e, key) { |
| 677 | | |
| 678 | | |
| 679 | 0× | Error::Exists(k) => Error::Conflict(k), |
| 680 | 0× | other => other, |
| 681 | 0× | })?; |
| 682 | 0× | Ok(Self::version_of(put.e_tag, put.version)) |
| 683 | 0× | } |
| 684 | | } |
| 685 | |
|
| 686 | | #[cfg(test)] |
| 687 | | mod tests { |
| 688 | |
|
| 689 | | |
| 690 | | |
| 691 | | #[test] |
| 692 | 1× | fn a_store_opened_again_shares_its_client() { |
| 693 | 1× | let creds = |k: &str| Credentials::Aws { |
| 694 | 3× | access_key_id: k.into(), |
| 695 | 3× | secret_access_key: "s".into(), |
| 696 | 3× | session_token: None, |
| 697 | 3× | }; |
| 698 | 1× | let url = "s3://oxy-shared-test/repos/a?region=eu-west-2"; |
| 699 | 1× | let before = super::stats().opens; |
| 700 | 1× | let a = super::shared(url, Some(creds("one"))).unwrap(); |
| 701 | 1× | let b = super::shared(url, Some(creds("one"))).unwrap(); |
| 702 | 1× | assert!(std::sync::Arc::ptr_eq(&a, &b)); |
| 703 | 1× | let other_keys = super::shared(url, Some(creds("two"))).unwrap(); |
| 704 | 1× | assert!( |
| 705 | 1× | !std::sync::Arc::ptr_eq(&a, &other_keys), |
| 706 | | "other credentials, another client" |
| 707 | | ); |
| 708 | 1× | assert!( |
| 709 | 1× | super::stats().opens - before >= 2, |
| 710 | | "two clients opened (other tests may open more)" |
| 711 | | ); |
| 712 | 1× | } |
| 713 | |
|
| 714 | | #[tokio::test] |
| 715 | 1× | async fn a_store_can_be_used_from_inside_a_runtime() { |
| 716 | | |
| 717 | | |
| 718 | 1× | let store = CloudStore::open( |
| 719 | 1× | "s3://oxy-no-such-bucket/p?region=eu-west-2&endpoint=http://127.0.0.1:9", |
| 720 | | ) |
| 721 | 1× | .unwrap(); |
| 722 | 1× | assert_eq!(store.block(async { 7 }), 7); |
| 723 | 1× | drop(store); |
| 724 | 1× | } |
| 725 | |
|
| 726 | | #[test] |
| 727 | 1× | fn credentials_round_trip_and_never_show_their_secret() { |
| 728 | 1× | let aws = Credentials::Aws { |
| 729 | 1× | access_key_id: "AKIDEXAMPLE".into(), |
| 730 | 1× | secret_access_key: "wJalrXUtnFEMI".into(), |
| 731 | 1× | session_token: None, |
| 732 | 1× | }; |
| 733 | 1× | assert_eq!(Credentials::from_json(&aws.to_json()).unwrap(), aws); |
| 734 | 1× | assert_eq!(format!("{aws:?}"), "Aws(AKIDEXAMPLE, secret hidden)"); |
| 735 | 1× | let az = Credentials::Azure { |
| 736 | 1× | tenant_id: "t".into(), |
| 737 | 1× | client_id: "c".into(), |
| 738 | 1× | client_secret: "s3cr3t".into(), |
| 739 | 1× | }; |
| 740 | 1× | assert_eq!(Credentials::from_json(&az.to_json()).unwrap(), az); |
| 741 | 1× | assert!(!format!("{az:?}").contains("s3cr3t")); |
| 742 | 1× | let key = r#"{"type":"service_account","client_email":"x@y","private_key":"k"}"#; |
| 743 | 1× | let gcp = Credentials::Gcp { |
| 744 | 1× | service_account_key: key.into(), |
| 745 | 1× | }; |
| 746 | 1× | assert_eq!(Credentials::from_json(&gcp.to_json()).unwrap(), gcp); |
| 747 | 1× | assert!(!format!("{gcp:?}").contains("private_key")); |
| 748 | 4× | for (bad, why) in [ |
| 749 | 1× | (r#"{"kind":"aws","access_key_id":"a"}"#, "secret_access_key"), |
| 750 | 1× | ( |
| 751 | 1× | r#"{"kind":"gcp","service_account_key":"{\"type\":\"authorized_user\"}"}"#, |
| 752 | 1× | "not a service account key", |
| 753 | 1× | ), |
| 754 | 1× | (r#"{"kind":"ftp"}"#, "aws, gcp or azure"), |
| 755 | 1× | ("nope", "not JSON"), |
| 756 | 1× | ] { |
| 757 | 4× | let e = Credentials::from_json(bad).unwrap_err().to_string(); |
| 758 | 4× | assert!(e.contains(why), "{bad}: {e}"); |
| 759 | | } |
| 760 | 1× | let e = CloudStore::open_with("gs://bucket/p", Some(&aws)) |
| 761 | 1× | .err() |
| 762 | 1× | .unwrap() |
| 763 | 1× | .to_string(); |
| 764 | 1× | assert!(e.contains("are for s3:// stores"), "{e}"); |
| 765 | 1× | } |
| 766 | |
|
| 767 | | use super::*; |
| 768 | |
|
| 769 | | #[test] |
| 770 | 1× | fn urls_parse_with_their_parameters() { |
| 771 | 1× | let u = |
| 772 | 1× | StoreUrl::parse("s3://my-bucket/repos/oxygen?profile=work®ion=eu-west-2").unwrap(); |
| 773 | 1× | assert_eq!(u.scheme, "s3"); |
| 774 | 1× | assert_eq!(u.host, "my-bucket"); |
| 775 | 1× | assert_eq!(u.path, "repos/oxygen"); |
| 776 | 1× | assert_eq!(u.param("profile"), Some("work")); |
| 777 | 1× | assert_eq!(u.param("region"), Some("eu-west-2")); |
| 778 | 1× | assert_eq!(u.plain(), "s3://my-bucket/repos/oxygen"); |
| 779 | 1× | let u = StoreUrl::parse("gs://bucket").unwrap(); |
| 780 | 1× | assert_eq!((u.host.as_str(), u.path.as_str()), ("bucket", "")); |
| 781 | 1× | assert_eq!(u.plain(), "gs://bucket"); |
| 782 | 1× | let u = StoreUrl::parse("az://acct/container/a/b/?endpoint=http%3A%2F%2F127.0.0.1%3A10000") |
| 783 | 1× | .unwrap(); |
| 784 | 1× | assert_eq!(u.path, "container/a/b"); |
| 785 | 1× | assert_eq!(u.param("endpoint"), Some("http://127.0.0.1:10000")); |
| 786 | 1× | assert!(StoreUrl::parse("s3://").is_err()); |
| 787 | 1× | assert!(StoreUrl::parse("nonsense").is_err()); |
| 788 | 1× | } |
| 789 | |
|
| 790 | | #[test] |
| 791 | 1× | fn versions_carry_both_an_etag_and_a_generation() { |
| 792 | 1× | let v = CloudStore::version_of(Some("\"abc\"".into()), Some("17".into())); |
| 793 | 1× | let u = CloudStore::update_version(&v); |
| 794 | 1× | assert_eq!(u.e_tag.as_deref(), Some("\"abc\"")); |
| 795 | 1× | assert_eq!(u.version.as_deref(), Some("17")); |
| 796 | 1× | let u = CloudStore::update_version(&CloudStore::version_of(None, Some("3".into()))); |
| 797 | 1× | assert_eq!((u.e_tag, u.version.as_deref()), (None, Some("3"))); |
| 798 | 1× | } |
| 799 | | } |