opendal/services/moka/core.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::fmt::Debug;
19
20use moka::future::Cache;
21
22use crate::*;
23
24/// Value stored in moka cache containing both metadata and content
25#[derive(Clone)]
26pub struct MokaValue {
27 /// Stored metadata in moka cache.
28 pub metadata: Metadata,
29 /// Stored content in moka cache.
30 pub content: Buffer,
31}
32
33#[derive(Clone)]
34pub struct MokaCore {
35 pub cache: Cache<String, MokaValue>,
36}
37
38impl Debug for MokaCore {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 f.debug_struct("MokaCore")
41 .field("size", &self.cache.weighted_size())
42 .field("count", &self.cache.entry_count())
43 .finish()
44 }
45}
46
47impl MokaCore {
48 pub async fn get(&self, key: &str) -> Result<Option<MokaValue>> {
49 Ok(self.cache.get(key).await)
50 }
51
52 pub async fn set(&self, key: &str, value: MokaValue) -> Result<()> {
53 self.cache.insert(key.to_string(), value).await;
54 Ok(())
55 }
56
57 pub async fn delete(&self, key: &str) -> Result<()> {
58 self.cache.invalidate(key).await;
59 Ok(())
60 }
61}