Skip to main content

common_cache/
paged.rs

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//! Immutable byte pages backed by native cache loading and direct range reads.
16
17#[cfg(test)]
18mod tests;
19
20use std::collections::{BTreeMap, BTreeSet};
21use std::hash::Hash;
22use std::io;
23use std::num::NonZeroU64;
24use std::ops::Range;
25use std::sync::Arc;
26use std::time::Duration;
27
28use bytes::{Bytes, BytesMut};
29use common_base::range_read::RangeReader;
30
31use crate::metrics::{CacheMetrics, CacheSizeMetric, CacheSizeRegistration};
32use crate::page::PageLayout;
33use crate::{Cache, RemovalCause, batch};
34
35/// Business-level events; callers retain their existing hit/miss metric units.
36pub enum PageEvent {
37    /// Unique logical page lookups in one request, before any missing loads execute.
38    Lookup { hits: usize, misses: usize },
39    /// One successful native page loader, excluding waiters and hits.
40    Loaded { bytes: u64 },
41    /// Backend eviction, excluding unadmitted values released by their owners.
42    Evicted { cause: RemovalCause },
43}
44
45/// Caller-bound metrics without storage-engine dependencies or global registrations.
46#[derive(Clone)]
47pub struct PageCacheObserver {
48    pub bytes: CacheSizeMetric,
49    pub capacity: CacheSizeMetric,
50    pub loads: Option<Arc<CacheMetrics>>,
51    pub events: Arc<dyn Fn(PageEvent) + Send + Sync>,
52}
53
54/// Byte accounting for one successful fetch. Hits are initial lookups, not waiters.
55#[derive(Debug, Default)]
56pub struct PageFetchStats {
57    pub cache_hit: usize,
58    pub cache_miss: usize,
59    /// Requested intersections already cached; overlapping requests count repeatedly.
60    pub cached_bytes: u64,
61    pub cached_fragments: usize,
62    /// Original request lengths, including duplicates and overlaps.
63    pub requested_bytes: u64,
64    /// Sum of unique logical page lengths, clipped at EOF, including cache hits.
65    pub aligned_bytes: u64,
66    /// Union of original request byte ranges, excluding overlaps.
67    pub unique_requested_bytes: u64,
68}
69
70/// Caches fixed-size byte pages of immutable content identified by `K`.
71/// File identity must include any version needed to distinguish different contents.
72/// Missing pages elected by this fetch are submitted through [`RangeReader::read_vec`].
73pub struct PagedCache<K> {
74    cache: Cache<(K, u64), Arc<CachedPage>>,
75    page_size: u64,
76    observer: PageCacheObserver,
77    _capacity_registration: CacheSizeRegistration,
78}
79
80impl<K: Hash + Eq + Clone + Send + Sync + 'static> PagedCache<K> {
81    /// Creates an independent cache budget. Zero page size is rejected by fetch.
82    pub fn new(
83        name: &str,
84        capacity: u64,
85        page_size: u64,
86        weigher: impl Fn(&(K, u64), &Bytes) -> u32 + Send + Sync + 'static,
87        observer: PageCacheObserver,
88    ) -> Self {
89        Self::new_with_ttl(name, capacity, page_size, weigher, observer, None)
90    }
91
92    /// Creates a page cache with optional expiration measured from insertion.
93    pub fn new_with_ttl(
94        name: &str,
95        capacity: u64,
96        page_size: u64,
97        weigher: impl Fn(&(K, u64), &Bytes) -> u32 + Send + Sync + 'static,
98        observer: PageCacheObserver,
99        ttl: Option<Duration>,
100    ) -> Self {
101        let events = observer.events.clone();
102        let mut cache = Cache::new_with_ttl(
103            name,
104            capacity,
105            move |key, value: &Arc<CachedPage>| weigher(key, &value.bytes),
106            move |_, _, cause| {
107                events(PageEvent::Evicted { cause });
108            },
109            ttl,
110        )
111        .with_size_metric(observer.bytes.clone());
112        if let Some(metrics) = &observer.loads {
113            cache = cache.with_metrics(metrics.clone());
114        }
115        let capacity_registration = observer.capacity.register(move || capacity);
116        Self {
117            _capacity_registration: capacity_registration,
118            cache,
119            page_size,
120            observer,
121        }
122    }
123
124    /// Invalidates completed pages. Concurrent loads are not fenced.
125    pub fn invalidate_if(
126        &self,
127        predicate: impl Fn(&K) -> bool + Send + Sync + 'static,
128    ) -> io::Result<()> {
129        self.cache
130            .invalidate_if(move |(file, _), _| predicate(file))
131    }
132
133    /// Looks up a completed page without updating business lookup counters.
134    pub async fn contains(&self, file: &K, page_id: u64) -> bool {
135        self.cache.get(&(file.clone(), page_id)).await.is_some()
136    }
137
138    /// Recovers immutable file size from a requested page already in memory.
139    pub async fn known_file_size(&self, file: &K, ranges: &[Range<u64>]) -> Option<u64> {
140        let layout = PageLayout::new(NonZeroU64::new(self.page_size)?, u64::MAX);
141        for range in ranges {
142            for id in layout.page_ids(range.clone()).ok()? {
143                if let Some(page) = self.cache.get(&(file.clone(), id)).await {
144                    return Some(page.file_size);
145                }
146            }
147        }
148        None
149    }
150
151    /// Applies pending cache admission and eviction work.
152    pub async fn run_pending_tasks(&self) {
153        self.cache.run_pending_tasks().await;
154    }
155
156    /// Fetches bytes in input order. The reader must address the same immutable
157    /// content as `file`. Each successful loader reads one complete missing page.
158    pub async fn fetch<R: RangeReader + ?Sized>(
159        &self,
160        file: K,
161        file_size: u64,
162        ranges: &[Range<u64>],
163        reader: &R,
164    ) -> Result<(Vec<Bytes>, PageFetchStats), Arc<io::Error>> {
165        if ranges.iter().any(|r| r.start > r.end || r.end > file_size) {
166            return Err(invalid_request());
167        }
168        let page_size = NonZeroU64::new(self.page_size).ok_or_else(invalid_request)?;
169        let layout = PageLayout::new(page_size, file_size);
170        let mut stats = PageFetchStats::default();
171        let mut ids = BTreeSet::new();
172        for range in ranges {
173            stats.requested_bytes = stats
174                .requested_bytes
175                .checked_add(range.end - range.start)
176                .ok_or_else(invalid_request)?;
177            ids.extend(layout.page_ids(range.clone()).map_err(Arc::new)?);
178        }
179        stats.unique_requested_bytes = unique_requested_bytes(ranges);
180        let mut pages = BTreeMap::new();
181        let mut missing = Vec::new();
182        for id in ids {
183            let range = layout.page_range(id).ok_or_else(invalid_request)?;
184            stats.aligned_bytes += range.end - range.start;
185            if let Some(page) = self.cache.get(&(file.clone(), id)).await {
186                check_file_size(&page, file_size)?;
187                pages.insert(id, page.bytes.clone());
188            } else {
189                missing.push(id);
190            }
191        }
192        for range in ranges {
193            for id in layout.page_ids(range.clone()).map_err(Arc::new)? {
194                if pages.contains_key(&id) {
195                    let slice = layout
196                        .request_slice(id, range.clone())
197                        .map_err(Arc::new)?
198                        .ok_or_else(invalid_request)?;
199                    stats.cached_bytes += slice.len() as u64;
200                    stats.cached_fragments += 1;
201                }
202            }
203        }
204        stats.cache_hit = pages.len();
205        stats.cache_miss = missing.len();
206        (self.observer.events)(PageEvent::Lookup {
207            hits: stats.cache_hit,
208            misses: stats.cache_miss,
209        });
210        if !missing.is_empty() {
211            let loads = |requests: batch::BatchSender<_, _>| {
212                missing.into_iter().map(move |id| {
213                    self.load_page((file.clone(), id), layout, file_size, requests.clone())
214                })
215            };
216            batch::load(
217                loads,
218                |ranges, replies| async move {
219                    let result = reader.read_vec(&ranges).await.and_then(|bytes| {
220                        if bytes.len() == ranges.len() {
221                            Ok(bytes)
222                        } else {
223                            Err(io::Error::new(
224                                io::ErrorKind::InvalidData,
225                                "Invalid page response count",
226                            ))
227                        }
228                    });
229                    match result {
230                        Ok(bytes) => {
231                            for (reply, bytes) in replies.into_iter().zip(bytes) {
232                                let _ = reply.send(Ok(bytes));
233                            }
234                        }
235                        Err(error) => {
236                            let error = Arc::new(error);
237                            for reply in replies {
238                                let _ = reply.send(Err(error.clone()));
239                            }
240                        }
241                    }
242                },
243                |(id, bytes)| {
244                    pages.insert(id, bytes);
245                },
246            )
247            .await?;
248        }
249        let mut output = Vec::with_capacity(ranges.len());
250        for range in ranges {
251            if range.is_empty() {
252                output.push(Bytes::new());
253                continue;
254            }
255            let ids = layout.page_ids(range.clone()).map_err(Arc::new)?;
256            if ids.end - ids.start == 1 {
257                let slice = layout
258                    .request_slice(ids.start, range.clone())
259                    .map_err(Arc::new)?
260                    .ok_or_else(invalid_request)?;
261                let page = pages.get(&ids.start).ok_or_else(invalid_request)?;
262                if slice.end > page.len() {
263                    return Err(invalid_request());
264                }
265                output.push(page.slice(slice));
266                continue;
267            }
268            let len = usize::try_from(range.end - range.start).map_err(|_| invalid_request())?;
269            let mut assembled = BytesMut::with_capacity(len);
270            for id in ids {
271                let slice = layout
272                    .request_slice(id, range.clone())
273                    .map_err(Arc::new)?
274                    .ok_or_else(invalid_request)?;
275                let page = pages.get(&id).ok_or_else(invalid_request)?;
276                if slice.end > page.len() {
277                    return Err(invalid_request());
278                }
279                assembled.extend_from_slice(&page[slice]);
280            }
281            if assembled.len() != len {
282                return Err(invalid_request());
283            }
284            output.push(assembled.freeze());
285        }
286        Ok((output, stats))
287    }
288
289    async fn load_page(
290        &self,
291        key: (K, u64),
292        layout: PageLayout,
293        file_size: u64,
294        requests: batch::BatchSender<Range<u64>, Result<Bytes, Arc<io::Error>>>,
295    ) -> Result<(u64, Bytes), Arc<io::Error>> {
296        let range = layout.page_range(key.1).ok_or_else(invalid_request)?;
297        let page = self
298            .cache
299            .try_get_with(&key, async {
300                let bytes = requests
301                    .request(range.clone())
302                    .await
303                    .ok_or_else(|| io::Error::other("Page read batch cancelled"))?
304                    .map_err(|error: Arc<io::Error>| io::Error::new(error.kind(), error))?;
305                if bytes.len() as u64 != range.end - range.start {
306                    return Err(io::Error::new(
307                        io::ErrorKind::UnexpectedEof,
308                        "Invalid page response length",
309                    ));
310                }
311                // Detach readers' shared backing buffers from cache accounting.
312                Ok(self.create_cached_page(file_size, Bytes::copy_from_slice(&bytes)))
313            })
314            .await?;
315        check_file_size(&page, file_size)?;
316        Ok((key.1, page.bytes.clone()))
317    }
318
319    fn create_cached_page(&self, file_size: u64, bytes: Bytes) -> Arc<CachedPage> {
320        (self.observer.events)(PageEvent::Loaded {
321            bytes: bytes.len() as u64,
322        });
323        Arc::new(CachedPage { file_size, bytes })
324    }
325}
326
327struct CachedPage {
328    file_size: u64,
329    bytes: Bytes,
330}
331
332fn invalid_request() -> Arc<io::Error> {
333    Arc::new(io::Error::new(
334        io::ErrorKind::InvalidInput,
335        "Invalid cached page range",
336    ))
337}
338
339fn check_file_size(page: &CachedPage, expected: u64) -> Result<(), Arc<io::Error>> {
340    if page.file_size != expected {
341        return Err(Arc::new(io::Error::new(
342            io::ErrorKind::InvalidInput,
343            "Cached content identity used with inconsistent file sizes",
344        )));
345    }
346    Ok(())
347}
348
349/// Counts the union of request ranges already validated by fetch.
350fn unique_requested_bytes(ranges: &[Range<u64>]) -> u64 {
351    let mut ranges = ranges.to_vec();
352    ranges.sort_unstable_by_key(|range| range.start);
353    let mut end = 0;
354    let mut bytes = 0;
355    for range in ranges {
356        bytes += range.end.saturating_sub(range.start.max(end));
357        end = end.max(range.end);
358    }
359    bytes
360}