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