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