opendal/services/gdrive/writer.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use bytes::Buf;
21use http::StatusCode;
22
23use super::core::GdriveCore;
24use super::core::GdriveFile;
25use super::error::parse_error;
26use crate::raw::*;
27use crate::*;
28
29pub struct GdriveWriter {
30 core: Arc<GdriveCore>,
31
32 path: String,
33
34 file_id: Option<String>,
35}
36
37impl GdriveWriter {
38 pub fn new(core: Arc<GdriveCore>, path: String, file_id: Option<String>) -> Self {
39 GdriveWriter {
40 core,
41 path,
42
43 file_id,
44 }
45 }
46}
47
48impl oio::OneShotWrite for GdriveWriter {
49 async fn write_once(&self, bs: Buffer) -> Result<Metadata> {
50 let size = bs.len();
51
52 let resp = if let Some(file_id) = &self.file_id {
53 self.core
54 .gdrive_upload_overwrite_simple_request(file_id, size as u64, bs)
55 .await
56 } else {
57 self.core
58 .gdrive_upload_simple_request(&self.path, size as u64, bs)
59 .await
60 }?;
61
62 let status = resp.status();
63 match status {
64 StatusCode::OK | StatusCode::CREATED => {
65 // If we don't have the file id before, let's update the cache to avoid re-fetching.
66 if self.file_id.is_none() {
67 let bs = resp.into_body();
68 let file: GdriveFile =
69 serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
70 self.core.path_cache.insert(&self.path, &file.id).await;
71 }
72 Ok(Metadata::default())
73 }
74 _ => Err(parse_error(resp)),
75 }
76 }
77}