opendal_core/services/cloudflare_kv/
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 super::core::CloudflareKvCore;
21use super::error::parse_error;
22use crate::raw::*;
23use crate::services::cloudflare_kv::model::CfKvMetadata;
24use crate::*;
25use http::StatusCode;
26
27pub struct CloudflareWriter {
28    core: Arc<CloudflareKvCore>,
29    path: String,
30}
31
32impl CloudflareWriter {
33    pub fn new(core: Arc<CloudflareKvCore>, path: String) -> Self {
34        CloudflareWriter { core, path }
35    }
36}
37
38impl oio::OneShotWrite for CloudflareWriter {
39    async fn write_once(&self, bs: Buffer) -> Result<Metadata> {
40        let cf_kv_metadata = CfKvMetadata {
41            etag: build_tmp_path_of(&self.path),
42            last_modified: Timestamp::now().to_string(),
43            content_length: bs.len(),
44            is_dir: self.path.ends_with('/'),
45        };
46
47        let resp = self
48            .core
49            .set(&self.path, bs, cf_kv_metadata.clone())
50            .await?;
51
52        let status = resp.status();
53
54        match status {
55            StatusCode::OK => {
56                let mut metadata = Metadata::default();
57                metadata.set_etag(&cf_kv_metadata.etag);
58                metadata.set_last_modified(cf_kv_metadata.last_modified.parse::<Timestamp>()?);
59                metadata.set_content_length(cf_kv_metadata.content_length as u64);
60
61                Ok(metadata)
62            }
63            _ => Err(parse_error(resp)),
64        }
65    }
66}