opendal/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 std::sync::Arc;
19
20use super::core::{MiniMokaCore, MiniMokaValue};
21use crate::raw::oio;
22use crate::raw::*;
23use crate::*;
24
25pub struct MiniMokaWriter {
26    core: Arc<MiniMokaCore>,
27    path: String,
28    op: OpWrite,
29    buffer: oio::QueueBuf,
30}
31
32impl MiniMokaWriter {
33    pub fn new(core: Arc<MiniMokaCore>, 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 MiniMokaWriter {
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
52        let mut md = Metadata::new(EntryMode::from_path(&self.path));
53        md.set_content_length(buf.len() as u64);
54        md.set_last_modified(chrono::Utc::now());
55
56        // Set metadata from OpWrite
57        if let Some(content_type) = self.op.content_type() {
58            md.set_content_type(content_type);
59        }
60        if let Some(content_disposition) = self.op.content_disposition() {
61            md.set_content_disposition(content_disposition);
62        }
63        if let Some(content_encoding) = self.op.content_encoding() {
64            md.set_content_encoding(content_encoding);
65        }
66        if let Some(cache_control) = self.op.cache_control() {
67            md.set_cache_control(cache_control);
68        }
69
70        let value = MiniMokaValue {
71            metadata: md.clone(),
72            content: buf,
73        };
74
75        self.core.cache.insert(self.path.clone(), value);
76
77        Ok(md)
78    }
79
80    async fn abort(&mut self) -> Result<()> {
81        self.buffer.clear();
82        Ok(())
83    }
84}