1use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use http::Response;
23use http::StatusCode;
24use log::debug;
25use reqsign::GoogleCredentialLoader;
26use reqsign::GoogleSigner;
27use reqsign::GoogleTokenLoad;
28use reqsign::GoogleTokenLoader;
29
30use super::core::*;
31use super::delete::GcsDeleter;
32use super::error::parse_error;
33use super::lister::GcsLister;
34use super::writer::GcsWriter;
35use super::writer::GcsWriters;
36use super::DEFAULT_SCHEME;
37use crate::raw::oio::BatchDeleter;
38use crate::raw::*;
39use crate::services::GcsConfig;
40use crate::*;
41const DEFAULT_GCS_ENDPOINT: &str = "https://storage.googleapis.com";
42const DEFAULT_GCS_SCOPE: &str = "https://www.googleapis.com/auth/devstorage.read_write";
43
44impl Configurator for GcsConfig {
45 type Builder = GcsBuilder;
46
47 #[allow(deprecated)]
48 fn into_builder(self) -> Self::Builder {
49 GcsBuilder {
50 config: self,
51 http_client: None,
52 customized_token_loader: None,
53 }
54 }
55}
56
57#[doc = include_str!("docs.md")]
59#[derive(Default)]
60pub struct GcsBuilder {
61 config: GcsConfig,
62
63 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
64 http_client: Option<HttpClient>,
65 customized_token_loader: Option<Box<dyn GoogleTokenLoad>>,
66}
67
68impl Debug for GcsBuilder {
69 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
70 let mut ds = f.debug_struct("GcsBuilder");
71
72 ds.field("config", &self.config);
73 ds.finish_non_exhaustive()
74 }
75}
76
77impl GcsBuilder {
78 pub fn root(mut self, root: &str) -> Self {
80 self.config.root = if root.is_empty() {
81 None
82 } else {
83 Some(root.to_string())
84 };
85
86 self
87 }
88
89 pub fn bucket(mut self, bucket: &str) -> Self {
91 self.config.bucket = bucket.to_string();
92 self
93 }
94
95 pub fn scope(mut self, scope: &str) -> Self {
107 if !scope.is_empty() {
108 self.config.scope = Some(scope.to_string())
109 };
110 self
111 }
112
113 pub fn service_account(mut self, service_account: &str) -> Self {
118 if !service_account.is_empty() {
119 self.config.service_account = Some(service_account.to_string())
120 };
121 self
122 }
123
124 pub fn endpoint(mut self, endpoint: &str) -> Self {
126 if !endpoint.is_empty() {
127 self.config.endpoint = Some(endpoint.to_string())
128 };
129 self
130 }
131
132 pub fn credential(mut self, credential: &str) -> Self {
140 if !credential.is_empty() {
141 self.config.credential = Some(credential.to_string())
142 };
143 self
144 }
145
146 pub fn credential_path(mut self, path: &str) -> Self {
153 if !path.is_empty() {
154 self.config.credential_path = Some(path.to_string())
155 };
156 self
157 }
158
159 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
166 #[allow(deprecated)]
167 pub fn http_client(mut self, client: HttpClient) -> Self {
168 self.http_client = Some(client);
169 self
170 }
171
172 pub fn customized_token_loader(mut self, token_load: Box<dyn GoogleTokenLoad>) -> Self {
174 self.customized_token_loader = Some(token_load);
175 self
176 }
177
178 pub fn token(mut self, token: String) -> Self {
180 self.config.token = Some(token);
181 self
182 }
183
184 pub fn disable_vm_metadata(mut self) -> Self {
186 self.config.disable_vm_metadata = true;
187 self
188 }
189
190 pub fn disable_config_load(mut self) -> Self {
192 self.config.disable_config_load = true;
193 self
194 }
195
196 pub fn predefined_acl(mut self, acl: &str) -> Self {
206 if !acl.is_empty() {
207 self.config.predefined_acl = Some(acl.to_string())
208 };
209 self
210 }
211
212 pub fn default_storage_class(mut self, class: &str) -> Self {
220 if !class.is_empty() {
221 self.config.default_storage_class = Some(class.to_string())
222 };
223 self
224 }
225
226 pub fn allow_anonymous(mut self) -> Self {
231 self.config.allow_anonymous = true;
232 self
233 }
234}
235
236impl Builder for GcsBuilder {
237 type Config = GcsConfig;
238
239 fn build(self) -> Result<impl Access> {
240 debug!("backend build started: {self:?}");
241
242 let root = normalize_root(&self.config.root.unwrap_or_default());
243 debug!("backend use root {root}");
244
245 let bucket = match self.config.bucket.is_empty() {
247 false => Ok(&self.config.bucket),
248 true => Err(
249 Error::new(ErrorKind::ConfigInvalid, "The bucket is misconfigured")
250 .with_operation("Builder::build")
251 .with_context("service", Scheme::Gcs),
252 ),
253 }?;
254
255 let endpoint = self
258 .config
259 .endpoint
260 .clone()
261 .unwrap_or_else(|| DEFAULT_GCS_ENDPOINT.to_string());
262 debug!("backend use endpoint: {endpoint}");
263
264 let mut cred_loader = GoogleCredentialLoader::default();
265 if let Some(cred) = &self.config.credential {
266 cred_loader = cred_loader.with_content(cred);
267 }
268 if let Some(cred) = &self.config.credential_path {
269 cred_loader = cred_loader.with_path(cred);
270 }
271 #[cfg(target_arch = "wasm32")]
272 {
273 cred_loader = cred_loader.with_disable_env();
274 cred_loader = cred_loader.with_disable_well_known_location();
275 }
276
277 if self.config.disable_config_load {
278 cred_loader = cred_loader
279 .with_disable_env()
280 .with_disable_well_known_location();
281 }
282
283 let scope = if let Some(scope) = &self.config.scope {
284 scope
285 } else {
286 DEFAULT_GCS_SCOPE
287 };
288
289 let mut token_loader = GoogleTokenLoader::new(scope, GLOBAL_REQWEST_CLIENT.clone());
290 if let Some(account) = &self.config.service_account {
291 token_loader = token_loader.with_service_account(account);
292 }
293 if let Ok(Some(cred)) = cred_loader.load() {
294 token_loader = token_loader.with_credentials(cred)
295 }
296 if let Some(loader) = self.customized_token_loader {
297 token_loader = token_loader.with_customized_token_loader(loader)
298 }
299
300 if self.config.disable_vm_metadata {
301 token_loader = token_loader.with_disable_vm_metadata(true);
302 }
303
304 let signer = GoogleSigner::new("storage");
305
306 let backend = GcsBackend {
307 core: Arc::new(GcsCore {
308 info: {
309 let am = AccessorInfo::default();
310 am.set_scheme(DEFAULT_SCHEME)
311 .set_root(&root)
312 .set_name(bucket)
313 .set_native_capability(Capability {
314 stat: true,
315 stat_with_if_match: true,
316 stat_with_if_none_match: true,
317
318 read: true,
319
320 read_with_if_match: true,
321 read_with_if_none_match: true,
322
323 write: true,
324 write_can_empty: true,
325 write_can_multi: true,
326 write_with_cache_control: true,
327 write_with_content_type: true,
328 write_with_content_encoding: true,
329 write_with_user_metadata: true,
330 write_with_if_not_exists: true,
331
332 write_multi_min_size: Some(5 * 1024 * 1024),
336 write_multi_max_size: if cfg!(target_pointer_width = "64") {
340 Some(5 * 1024 * 1024 * 1024)
341 } else {
342 Some(usize::MAX)
343 },
344
345 delete: true,
346 delete_max_size: Some(100),
347 copy: true,
348
349 list: true,
350 list_with_limit: true,
351 list_with_start_after: true,
352 list_with_recursive: true,
353
354 presign: true,
355 presign_stat: true,
356 presign_read: true,
357 presign_write: true,
358
359 shared: true,
360
361 ..Default::default()
362 });
363
364 #[allow(deprecated)]
366 if let Some(client) = self.http_client {
367 am.update_http_client(|_| client);
368 }
369
370 am.into()
371 },
372 endpoint,
373 bucket: bucket.to_string(),
374 root,
375 signer,
376 token_loader,
377 token: self.config.token,
378 scope: scope.to_string(),
379 credential_loader: cred_loader,
380 predefined_acl: self.config.predefined_acl.clone(),
381 default_storage_class: self.config.default_storage_class.clone(),
382 allow_anonymous: self.config.allow_anonymous,
383 }),
384 };
385
386 Ok(backend)
387 }
388}
389
390#[derive(Clone, Debug)]
392pub struct GcsBackend {
393 core: Arc<GcsCore>,
394}
395
396impl Access for GcsBackend {
397 type Reader = HttpBody;
398 type Writer = GcsWriters;
399 type Lister = oio::PageLister<GcsLister>;
400 type Deleter = oio::BatchDeleter<GcsDeleter>;
401
402 fn info(&self) -> Arc<AccessorInfo> {
403 self.core.info.clone()
404 }
405
406 async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
407 let resp = self.core.gcs_get_object_metadata(path, &args).await?;
408
409 if !resp.status().is_success() {
410 return Err(parse_error(resp));
411 }
412
413 let slc = resp.into_body();
414 let m = GcsCore::build_metadata_from_object_response(path, slc)?;
415
416 Ok(RpStat::new(m))
417 }
418
419 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
420 let resp = self.core.gcs_get_object(path, args.range(), &args).await?;
421
422 let status = resp.status();
423
424 match status {
425 StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
426 Ok((RpRead::default(), resp.into_body()))
427 }
428 _ => {
429 let (part, mut body) = resp.into_parts();
430 let buf = body.to_buffer().await?;
431 Err(parse_error(Response::from_parts(part, buf)))
432 }
433 }
434 }
435
436 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
437 let concurrent = args.concurrent();
438 let w = GcsWriter::new(self.core.clone(), path, args);
439 let w = oio::MultipartWriter::new(self.core.info.clone(), w, concurrent);
440
441 Ok((RpWrite::default(), w))
442 }
443
444 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
445 Ok((
446 RpDelete::default(),
447 BatchDeleter::new(GcsDeleter::new(self.core.clone())),
448 ))
449 }
450
451 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
452 let l = GcsLister::new(
453 self.core.clone(),
454 path,
455 args.recursive(),
456 args.limit(),
457 args.start_after(),
458 );
459
460 Ok((RpList::default(), oio::PageLister::new(l)))
461 }
462
463 async fn copy(&self, from: &str, to: &str, _: OpCopy) -> Result<RpCopy> {
464 let resp = self.core.gcs_copy_object(from, to).await?;
465
466 if resp.status().is_success() {
467 Ok(RpCopy::default())
468 } else {
469 Err(parse_error(resp))
470 }
471 }
472
473 async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
474 let req = match args.operation() {
476 PresignOperation::Stat(v) => self.core.gcs_head_object_xml_request(path, v),
477 PresignOperation::Read(v) => self.core.gcs_get_object_xml_request(path, v),
478 PresignOperation::Write(v) => {
479 self.core
480 .gcs_insert_object_xml_request(path, v, Buffer::new())
481 }
482 PresignOperation::Delete(_) => Err(Error::new(
483 ErrorKind::Unsupported,
484 "operation is not supported",
485 )),
486 };
487 let mut req = req?;
488 self.core.sign_query(&mut req, args.expire())?;
489
490 let (parts, _) = req.into_parts();
492
493 Ok(RpPresign::new(PresignedRequest::new(
494 parts.method,
495 parts.uri,
496 parts.headers,
497 )))
498 }
499}