opendal/services/moka/
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::{MokaCore, MokaValue};
21use crate::raw::oio;
22use crate::raw::*;
23use crate::*;
24
25pub struct MokaWriter {
26    core: Arc<MokaCore>,
27    path: String,
28    op: OpWrite,
29    buffer: oio::QueueBuf,
30}
31
32impl MokaWriter {
33    pub fn new(core: Arc<MokaCore>, path: String, op: OpWrite) -> Self {
34        Self {
35            core,
36            path,
37            op,
38            buffer: oio::QueueBuf::new(),
39        }
40    }
41}
42
43impl oio::Write for MokaWriter {
44    async fn write(&mut self, bs: Buffer) -> Result<()> {
45        self.buffer.push(bs);
46        Ok(())
47    }
48
49    async fn close(&mut self) -> Result<Metadata> {
50        let buf = self.buffer.clone().collect();
51        let length = buf.len() as u64;
52
53        // Build metadata with write options
54        let mut metadata =
55            Metadata::new(EntryMode::from_path(&self.path)).with_content_length(length);
56
57        if let Some(content_type) = self.op.content_type() {
58            metadata.set_content_type(content_type);
59        }
60        if let Some(content_disposition) = self.op.content_disposition() {
61            metadata.set_content_disposition(content_disposition);
62        }
63        if let Some(cache_control) = self.op.cache_control() {
64            metadata.set_cache_control(cache_control);
65        }
66        if let Some(content_encoding) = self.op.content_encoding() {
67            metadata.set_content_encoding(content_encoding);
68        }
69
70        let value = MokaValue {
71            metadata: metadata.clone(),
72            content: buf,
73        };
74
75        self.core.set(&self.path, value).await?;
76        Ok(metadata)
77    }
78
79    async fn abort(&mut self) -> Result<()> {
80        self.buffer.clear();
81        Ok(())
82    }
83}