|
| 1 | +// Copyright 2023 Greptime Team |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +use std::num::NonZeroUsize; |
| 16 | +use std::ops::DerefMut; |
| 17 | +use std::sync::Arc; |
| 18 | + |
| 19 | +use async_trait::async_trait; |
| 20 | +use futures::future::BoxFuture; |
| 21 | +use lru::LruCache; |
| 22 | +use opendal::layers::CachePolicy; |
| 23 | +use opendal::raw::output::Reader; |
| 24 | +use opendal::raw::{Accessor, RpDelete, RpRead}; |
| 25 | +use opendal::{ErrorKind, OpDelete, OpRead, OpWrite, Result}; |
| 26 | +use tokio::sync::Mutex; |
| 27 | + |
| 28 | +#[derive(Debug)] |
| 29 | +pub struct LruCachePolicy { |
| 30 | + lru_cache: Arc<Mutex<LruCache<String, ()>>>, |
| 31 | +} |
| 32 | + |
| 33 | +impl LruCachePolicy { |
| 34 | + pub fn new(capacity: usize) -> Self { |
| 35 | + Self { |
| 36 | + lru_cache: Arc::new(Mutex::new(LruCache::new( |
| 37 | + NonZeroUsize::new(capacity).unwrap(), |
| 38 | + ))), |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + fn cache_path(&self, path: &str, args: &OpRead) -> String { |
| 43 | + format!("{}.cache-{}", path, args.range().to_header()) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +#[async_trait] |
| 48 | +impl CachePolicy for LruCachePolicy { |
| 49 | + fn on_read( |
| 50 | + &self, |
| 51 | + inner: Arc<dyn Accessor>, |
| 52 | + cache: Arc<dyn Accessor>, |
| 53 | + path: &str, |
| 54 | + args: OpRead, |
| 55 | + ) -> BoxFuture<'static, Result<(RpRead, Reader)>> { |
| 56 | + let path = path.to_string(); |
| 57 | + let cache_path = self.cache_path(&path, &args); |
| 58 | + let lru_cache = self.lru_cache.clone(); |
| 59 | + Box::pin(async move { |
| 60 | + match cache.read(&cache_path, OpRead::default()).await { |
| 61 | + Ok(v) => { |
| 62 | + // update lru when cache hit |
| 63 | + let mut lru_cache = lru_cache.lock().await; |
| 64 | + lru_cache.get_or_insert(cache_path.clone(), || ()); |
| 65 | + Ok(v) |
| 66 | + } |
| 67 | + Err(err) if err.kind() == ErrorKind::ObjectNotFound => { |
| 68 | + let (rp, reader) = inner.read(&path, args.clone()).await?; |
| 69 | + let size = rp.clone().into_metadata().content_length(); |
| 70 | + let _ = cache |
| 71 | + .write(&cache_path, OpWrite::new(size), Box::new(reader)) |
| 72 | + .await?; |
| 73 | + match cache.read(&cache_path, OpRead::default()).await { |
| 74 | + Ok(v) => { |
| 75 | + let r = { |
| 76 | + // push new cache file name to lru |
| 77 | + let mut lru_cache = lru_cache.lock().await; |
| 78 | + lru_cache.push(cache_path.clone(), ()) |
| 79 | + }; |
| 80 | + // delete the evicted cache file |
| 81 | + if let Some((k, _v)) = r { |
| 82 | + let _ = cache.delete(&k, OpDelete::new()).await; |
| 83 | + } |
| 84 | + Ok(v) |
| 85 | + } |
| 86 | + Err(_) => return inner.read(&path, args).await, |
| 87 | + } |
| 88 | + } |
| 89 | + Err(_) => return inner.read(&path, args).await, |
| 90 | + } |
| 91 | + }) |
| 92 | + } |
| 93 | + |
| 94 | + fn on_delete( |
| 95 | + &self, |
| 96 | + inner: Arc<dyn Accessor>, |
| 97 | + cache: Arc<dyn Accessor>, |
| 98 | + path: &str, |
| 99 | + args: OpDelete, |
| 100 | + ) -> BoxFuture<'static, Result<RpDelete>> { |
| 101 | + let path = path.to_string(); |
| 102 | + let lru_cache = self.lru_cache.clone(); |
| 103 | + Box::pin(async move { |
| 104 | + let cache_files: Vec<String> = { |
| 105 | + let mut guard = lru_cache.lock().await; |
| 106 | + let lru = guard.deref_mut(); |
| 107 | + let cache_files = lru |
| 108 | + .iter() |
| 109 | + .filter(|(k, _v)| k.starts_with(format!("{path}.cache-").as_str())) |
| 110 | + .map(|(k, _v)| k.clone()) |
| 111 | + .collect::<Vec<_>>(); |
| 112 | + for k in &cache_files { |
| 113 | + lru.pop(k); |
| 114 | + } |
| 115 | + cache_files |
| 116 | + }; |
| 117 | + for file in cache_files { |
| 118 | + let _ = cache.delete(&file, OpDelete::new()).await; |
| 119 | + } |
| 120 | + return inner.delete(&path, args).await; |
| 121 | + }) |
| 122 | + } |
| 123 | +} |
0 commit comments