ballista_cache/loading_cache/
mod.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
18/// It's a fork version from the influxdb_iox::cache_system[https://github.com/influxdata/influxdb_iox].
19/// Later we will propose to influxdb team to make this cache part more general.
20mod cancellation_safe_future;
21pub mod driver;
22pub mod loader;
23
24use async_trait::async_trait;
25use std::fmt::Debug;
26use std::hash::Hash;
27
28/// High-level loading cache interface.
29///
30/// Cache entries are manually added using get(Key, GetExtra) or put(Key, Value),
31/// and are stored in the cache until either evicted or manually invalidated.
32///
33/// # Concurrency
34///
35/// Multiple cache requests for different keys can run at the same time. When data is requested for
36/// the same key, the underlying loader will only be polled once, even when the requests are made
37/// while the loader is still running.
38///
39/// # Cancellation
40///
41/// Canceling a [`get`](Self::get) request will NOT cancel the underlying loader. The data will
42/// still be cached.
43#[async_trait]
44pub trait LoadingCache: Debug + Send + Sync + 'static {
45    /// Cache key.
46    type K: Clone + Eq + Hash + Debug + Ord + Send + 'static;
47
48    /// Cache value.
49    type V: Clone + Debug + Send + 'static;
50
51    /// Extra data that is provided during [`GET`](Self::get) but that is NOT part of the cache key.
52    type GetExtra: Debug + Send + 'static;
53
54    /// Get value from cache.
55    ///
56    /// In contrast to [`get`](Self::get) this will only return a value if there is a stored value.
57    /// This will NOT start a new loading task.
58    fn get_if_present(&self, k: Self::K) -> Option<Self::V>;
59
60    /// Get value from cache.
61    ///
62    /// Note that `extra` is only used if the key is missing from the storage backend
63    /// and no value loader for this key is running yet.
64    async fn get(&self, k: Self::K, extra: Self::GetExtra) -> Self::V {
65        self.get_with_status(k, extra).await.0
66    }
67
68    /// Get value from cache and the [status](CacheGetStatus).
69    ///
70    /// Note that `extra` is only used if the key is missing from the storage backend
71    /// and no value loader for this key is running yet.
72    async fn get_with_status(
73        &self,
74        k: Self::K,
75        extra: Self::GetExtra,
76    ) -> (Self::V, CacheGetStatus);
77
78    /// Side-load an entry into the cache. If the cache previously contained a value associated with key,
79    /// the old value is replaced by value.
80    ///
81    /// This will also complete a currently running loader for this key.
82    async fn put(&self, k: Self::K, v: Self::V);
83
84    /// Discard any cached value for the key.
85    ///
86    /// This will also interrupt a currently running loader for this key.
87    fn invalidate(&self, k: Self::K);
88}
89
90/// Status of a [`Cache`] [GET](LoadingCache::get_with_status) request.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum CacheGetStatus {
93    /// The requested entry was present in the storage backend.
94    Hit,
95
96    /// The requested entry was NOT present in the storage backend and there's no running value loader.
97    Miss,
98
99    /// The requested entry was NOT present in the storage backend, but there was already a running value loader for
100    /// this particular key.
101    MissAlreadyLoading,
102}
103
104impl CacheGetStatus {
105    /// Get human and machine readable name.
106    pub fn name(&self) -> &'static str {
107        match self {
108            Self::Hit => "hit",
109            Self::Miss => "miss",
110            Self::MissAlreadyLoading => "miss_already_loading",
111        }
112    }
113}