puffin/puffin_manager.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
15pub mod cache;
16pub mod file_accessor;
17pub mod file_key;
18pub mod fs_puffin_manager;
19pub mod stager;
20
21#[cfg(test)]
22mod tests;
23
24use std::collections::HashMap;
25use std::path::PathBuf;
26use std::sync::Arc;
27
28use async_trait::async_trait;
29use common_base::range_read::RangeReader;
30use futures::AsyncRead;
31
32use crate::blob_metadata::{BlobMetadata, CompressionCodec};
33use crate::error::Result;
34use crate::file_metadata::FileMetadata;
35use crate::puffin_manager::file_key::PuffinFileKey;
36
37/// Metrics returned by `PuffinReader::dir` operations.
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39pub struct DirMetrics {
40 /// Whether this was a cache hit (true) or cache miss (false).
41 pub cache_hit: bool,
42 /// Size of the directory in bytes.
43 pub dir_size: u64,
44}
45
46/// The `PuffinManager` trait provides a unified interface for creating `PuffinReader` and `PuffinWriter`.
47#[async_trait]
48pub trait PuffinManager {
49 type Reader: PuffinReader;
50 type Writer: PuffinWriter;
51 type FileHandle: ToString + Clone + Send + Sync;
52
53 /// Returns a stable storage-scoped key without opening or reading the file.
54 fn file_key(&self, handle: &Self::FileHandle) -> PuffinFileKey<Self::FileHandle>;
55
56 /// Creates a `PuffinReader` for the specified `handle`.
57 async fn reader(&self, handle: &Self::FileHandle) -> Result<Self::Reader>;
58
59 /// Creates a `PuffinWriter` for the specified `handle`.
60 async fn writer(&self, handle: &Self::FileHandle) -> Result<Self::Writer>;
61}
62
63/// The `PuffinWriter` trait provides methods for writing blobs and directories to a Puffin file.
64#[async_trait]
65pub trait PuffinWriter {
66 /// Writes a blob associated with the specified `key` to the Puffin file.
67 /// Returns the number of bytes written.
68 async fn put_blob<R>(
69 &mut self,
70 key: &str,
71 raw_data: R,
72 options: PutOptions,
73 properties: HashMap<String, String>,
74 ) -> Result<u64>
75 where
76 R: AsyncRead + Send;
77
78 /// Writes a directory associated with the specified `key` to the Puffin file.
79 /// Returns the number of bytes written.
80 ///
81 /// The specified `dir` should be accessible from the filesystem.
82 async fn put_dir(
83 &mut self,
84 key: &str,
85 dir: PathBuf,
86 options: PutOptions,
87 properties: HashMap<String, String>,
88 ) -> Result<u64>;
89
90 /// Sets whether the footer should be LZ4 compressed.
91 fn set_footer_lz4_compressed(&mut self, lz4_compressed: bool);
92
93 /// Finalizes the Puffin file after writing.
94 async fn finish(self) -> Result<u64>;
95}
96
97/// Options available for `put_blob` and `put_dir` methods.
98#[derive(Debug, Clone, Default)]
99pub struct PutOptions {
100 /// The compression codec to use for blob data.
101 pub compression: Option<CompressionCodec>,
102}
103
104/// The `PuffinReader` trait provides methods for reading blobs and directories from a Puffin file.
105#[async_trait]
106pub trait PuffinReader {
107 type Blob: BlobGuard;
108 type Dir: DirGuard;
109
110 fn with_file_size_hint(self, file_size_hint: Option<u64>) -> Self;
111
112 /// Returns the metadata of the Puffin file.
113 async fn metadata(&self) -> Result<Arc<FileMetadata>>;
114
115 /// Returns metadata for a unique blob key without reading its payload.
116 ///
117 /// Missing keys return `None`; duplicate keys return an error. The length is
118 /// the stored byte length, before any decompression performed by [`Self::blob`].
119 async fn blob_metadata(&self, key: &str) -> Result<Option<BlobMetadata>> {
120 let metadata = self.metadata().await?;
121 let mut matches = metadata.blobs.iter().filter(|blob| blob.blob_type == key);
122 let first = matches.next();
123 if matches.next().is_some() {
124 return crate::error::AmbiguousBlobSnafu { blob: key }.fail();
125 }
126 Ok(first.cloned())
127 }
128
129 /// Reads a blob from the Puffin file.
130 ///
131 /// The returned `GuardWithMetadata` is used to access the blob data and its metadata.
132 /// Users should hold the `GuardWithMetadata` until they are done with the blob data.
133 async fn blob(&self, key: &str) -> Result<GuardWithMetadata<Self::Blob>>;
134
135 /// Reads a directory from the Puffin file.
136 ///
137 /// The returned tuple contains `GuardWithMetadata` and `DirMetrics`.
138 /// The `GuardWithMetadata` is used to access the directory data and its metadata.
139 /// Users should hold the `GuardWithMetadata` until they are done with the directory data.
140 async fn dir(&self, key: &str) -> Result<(GuardWithMetadata<Self::Dir>, DirMetrics)>;
141}
142
143/// `BlobGuard` is provided by the `PuffinReader` to access the blob data.
144/// Users should hold the `BlobGuard` until they are done with the blob data.
145#[async_trait]
146#[auto_impl::auto_impl(Arc)]
147pub trait BlobGuard {
148 type Reader: RangeReader;
149 async fn reader(&self) -> Result<Self::Reader>;
150}
151
152/// `DirGuard` is provided by the `PuffinReader` to access the directory in the filesystem.
153/// Users should hold the `DirGuard` until they are done with the directory.
154#[auto_impl::auto_impl(Arc)]
155pub trait DirGuard {
156 fn path(&self) -> &PathBuf;
157}
158
159/// `GuardWithMetadata` provides access to the blob or directory data and its metadata.
160pub struct GuardWithMetadata<G> {
161 guard: G,
162 metadata: BlobMetadata,
163}
164
165impl<G> GuardWithMetadata<G> {
166 /// Creates a new `GuardWithMetadata` instance.
167 pub fn new(guard: G, metadata: BlobMetadata) -> Self {
168 Self { guard, metadata }
169 }
170
171 /// Returns the metadata of the directory.
172 pub fn metadata(&self) -> &BlobMetadata {
173 &self.metadata
174 }
175}
176
177impl<G: BlobGuard> GuardWithMetadata<G> {
178 /// Returns the reader for the blob data.
179 pub async fn reader(&self) -> Result<G::Reader> {
180 self.guard.reader().await
181 }
182}
183
184impl<G: DirGuard> GuardWithMetadata<G> {
185 /// Returns the path of the directory.
186 pub fn path(&self) -> &PathBuf {
187 self.guard.path()
188 }
189}