Skip to main content

mito2/sst/index/
store.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
15use std::io;
16use std::ops::Range;
17use std::pin::Pin;
18use std::task::{Context, Poll};
19
20use async_trait::async_trait;
21use bytes::{BufMut, Bytes};
22use common_base::range_read::{Metadata, RangeReader, SizeAwareRangeReader};
23#[cfg(feature = "enterprise")]
24use futures::future::Either;
25use futures::{AsyncRead, AsyncSeek, AsyncWrite};
26use object_store::{FuturesAsyncWriter, ObjectStore};
27use pin_project::pin_project;
28use prometheus::IntCounter;
29use snafu::ResultExt;
30
31use crate::error::{OpenDalSnafu, Result};
32
33/// A wrapper around [`ObjectStore`] that adds instrumentation for monitoring
34/// metrics such as bytes read, bytes written, and the number of seek operations.
35///
36/// TODO: Consider refactor InstrumentedStore to use async in trait instead of AsyncRead.
37#[derive(Clone)]
38pub(crate) struct InstrumentedStore {
39    /// The underlying object store.
40    object_store: ObjectStore,
41    write_buffer: IndexWriteBuffer,
42}
43
44/// Upload policy of the Puffin index writer opened by [`InstrumentedStore::writer`].
45///
46/// Each variant selects a different object-store writer, not only a buffer size.
47#[derive(Clone, Copy, Default)]
48pub(crate) enum IndexWriteBuffer {
49    /// Opens the store's default writer: no explicit chunk size or concurrency,
50    /// so the backend's own limits apply.
51    #[default]
52    Default,
53    /// Requests exact parts of the given size, clamped to the backend's limits,
54    /// with the store's default concurrency.
55    Chunk(usize),
56    /// Requests parts sized by the given limits with one upload at a time, and
57    /// buffers writes through [`crate::sst::upload::buffered::writer`], which
58    /// assembles whole parts and rejects writes beyond the object size limit.
59    #[cfg(feature = "enterprise")]
60    Bounded(crate::sst::upload::buffered::UploadLimits),
61}
62
63impl From<Option<usize>> for IndexWriteBuffer {
64    fn from(bytes: Option<usize>) -> Self {
65        bytes
66            .filter(|&size| size > 0)
67            .map_or(Self::Default, Self::Chunk)
68    }
69}
70
71impl InstrumentedStore {
72    /// Create a new `InstrumentedStore`.
73    pub fn new(object_store: ObjectStore) -> Self {
74        Self {
75            object_store,
76            write_buffer: IndexWriteBuffer::Default,
77        }
78    }
79
80    pub fn store(&self) -> &ObjectStore {
81        &self.object_store
82    }
83
84    /// Set the size of the write buffer.
85    pub fn with_write_buffer_size(self, write_buffer_size: Option<usize>) -> Self {
86        self.with_write_buffer(write_buffer_size.into())
87    }
88
89    pub(crate) fn with_write_buffer(mut self, write_buffer: IndexWriteBuffer) -> Self {
90        self.write_buffer = write_buffer;
91        self
92    }
93
94    /// Returns an [`InstrumentedRangeReader`] for the given path.
95    /// Metrics like the number of bytes read are recorded using the provided `IntCounter`.
96    pub async fn range_reader<'a>(
97        &self,
98        path: &str,
99        read_byte_count: &'a IntCounter,
100        read_count: &'a IntCounter,
101    ) -> Result<InstrumentedRangeReader<'a>> {
102        Ok(InstrumentedRangeReader {
103            store: self.object_store.clone(),
104            path: path.to_string(),
105            read_byte_count,
106            read_count,
107            file_size_hint: None,
108        })
109    }
110
111    /// Returns an [`InstrumentedAsyncRead`] for the given path.
112    /// Metrics like the number of bytes read, read and seek operations
113    /// are recorded using the provided `IntCounter`s.
114    pub async fn reader<'a>(
115        &self,
116        path: &str,
117        read_byte_count: &'a IntCounter,
118        read_count: &'a IntCounter,
119        seek_count: &'a IntCounter,
120    ) -> Result<InstrumentedAsyncRead<'a, object_store::FuturesAsyncReader>> {
121        let meta = self.object_store.stat(path).await.context(OpenDalSnafu)?;
122        let reader = self
123            .object_store
124            .reader(path)
125            .await
126            .context(OpenDalSnafu)?
127            .into_futures_async_read(0..meta.content_length())
128            .await
129            .context(OpenDalSnafu)?;
130        Ok(InstrumentedAsyncRead::new(
131            reader,
132            read_byte_count,
133            read_count,
134            seek_count,
135        ))
136    }
137
138    /// Returns an [`InstrumentedAsyncWrite`] for the given path.
139    /// Metrics like the number of bytes written, write and flush operations
140    /// are recorded using the provided `IntCounter`s.
141    pub async fn writer<'a>(
142        &self,
143        path: &str,
144        write_byte_count: &'a IntCounter,
145        write_count: &'a IntCounter,
146        flush_count: &'a IntCounter,
147    ) -> Result<InstrumentedAsyncWrite<'a, IndexObjectWriter>> {
148        let writer = match self.write_buffer {
149            IndexWriteBuffer::Default => self.object_store.writer(path).await,
150            IndexWriteBuffer::Chunk(bytes) => {
151                self.object_store.writer_with(path).chunk(bytes).await
152            }
153            #[cfg(feature = "enterprise")]
154            IndexWriteBuffer::Bounded(limits) => {
155                self.object_store
156                    .writer_with(path)
157                    .chunk(limits.chunk_bytes)
158                    .concurrent(1)
159                    .await
160            }
161        }
162        .context(OpenDalSnafu)?;
163        #[cfg(feature = "enterprise")]
164        let writer: IndexObjectWriter = match self.write_buffer {
165            IndexWriteBuffer::Bounded(limits) => Either::Right(Box::new(
166                crate::sst::upload::buffered::writer(writer, limits),
167            )),
168            _ => Either::Left(writer.into_futures_async_write()),
169        };
170        #[cfg(not(feature = "enterprise"))]
171        let writer = writer.into_futures_async_write();
172        Ok(InstrumentedAsyncWrite::new(
173            writer,
174            write_byte_count,
175            write_count,
176            flush_count,
177        ))
178    }
179
180    /// Proxies to [`ObjectStore::list`].
181    pub async fn list(&self, path: &str) -> Result<Vec<object_store::Entry>> {
182        let list = self.object_store.list(path).await.context(OpenDalSnafu)?;
183        Ok(list)
184    }
185
186    /// Recursively deletes all objects under the given path.
187    pub async fn remove_all(&self, path: &str) -> Result<()> {
188        self.object_store
189            .delete_with(path)
190            .recursive(true)
191            .await
192            .context(OpenDalSnafu)
193    }
194}
195
196/// A wrapper around [`AsyncRead`] that adds instrumentation for monitoring
197#[pin_project]
198pub struct InstrumentedAsyncRead<'a, R> {
199    #[pin]
200    inner: R,
201    read_byte_count: CounterGuard<'a>,
202    read_count: CounterGuard<'a>,
203    seek_count: CounterGuard<'a>,
204}
205
206impl<'a, R> InstrumentedAsyncRead<'a, R> {
207    /// Create a new `InstrumentedAsyncRead`.
208    fn new(
209        inner: R,
210        read_byte_count: &'a IntCounter,
211        read_count: &'a IntCounter,
212        seek_count: &'a IntCounter,
213    ) -> Self {
214        Self {
215            inner,
216            read_byte_count: CounterGuard::new(read_byte_count),
217            read_count: CounterGuard::new(read_count),
218            seek_count: CounterGuard::new(seek_count),
219        }
220    }
221}
222
223impl<R: AsyncRead + Unpin + Send> AsyncRead for InstrumentedAsyncRead<'_, R> {
224    fn poll_read(
225        mut self: Pin<&mut Self>,
226        cx: &mut Context<'_>,
227        buf: &mut [u8],
228    ) -> Poll<io::Result<usize>> {
229        let poll = self.as_mut().project().inner.poll_read(cx, buf);
230        if let Poll::Ready(Ok(n)) = &poll {
231            self.read_count.inc_by(1);
232            self.read_byte_count.inc_by(*n);
233        }
234        poll
235    }
236}
237
238impl<R: AsyncSeek + Unpin + Send> AsyncSeek for InstrumentedAsyncRead<'_, R> {
239    fn poll_seek(
240        mut self: Pin<&mut Self>,
241        cx: &mut Context<'_>,
242        pos: io::SeekFrom,
243    ) -> Poll<io::Result<u64>> {
244        let poll = self.as_mut().project().inner.poll_seek(cx, pos);
245        if let Poll::Ready(Ok(_)) = &poll {
246            self.seek_count.inc_by(1);
247        }
248        poll
249    }
250}
251
252/// The [`AsyncWrite`] sink of a Puffin index file.
253///
254/// The bounded side is boxed because [`crate::sst::upload::buffered::writer`]
255/// returns an opaque `impl AsyncWrite`, which keeps that private adapter out of
256/// this alias; the plain side stays concrete.
257#[cfg(feature = "enterprise")]
258pub type IndexObjectWriter = Either<FuturesAsyncWriter, Box<dyn AsyncWrite + Send + Sync + Unpin>>;
259/// The [`AsyncWrite`] sink of a Puffin index file.
260#[cfg(not(feature = "enterprise"))]
261pub type IndexObjectWriter = FuturesAsyncWriter;
262
263/// A wrapper around [`AsyncWrite`] that adds instrumentation for monitoring
264#[pin_project]
265pub struct InstrumentedAsyncWrite<'a, W> {
266    #[pin]
267    inner: W,
268    write_byte_count: CounterGuard<'a>,
269    write_count: CounterGuard<'a>,
270    flush_count: CounterGuard<'a>,
271}
272
273impl<'a, W> InstrumentedAsyncWrite<'a, W> {
274    /// Create a new `InstrumentedAsyncWrite`.
275    fn new(
276        inner: W,
277        write_byte_count: &'a IntCounter,
278        write_count: &'a IntCounter,
279        flush_count: &'a IntCounter,
280    ) -> Self {
281        Self {
282            inner,
283            write_byte_count: CounterGuard::new(write_byte_count),
284            write_count: CounterGuard::new(write_count),
285            flush_count: CounterGuard::new(flush_count),
286        }
287    }
288}
289
290impl<W: AsyncWrite + Unpin + Send> AsyncWrite for InstrumentedAsyncWrite<'_, W> {
291    fn poll_write(
292        mut self: Pin<&mut Self>,
293        cx: &mut Context<'_>,
294        buf: &[u8],
295    ) -> Poll<io::Result<usize>> {
296        let poll = self.as_mut().project().inner.poll_write(cx, buf);
297        if let Poll::Ready(Ok(n)) = &poll {
298            self.write_count.inc_by(1);
299            self.write_byte_count.inc_by(*n);
300        }
301        poll
302    }
303
304    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
305        let poll = self.as_mut().project().inner.poll_flush(cx);
306        if let Poll::Ready(Ok(())) = &poll {
307            self.flush_count.inc_by(1);
308        }
309        poll
310    }
311
312    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
313        self.project().inner.poll_close(cx)
314    }
315}
316
317/// Ranges fetched in parallel by one `read_vec`, as for parquet reads.
318const FETCH_CONCURRENCY: usize = 8;
319
320/// Implements `RangeReader` for `ObjectStore` and record metrics.
321pub struct InstrumentedRangeReader<'a> {
322    store: ObjectStore,
323    path: String,
324    read_byte_count: &'a IntCounter,
325    read_count: &'a IntCounter,
326    file_size_hint: Option<u64>,
327}
328
329impl SizeAwareRangeReader for InstrumentedRangeReader<'_> {
330    fn with_file_size_hint(&mut self, file_size_hint: u64) {
331        self.file_size_hint = Some(file_size_hint);
332    }
333}
334
335#[async_trait]
336impl RangeReader for InstrumentedRangeReader<'_> {
337    async fn metadata(&self) -> io::Result<Metadata> {
338        match self.file_size_hint {
339            Some(file_size_hint) => Ok(Metadata {
340                content_length: file_size_hint,
341            }),
342            None => {
343                let stat = self.store.stat(&self.path).await?;
344                Ok(Metadata {
345                    content_length: stat.content_length(),
346                })
347            }
348        }
349    }
350
351    async fn read(&self, range: Range<u64>) -> io::Result<Bytes> {
352        let buf = self.store.reader(&self.path).await?.read(range).await?;
353        self.read_byte_count.inc_by(buf.len() as _);
354        self.read_count.inc_by(1);
355        Ok(buf.to_bytes())
356    }
357
358    async fn read_into(&self, range: Range<u64>, buf: &mut (impl BufMut + Send)) -> io::Result<()> {
359        let reader = self.store.reader(&self.path).await?;
360        let size = reader.read_into(buf, range).await?;
361        self.read_byte_count.inc_by(size as _);
362        self.read_count.inc_by(1);
363        Ok(())
364    }
365
366    async fn read_vec(&self, ranges: &[Range<u64>]) -> io::Result<Vec<Bytes>> {
367        // OpenDAL merges ranges less than 1 MiB apart by default without bounding the merged
368        // length, so sparse page reads could fetch most of the file. Only merge adjacent
369        // ranges, and fetch the rest in parallel like parquet reads do.
370        // TODO: decide whether to merge across small gaps based on object store latency,
371        // bytes read and query latency.
372        let bufs = self
373            .store
374            .reader_with(&self.path)
375            .gap(0)
376            .concurrent(FETCH_CONCURRENCY)
377            .await?
378            .fetch(ranges.to_owned())
379            .await?;
380        let total_size: usize = bufs.iter().map(|buf| buf.len()).sum();
381        self.read_byte_count.inc_by(total_size as _);
382        self.read_count.inc_by(1);
383        Ok(bufs.into_iter().map(|buf| buf.to_bytes()).collect())
384    }
385}
386
387/// A guard that increments a counter when dropped.
388struct CounterGuard<'a> {
389    count: usize,
390    counter: &'a IntCounter,
391}
392
393impl<'a> CounterGuard<'a> {
394    /// Create a new `CounterGuard`.
395    fn new(counter: &'a IntCounter) -> Self {
396        Self { count: 0, counter }
397    }
398
399    /// Increment the counter by `n`.
400    fn inc_by(&mut self, n: usize) {
401        self.count += n;
402    }
403}
404
405impl Drop for CounterGuard<'_> {
406    fn drop(&mut self) {
407        if self.count > 0 {
408            self.counter.inc_by(self.count as _);
409        }
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use futures::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
416    use object_store::services::Memory;
417
418    use super::*;
419
420    #[tokio::test]
421    async fn test_instrumented_store_read_write() {
422        let instrumented_store =
423            InstrumentedStore::new(ObjectStore::new(Memory::default()).unwrap());
424
425        let read_byte_count = IntCounter::new("read_byte_count", "read_byte_count").unwrap();
426        let read_count = IntCounter::new("read_count", "read_count").unwrap();
427        let seek_count = IntCounter::new("seek_count", "seek_count").unwrap();
428        let write_byte_count = IntCounter::new("write_byte_count", "write_byte_count").unwrap();
429        let write_count = IntCounter::new("write_count", "write_count").unwrap();
430        let flush_count = IntCounter::new("flush_count", "flush_count").unwrap();
431
432        let mut writer = instrumented_store
433            .writer("my_file", &write_byte_count, &write_count, &flush_count)
434            .await
435            .unwrap();
436        writer.write_all(b"hello").await.unwrap();
437        writer.flush().await.unwrap();
438        writer.close().await.unwrap();
439        drop(writer);
440
441        let mut reader = instrumented_store
442            .reader("my_file", &read_byte_count, &read_count, &seek_count)
443            .await
444            .unwrap();
445        let mut buf = vec![0; 5];
446        reader.read_exact(&mut buf).await.unwrap();
447        reader.seek(io::SeekFrom::Start(0)).await.unwrap();
448        reader.read_exact(&mut buf).await.unwrap();
449        drop(reader);
450
451        assert_eq!(read_byte_count.get(), 10);
452        assert_eq!(read_count.get(), 2);
453        assert_eq!(seek_count.get(), 1);
454        assert_eq!(write_byte_count.get(), 5);
455        assert_eq!(write_count.get(), 1);
456        assert_eq!(flush_count.get(), 1);
457    }
458}