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