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, LoadPool, 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    /// Bytes physically read by this request for missing pages.
58    pub loaded_bytes: u64,
59    pub cache_hit: usize,
60    pub cache_miss: usize,
61    /// Requested intersections already cached; overlapping requests count repeatedly.
62    pub cached_bytes: u64,
63    pub cached_fragments: usize,
64    /// Original request lengths, including duplicates and overlaps.
65    pub requested_bytes: u64,
66    /// Sum of unique logical page lengths, clipped at EOF, including cache hits.
67    pub aligned_bytes: u64,
68    /// Union of original request byte ranges, excluding overlaps.
69    pub unique_requested_bytes: u64,
70}
71
72/// Caches fixed-size byte pages of immutable content identified by `K`.
73/// File identity must include any version needed to distinguish different contents.
74/// Missing pages elected by this fetch are submitted through [`RangeReader::read_vec`].
75pub struct PagedCache<K> {
76    cache: Cache<(K, u64), Arc<CachedPage>>,
77    page_size: u64,
78    observer: PageCacheObserver,
79    _capacity_registration: CacheSizeRegistration,
80}
81
82impl<K: Hash + Eq + Clone + Send + Sync + 'static> PagedCache<K> {
83    /// Creates an independent cache budget. Zero page size is rejected by fetch.
84    pub fn new(
85        name: &str,
86        capacity: u64,
87        page_size: u64,
88        weigher: impl Fn(&(K, u64), &Bytes) -> u32 + Send + Sync + 'static,
89        observer: PageCacheObserver,
90    ) -> Self {
91        Self::new_with_ttl(name, capacity, page_size, weigher, observer, None)
92    }
93
94    /// Creates a page cache with optional expiration measured from insertion.
95    pub fn new_with_ttl(
96        name: &str,
97        capacity: u64,
98        page_size: u64,
99        weigher: impl Fn(&(K, u64), &Bytes) -> u32 + Send + Sync + 'static,
100        observer: PageCacheObserver,
101        ttl: Option<Duration>,
102    ) -> Self {
103        let events = observer.events.clone();
104        let mut cache = Cache::new_with_ttl(
105            name,
106            capacity,
107            move |key, value: &Arc<CachedPage>| weigher(key, &value.bytes),
108            move |_, _, cause| {
109                events(PageEvent::Evicted { cause });
110            },
111            ttl,
112        )
113        .with_size_metric(observer.bytes.clone());
114        if let Some(metrics) = &observer.loads {
115            cache = cache.with_metrics(metrics.clone());
116        }
117        let capacity_registration = observer.capacity.register(move || capacity);
118        Self {
119            _capacity_registration: capacity_registration,
120            cache,
121            page_size,
122            observer,
123        }
124    }
125
126    /// Invalidates completed pages. Concurrent loads are not fenced.
127    pub fn invalidate_if(
128        &self,
129        predicate: impl Fn(&K) -> bool + Send + Sync + 'static,
130    ) -> io::Result<()> {
131        self.cache
132            .invalidate_if(move |(file, _), _| predicate(file))
133    }
134
135    /// Looks up a completed page without updating business lookup counters.
136    pub async fn contains(&self, file: &K, page_id: u64) -> bool {
137        self.cache.get(&(file.clone(), page_id)).await.is_some()
138    }
139
140    /// Recovers immutable file size from a requested page already in memory.
141    pub async fn known_file_size(&self, file: &K, ranges: &[Range<u64>]) -> Option<u64> {
142        let layout = PageLayout::new(NonZeroU64::new(self.page_size)?, u64::MAX);
143        for range in ranges {
144            for id in layout.page_ids(range.clone()).ok()? {
145                if let Some(page) = self.cache.get(&(file.clone(), id)).await {
146                    return Some(page.file_size);
147                }
148            }
149        }
150        None
151    }
152
153    /// Applies pending cache admission and eviction work.
154    pub async fn run_pending_tasks(&self) {
155        self.cache.run_pending_tasks().await;
156    }
157
158    /// Fetches bytes in input order. The reader must address the same immutable
159    /// content as `file`. Each successful loader reads one complete missing page.
160    pub async fn fetch<R: RangeReader + ?Sized>(
161        &self,
162        file: K,
163        file_size: u64,
164        ranges: &[Range<u64>],
165        reader: &R,
166    ) -> Result<(Vec<Bytes>, PageFetchStats), Arc<io::Error>> {
167        self.fetch_inner(&file, file_size, ranges, |layout, missing| {
168            self.load_missing(&file, layout, file_size, missing, reader)
169        })
170        .await
171    }
172
173    /// Looks up resident pages inline and drives all missing pages as one
174    /// worker job, preserving vector reads and sharing concurrent page loads.
175    pub async fn fetch_in_pool<R: RangeReader + 'static>(
176        self: &Arc<Self>,
177        pool: &LoadPool,
178        file: K,
179        file_size: u64,
180        ranges: &[Range<u64>],
181        reader: Arc<R>,
182    ) -> Result<(Vec<Bytes>, PageFetchStats), Arc<io::Error>> {
183        let file_key = &file;
184        self.fetch_inner(
185            file_key,
186            file_size,
187            ranges,
188            move |layout, missing| async move {
189                let cache = self.clone();
190                let key = file_key.clone();
191                let worker_reader = reader.clone();
192                let ids = missing.clone();
193                if let Some(result) = pool
194                    .run(async move {
195                        cache
196                            .load_missing(&key, layout, file_size, ids, &*worker_reader)
197                            .await
198                    })
199                    .await
200                {
201                    return result;
202                }
203                // No worker can deliver this result. Read directly, without taking
204                // a Moka initializer on the query stream.
205                let spans = missing
206                    .iter()
207                    .map(|id| layout.page_range(*id).ok_or_else(invalid_request))
208                    .collect::<Result<Vec<_>, _>>()?;
209                let buffers = reader.read_vec(&spans).await?;
210                if buffers.len() != spans.len()
211                    || buffers
212                        .iter()
213                        .zip(&spans)
214                        .any(|(buf, r)| buf.len() as u64 != r.end - r.start)
215                {
216                    return Err(invalid_request());
217                }
218                let bytes = buffers.iter().map(|buf| buf.len() as u64).sum();
219                Ok((missing.into_iter().zip(buffers).collect(), bytes))
220            },
221        )
222        .await
223    }
224
225    async fn fetch_inner<F: Future<Output = Result<(Vec<(u64, Bytes)>, u64), Arc<io::Error>>>>(
226        &self,
227        file: &K,
228        file_size: u64,
229        ranges: &[Range<u64>],
230        load: impl FnOnce(PageLayout, Vec<u64>) -> F,
231    ) -> Result<(Vec<Bytes>, PageFetchStats), Arc<io::Error>> {
232        if ranges.iter().any(|r| r.start > r.end || r.end > file_size) {
233            return Err(invalid_request());
234        }
235        let page_size = NonZeroU64::new(self.page_size).ok_or_else(invalid_request)?;
236        let layout = PageLayout::new(page_size, file_size);
237        let mut stats = PageFetchStats::default();
238        let mut ids = BTreeSet::new();
239        for range in ranges {
240            stats.requested_bytes = stats
241                .requested_bytes
242                .checked_add(range.end - range.start)
243                .ok_or_else(invalid_request)?;
244            ids.extend(layout.page_ids(range.clone()).map_err(Arc::new)?);
245        }
246        stats.unique_requested_bytes = unique_requested_bytes(ranges);
247        let mut pages = BTreeMap::new();
248        let mut missing = Vec::new();
249        for id in ids {
250            let range = layout.page_range(id).ok_or_else(invalid_request)?;
251            stats.aligned_bytes += range.end - range.start;
252            if let Some(page) = self.cache.get(&(file.clone(), id)).await {
253                check_file_size(&page, file_size)?;
254                pages.insert(id, page.bytes.clone());
255            } else {
256                missing.push(id);
257            }
258        }
259        for range in ranges {
260            for id in layout.page_ids(range.clone()).map_err(Arc::new)? {
261                if pages.contains_key(&id) {
262                    let slice = layout
263                        .request_slice(id, range.clone())
264                        .map_err(Arc::new)?
265                        .ok_or_else(invalid_request)?;
266                    stats.cached_bytes += slice.len() as u64;
267                    stats.cached_fragments += 1;
268                }
269            }
270        }
271        stats.cache_hit = pages.len();
272        stats.cache_miss = missing.len();
273        (self.observer.events)(PageEvent::Lookup {
274            hits: stats.cache_hit,
275            misses: stats.cache_miss,
276        });
277        if !missing.is_empty() {
278            let (loaded, bytes) = load(layout, missing).await?;
279            pages.extend(loaded);
280            stats.loaded_bytes = bytes;
281        }
282        let mut output = Vec::with_capacity(ranges.len());
283        for range in ranges {
284            if range.is_empty() {
285                output.push(Bytes::new());
286                continue;
287            }
288            let ids = layout.page_ids(range.clone()).map_err(Arc::new)?;
289            if ids.end - ids.start == 1 {
290                let slice = layout
291                    .request_slice(ids.start, range.clone())
292                    .map_err(Arc::new)?
293                    .ok_or_else(invalid_request)?;
294                let page = pages.get(&ids.start).ok_or_else(invalid_request)?;
295                if slice.end > page.len() {
296                    return Err(invalid_request());
297                }
298                output.push(page.slice(slice));
299                continue;
300            }
301            let len = usize::try_from(range.end - range.start).map_err(|_| invalid_request())?;
302            let mut assembled = BytesMut::with_capacity(len);
303            for id in ids {
304                let slice = layout
305                    .request_slice(id, range.clone())
306                    .map_err(Arc::new)?
307                    .ok_or_else(invalid_request)?;
308                let page = pages.get(&id).ok_or_else(invalid_request)?;
309                if slice.end > page.len() {
310                    return Err(invalid_request());
311                }
312                assembled.extend_from_slice(&page[slice]);
313            }
314            if assembled.len() != len {
315                return Err(invalid_request());
316            }
317            output.push(assembled.freeze());
318        }
319        Ok((output, stats))
320    }
321
322    async fn load_missing<R: RangeReader + ?Sized>(
323        &self,
324        file: &K,
325        layout: PageLayout,
326        file_size: u64,
327        missing: Vec<u64>,
328        reader: &R,
329    ) -> Result<(Vec<(u64, Bytes)>, u64), Arc<io::Error>> {
330        let mut pages = Vec::with_capacity(missing.len());
331        let mut loaded_bytes = 0;
332        let loads = |requests: batch::BatchSender<_, _>| {
333            missing.into_iter().map(move |id| {
334                self.load_page((file.clone(), id), layout, file_size, requests.clone())
335            })
336        };
337        batch::load(
338            loads,
339            |ranges, replies| {
340                loaded_bytes += ranges.iter().map(|r| r.end - r.start).sum::<u64>();
341                async move {
342                    let result = reader.read_vec(&ranges).await.and_then(|bytes| {
343                        if bytes.len() == ranges.len() {
344                            Ok(bytes)
345                        } else {
346                            Err(io::Error::new(
347                                io::ErrorKind::InvalidData,
348                                "Invalid page response count",
349                            ))
350                        }
351                    });
352                    match result {
353                        Ok(bytes) => {
354                            for (reply, bytes) in replies.into_iter().zip(bytes) {
355                                let _ = reply.send(Ok(bytes));
356                            }
357                        }
358                        Err(error) => {
359                            let error = Arc::new(error);
360                            for reply in replies {
361                                let _ = reply.send(Err(error.clone()));
362                            }
363                        }
364                    }
365                }
366            },
367            |page| pages.push(page),
368        )
369        .await?;
370        Ok((pages, loaded_bytes))
371    }
372
373    async fn load_page(
374        &self,
375        key: (K, u64),
376        layout: PageLayout,
377        file_size: u64,
378        requests: batch::BatchSender<Range<u64>, Result<Bytes, Arc<io::Error>>>,
379    ) -> Result<(u64, Bytes), Arc<io::Error>> {
380        let range = layout.page_range(key.1).ok_or_else(invalid_request)?;
381        let page = self
382            .cache
383            .try_get_with(&key, async {
384                let bytes = requests
385                    .request(range.clone())
386                    .await
387                    .ok_or_else(|| io::Error::other("Page read batch cancelled"))?
388                    .map_err(|error: Arc<io::Error>| io::Error::new(error.kind(), error))?;
389                if bytes.len() as u64 != range.end - range.start {
390                    return Err(io::Error::new(
391                        io::ErrorKind::UnexpectedEof,
392                        "Invalid page response length",
393                    ));
394                }
395                // Detach readers' shared backing buffers from cache accounting.
396                Ok(self.create_cached_page(file_size, Bytes::copy_from_slice(&bytes)))
397            })
398            .await?;
399        check_file_size(&page, file_size)?;
400        Ok((key.1, page.bytes.clone()))
401    }
402
403    fn create_cached_page(&self, file_size: u64, bytes: Bytes) -> Arc<CachedPage> {
404        (self.observer.events)(PageEvent::Loaded {
405            bytes: bytes.len() as u64,
406        });
407        Arc::new(CachedPage { file_size, bytes })
408    }
409}
410
411struct CachedPage {
412    file_size: u64,
413    bytes: Bytes,
414}
415
416fn invalid_request() -> Arc<io::Error> {
417    Arc::new(io::Error::new(
418        io::ErrorKind::InvalidInput,
419        "Invalid cached page range",
420    ))
421}
422
423fn check_file_size(page: &CachedPage, expected: u64) -> Result<(), Arc<io::Error>> {
424    if page.file_size != expected {
425        return Err(Arc::new(io::Error::new(
426            io::ErrorKind::InvalidInput,
427            "Cached content identity used with inconsistent file sizes",
428        )));
429    }
430    Ok(())
431}
432
433/// Counts the union of request ranges already validated by fetch.
434pub fn unique_requested_bytes(ranges: &[Range<u64>]) -> u64 {
435    let mut ranges = ranges.to_vec();
436    ranges.sort_unstable_by_key(|range| range.start);
437    let mut end = 0;
438    let mut bytes = 0;
439    for range in ranges {
440        bytes += range.end.saturating_sub(range.start.max(end));
441        end = end.max(range.end);
442    }
443    bytes
444}