Line data Source code
1 : //!
2 : //! Utilities for vectored reading of variable-sized "blobs".
3 : //!
4 : //! The "blob" api is an abstraction on top of the "block" api,
5 : //! with the main difference being that blobs do not have a fixed
6 : //! size (each blob is prefixed with 1 or 4 byte length field)
7 : //!
8 : //! The vectored apis provided in this module allow for planning
9 : //! and executing disk IO which covers multiple blobs.
10 : //!
11 : //! Reads are planned with [`VectoredReadPlanner`] which will coalesce
12 : //! adjacent blocks into a single disk IO request and exectuted by
13 : //! [`VectoredBlobReader`] which does all the required offset juggling
14 : //! and returns a buffer housing all the blobs and a list of offsets.
15 : //!
16 : //! Note that the vectored blob api does *not* go through the page cache.
17 :
18 : use std::collections::BTreeMap;
19 : use std::ops::Deref;
20 :
21 : use bytes::Bytes;
22 : use pageserver_api::key::Key;
23 : use tokio::io::AsyncWriteExt;
24 : use tokio_epoll_uring::BoundedBuf;
25 : use utils::lsn::Lsn;
26 : use utils::vec_map::VecMap;
27 :
28 : use crate::context::RequestContext;
29 : use crate::tenant::blob_io::{BYTE_UNCOMPRESSED, BYTE_ZSTD, Header};
30 : use crate::virtual_file::{self, IoBufferMut, VirtualFile};
31 :
32 : /// Metadata bundled with the start and end offset of a blob.
33 : #[derive(Copy, Clone, Debug)]
34 : pub struct BlobMeta {
35 : pub key: Key,
36 : pub lsn: Lsn,
37 : pub will_init: bool,
38 : }
39 :
40 : /// A view into the vectored blobs read buffer.
41 : #[derive(Clone, Debug)]
42 : pub(crate) enum BufView<'a> {
43 : Slice(&'a [u8]),
44 : Bytes(bytes::Bytes),
45 : }
46 :
47 : impl<'a> BufView<'a> {
48 : /// Creates a new slice-based view on the blob.
49 1614720 : pub fn new_slice(slice: &'a [u8]) -> Self {
50 1614720 : Self::Slice(slice)
51 1614720 : }
52 :
53 : /// Creates a new [`bytes::Bytes`]-based view on the blob.
54 12 : pub fn new_bytes(bytes: bytes::Bytes) -> Self {
55 12 : Self::Bytes(bytes)
56 12 : }
57 :
58 : /// Convert the view into `Bytes`.
59 : ///
60 : /// If using slice as the underlying storage, the copy will be an O(n) operation.
61 10261193 : pub fn into_bytes(self) -> Bytes {
62 10261193 : match self {
63 10261193 : BufView::Slice(slice) => Bytes::copy_from_slice(slice),
64 0 : BufView::Bytes(bytes) => bytes,
65 : }
66 10261193 : }
67 :
68 : /// Creates a sub-view of the blob based on the range.
69 23248877 : fn view(&self, range: std::ops::Range<usize>) -> Self {
70 23248877 : match self {
71 23248877 : BufView::Slice(slice) => BufView::Slice(&slice[range]),
72 0 : BufView::Bytes(bytes) => BufView::Bytes(bytes.slice(range)),
73 : }
74 23248877 : }
75 : }
76 :
77 : impl Deref for BufView<'_> {
78 : type Target = [u8];
79 :
80 13012752 : fn deref(&self) -> &Self::Target {
81 13012752 : match self {
82 13012740 : BufView::Slice(slice) => slice,
83 12 : BufView::Bytes(bytes) => bytes,
84 : }
85 13012752 : }
86 : }
87 :
88 : impl AsRef<[u8]> for BufView<'_> {
89 0 : fn as_ref(&self) -> &[u8] {
90 0 : match self {
91 0 : BufView::Slice(slice) => slice,
92 0 : BufView::Bytes(bytes) => bytes.as_ref(),
93 : }
94 0 : }
95 : }
96 :
97 : impl<'a> From<&'a [u8]> for BufView<'a> {
98 0 : fn from(value: &'a [u8]) -> Self {
99 0 : Self::new_slice(value)
100 0 : }
101 : }
102 :
103 : impl From<Bytes> for BufView<'_> {
104 0 : fn from(value: Bytes) -> Self {
105 0 : Self::new_bytes(value)
106 0 : }
107 : }
108 :
109 : /// Blob offsets into [`VectoredBlobsBuf::buf`]. The byte ranges is potentially compressed,
110 : /// subject to [`VectoredBlob::compression_bits`].
111 : pub struct VectoredBlob {
112 : /// Blob metadata.
113 : pub meta: BlobMeta,
114 : /// Header start offset.
115 : header_start: usize,
116 : /// Data start offset.
117 : data_start: usize,
118 : /// End offset.
119 : end: usize,
120 : /// Compression used on the data, extracted from the header.
121 : compression_bits: u8,
122 : }
123 :
124 : impl VectoredBlob {
125 : /// Reads a decompressed view of the blob.
126 23125901 : pub(crate) async fn read<'a>(&self, buf: &BufView<'a>) -> Result<BufView<'a>, std::io::Error> {
127 23125901 : let view = buf.view(self.data_start..self.end);
128 23125901 :
129 23125901 : match self.compression_bits {
130 23125889 : BYTE_UNCOMPRESSED => Ok(view),
131 : BYTE_ZSTD => {
132 12 : let mut decompressed_vec = Vec::new();
133 12 : let mut decoder =
134 12 : async_compression::tokio::write::ZstdDecoder::new(&mut decompressed_vec);
135 12 : decoder.write_all(&view).await?;
136 12 : decoder.flush().await?;
137 : // Zero-copy conversion from `Vec` to `Bytes`
138 12 : Ok(BufView::new_bytes(Bytes::from(decompressed_vec)))
139 : }
140 0 : bits => {
141 0 : let error = std::io::Error::new(
142 0 : std::io::ErrorKind::InvalidData,
143 0 : format!(
144 0 : "Failed to decompress blob for {}@{}, {}..{}: invalid compression byte {bits:x}",
145 0 : self.meta.key, self.meta.lsn, self.data_start, self.end
146 0 : ),
147 0 : );
148 0 : Err(error)
149 : }
150 : }
151 23125901 : }
152 :
153 : /// Returns the raw blob including header.
154 122976 : pub(crate) fn raw_with_header<'a>(&self, buf: &BufView<'a>) -> BufView<'a> {
155 122976 : buf.view(self.header_start..self.end)
156 122976 : }
157 : }
158 :
159 : impl std::fmt::Display for VectoredBlob {
160 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 0 : write!(
162 0 : f,
163 0 : "{}@{}, {}..{}",
164 0 : self.meta.key, self.meta.lsn, self.data_start, self.end
165 0 : )
166 0 : }
167 : }
168 :
169 : /// Return type of [`VectoredBlobReader::read_blobs`]
170 : pub struct VectoredBlobsBuf {
171 : /// Buffer for all blobs in this read
172 : pub buf: IoBufferMut,
173 : /// Offsets into the buffer and metadata for all blobs in this read
174 : pub blobs: Vec<VectoredBlob>,
175 : }
176 :
177 : /// Description of one disk read for multiple blobs.
178 : /// Used as the argument form [`VectoredBlobReader::read_blobs`]
179 : #[derive(Debug)]
180 : pub struct VectoredRead {
181 : pub start: u64,
182 : pub end: u64,
183 : /// Start offset and metadata for each blob in this read
184 : pub blobs_at: VecMap<u64, BlobMeta>,
185 : }
186 :
187 : impl VectoredRead {
188 7331037 : pub(crate) fn size(&self) -> usize {
189 7331037 : (self.end - self.start) as usize
190 7331037 : }
191 : }
192 :
193 : #[derive(Eq, PartialEq, Debug)]
194 : pub(crate) enum VectoredReadExtended {
195 : Yes,
196 : No,
197 : }
198 :
199 : /// A vectored read builder that tries to coalesce all reads that fits in a chunk.
200 : pub(crate) struct ChunkedVectoredReadBuilder {
201 : /// Start block number
202 : start_blk_no: usize,
203 : /// End block number (exclusive).
204 : end_blk_no: usize,
205 : /// Start offset and metadata for each blob in this read
206 : blobs_at: VecMap<u64, BlobMeta>,
207 : max_read_size: Option<usize>,
208 : }
209 :
210 : impl ChunkedVectoredReadBuilder {
211 : const CHUNK_SIZE: usize = virtual_file::get_io_buffer_alignment();
212 : /// Start building a new vectored read.
213 : ///
214 : /// Note that by design, this does not check against reading more than `max_read_size` to
215 : /// support reading larger blobs than the configuration value. The builder will be single use
216 : /// however after that.
217 1615176 : fn new_impl(
218 1615176 : start_offset: u64,
219 1615176 : end_offset: u64,
220 1615176 : meta: BlobMeta,
221 1615176 : max_read_size: Option<usize>,
222 1615176 : ) -> Self {
223 1615176 : let mut blobs_at = VecMap::default();
224 1615176 : blobs_at
225 1615176 : .append(start_offset, meta)
226 1615176 : .expect("First insertion always succeeds");
227 1615176 :
228 1615176 : let start_blk_no = start_offset as usize / Self::CHUNK_SIZE;
229 1615176 : let end_blk_no = (end_offset as usize).div_ceil(Self::CHUNK_SIZE);
230 1615176 : Self {
231 1615176 : start_blk_no,
232 1615176 : end_blk_no,
233 1615176 : blobs_at,
234 1615176 : max_read_size,
235 1615176 : }
236 1615176 : }
237 :
238 1371804 : pub(crate) fn new(
239 1371804 : start_offset: u64,
240 1371804 : end_offset: u64,
241 1371804 : meta: BlobMeta,
242 1371804 : max_read_size: usize,
243 1371804 : ) -> Self {
244 1371804 : Self::new_impl(start_offset, end_offset, meta, Some(max_read_size))
245 1371804 : }
246 :
247 243372 : pub(crate) fn new_streaming(start_offset: u64, end_offset: u64, meta: BlobMeta) -> Self {
248 243372 : Self::new_impl(start_offset, end_offset, meta, None)
249 243372 : }
250 :
251 : /// Attempts to extend the current read with a new blob if the new blob resides in the same or the immediate next chunk.
252 : ///
253 : /// The resulting size also must be below the max read size.
254 21878576 : pub(crate) fn extend(&mut self, start: u64, end: u64, meta: BlobMeta) -> VectoredReadExtended {
255 21878576 : tracing::trace!(start, end, "trying to extend");
256 21878576 : let start_blk_no = start as usize / Self::CHUNK_SIZE;
257 21878576 : let end_blk_no = (end as usize).div_ceil(Self::CHUNK_SIZE);
258 :
259 21878576 : let not_limited_by_max_read_size = {
260 21878576 : if let Some(max_read_size) = self.max_read_size {
261 9353684 : let coalesced_size = (end_blk_no - self.start_blk_no) * Self::CHUNK_SIZE;
262 9353684 : coalesced_size <= max_read_size
263 : } else {
264 12524892 : true
265 : }
266 : };
267 :
268 : // True if the second block starts in the same block or the immediate next block where the first block ended.
269 : //
270 : // Note: This automatically handles the case where two blocks are adjacent to each other,
271 : // whether they starts on chunk size boundary or not.
272 21878576 : let is_adjacent_chunk_read = {
273 : // 1. first.end & second.start are in the same block
274 21878576 : self.end_blk_no == start_blk_no + 1 ||
275 : // 2. first.end ends one block before second.start
276 262372 : self.end_blk_no == start_blk_no
277 : };
278 :
279 21878576 : if is_adjacent_chunk_read && not_limited_by_max_read_size {
280 21609701 : self.end_blk_no = end_blk_no;
281 21609701 : self.blobs_at
282 21609701 : .append(start, meta)
283 21609701 : .expect("LSNs are ordered within vectored reads");
284 21609701 :
285 21609701 : return VectoredReadExtended::Yes;
286 268875 : }
287 268875 :
288 268875 : VectoredReadExtended::No
289 21878576 : }
290 :
291 12764328 : pub(crate) fn size(&self) -> usize {
292 12764328 : (self.end_blk_no - self.start_blk_no) * Self::CHUNK_SIZE
293 12764328 : }
294 :
295 1615176 : pub(crate) fn build(self) -> VectoredRead {
296 1615176 : let start = (self.start_blk_no * Self::CHUNK_SIZE) as u64;
297 1615176 : let end = (self.end_blk_no * Self::CHUNK_SIZE) as u64;
298 1615176 : VectoredRead {
299 1615176 : start,
300 1615176 : end,
301 1615176 : blobs_at: self.blobs_at,
302 1615176 : }
303 1615176 : }
304 : }
305 :
306 : #[derive(Copy, Clone, Debug)]
307 : pub enum BlobFlag {
308 : None,
309 : Ignore,
310 : ReplaceAll,
311 : }
312 :
313 : /// Planner for vectored blob reads.
314 : ///
315 : /// Blob offsets are received via [`VectoredReadPlanner::handle`]
316 : /// and coalesced into disk reads.
317 : ///
318 : /// The implementation is very simple:
319 : /// * Collect all blob offsets in an ordered structure
320 : /// * Iterate over the collected blobs and coalesce them into reads at the end
321 : pub struct VectoredReadPlanner {
322 : // Track all the blob offsets. Start offsets must be ordered.
323 : // Values in the value tuples are:
324 : // (
325 : // lsn of the blob,
326 : // start offset of the blob in the underlying file,
327 : // end offset of the blob in the underlying file,
328 : // whether the blob initializes the page image or not
329 : // see [`pageserver_api::record::NeonWalRecord::will_init`]
330 : // )
331 : blobs: BTreeMap<Key, Vec<(Lsn, u64, u64, bool)>>,
332 : // Arguments for previous blob passed into [`VectoredReadPlanner::handle`]
333 : prev: Option<(Key, Lsn, u64, BlobFlag)>,
334 :
335 : max_read_size: usize,
336 : }
337 :
338 : impl VectoredReadPlanner {
339 1597902 : pub fn new(max_read_size: usize) -> Self {
340 1597902 : Self {
341 1597902 : blobs: BTreeMap::new(),
342 1597902 : prev: None,
343 1597902 : max_read_size,
344 1597902 : }
345 1597902 : }
346 :
347 : /// Include a new blob in the read plan.
348 : ///
349 : /// This function is called from a B-Tree index visitor (see `DeltaLayerInner::plan_reads`
350 : /// and `ImageLayerInner::plan_reads`). Said visitor wants to collect blob offsets for all
351 : /// keys in a given keyspace. This function must be called for each key in the desired
352 : /// keyspace (monotonically continuous). [`Self::handle_range_end`] must
353 : /// be called after every range in the offset.
354 : ///
355 : /// In the event that keys are skipped, the behaviour is undefined and can lead to an
356 : /// incorrect read plan. We can end up asserting, erroring in wal redo or returning
357 : /// incorrect data to the user.
358 : ///
359 : /// The `flag` argument has two interesting values:
360 : /// * [`BlobFlag::ReplaceAll`]: The blob for this key should replace all existing blobs.
361 : /// This is used for WAL records that `will_init`.
362 : /// * [`BlobFlag::Ignore`]: This blob should not be included in the read. This happens
363 : /// if the blob is cached.
364 20996167 : pub fn handle(&mut self, key: Key, lsn: Lsn, offset: u64, flag: BlobFlag) {
365 : // Implementation note: internally lag behind by one blob such that
366 : // we have a start and end offset when initialising [`VectoredRead`]
367 20996167 : let (prev_key, prev_lsn, prev_offset, prev_flag) = match self.prev {
368 : None => {
369 1196313 : self.prev = Some((key, lsn, offset, flag));
370 1196313 : return;
371 : }
372 19799854 : Some(prev) => prev,
373 19799854 : };
374 19799854 :
375 19799854 : self.add_blob(prev_key, prev_lsn, prev_offset, offset, prev_flag);
376 19799854 :
377 19799854 : self.prev = Some((key, lsn, offset, flag));
378 20996167 : }
379 :
380 1716210 : pub fn handle_range_end(&mut self, offset: u64) {
381 1716210 : if let Some((prev_key, prev_lsn, prev_offset, prev_flag)) = self.prev {
382 1196313 : self.add_blob(prev_key, prev_lsn, prev_offset, offset, prev_flag);
383 1196313 : }
384 :
385 1716210 : self.prev = None;
386 1716210 : }
387 :
388 20996167 : fn add_blob(&mut self, key: Key, lsn: Lsn, start_offset: u64, end_offset: u64, flag: BlobFlag) {
389 20996167 : match flag {
390 13551168 : BlobFlag::None => {
391 13551168 : let blobs_for_key = self.blobs.entry(key).or_default();
392 13551168 : blobs_for_key.push((lsn, start_offset, end_offset, false));
393 13551168 : }
394 2049303 : BlobFlag::ReplaceAll => {
395 2049303 : let blobs_for_key = self.blobs.entry(key).or_default();
396 2049303 : blobs_for_key.clear();
397 2049303 : blobs_for_key.push((lsn, start_offset, end_offset, true));
398 2049303 : }
399 5395696 : BlobFlag::Ignore => {}
400 : }
401 20996167 : }
402 :
403 1597902 : pub fn finish(self) -> Vec<VectoredRead> {
404 1597902 : let mut current_read_builder: Option<ChunkedVectoredReadBuilder> = None;
405 1597902 : let mut reads = Vec::new();
406 :
407 3636659 : for (key, blobs_for_key) in self.blobs {
408 12470506 : for (lsn, start_offset, end_offset, will_init) in blobs_for_key {
409 10431749 : let extended = match &mut current_read_builder {
410 9353552 : Some(read_builder) => read_builder.extend(
411 9353552 : start_offset,
412 9353552 : end_offset,
413 9353552 : BlobMeta {
414 9353552 : key,
415 9353552 : lsn,
416 9353552 : will_init,
417 9353552 : },
418 9353552 : ),
419 1078197 : None => VectoredReadExtended::No,
420 : };
421 :
422 10431749 : if extended == VectoredReadExtended::No {
423 1347036 : let next_read_builder = ChunkedVectoredReadBuilder::new(
424 1347036 : start_offset,
425 1347036 : end_offset,
426 1347036 : BlobMeta {
427 1347036 : key,
428 1347036 : lsn,
429 1347036 : will_init,
430 1347036 : },
431 1347036 : self.max_read_size,
432 1347036 : );
433 1347036 :
434 1347036 : let prev_read_builder = current_read_builder.replace(next_read_builder);
435 :
436 : // `current_read_builder` is None in the first iteration of the outer loop
437 1347036 : if let Some(read_builder) = prev_read_builder {
438 268839 : reads.push(read_builder.build());
439 1078197 : }
440 9084713 : }
441 : }
442 : }
443 :
444 1597902 : if let Some(read_builder) = current_read_builder {
445 1078197 : reads.push(read_builder.build());
446 1078197 : }
447 :
448 1597902 : reads
449 1597902 : }
450 : }
451 :
452 : /// Disk reader for vectored blob spans (does not go through the page cache)
453 : pub struct VectoredBlobReader<'a> {
454 : file: &'a VirtualFile,
455 : }
456 :
457 : impl<'a> VectoredBlobReader<'a> {
458 1472952 : pub fn new(file: &'a VirtualFile) -> Self {
459 1472952 : Self { file }
460 1472952 : }
461 :
462 : /// Read the requested blobs into the buffer.
463 : ///
464 : /// We have to deal with the fact that blobs are not fixed size.
465 : /// Each blob is prefixed by a size header.
466 : ///
467 : /// The success return value is a struct which contains the buffer
468 : /// filled from disk and a list of offsets at which each blob lies
469 : /// in the buffer.
470 1614720 : pub async fn read_blobs(
471 1614720 : &self,
472 1614720 : read: &VectoredRead,
473 1614720 : buf: IoBufferMut,
474 1614720 : ctx: &RequestContext,
475 1614720 : ) -> Result<VectoredBlobsBuf, std::io::Error> {
476 1614720 : assert!(read.size() > 0);
477 1614720 : assert!(
478 1614720 : read.size() <= buf.capacity(),
479 0 : "{} > {}",
480 0 : read.size(),
481 0 : buf.capacity()
482 : );
483 :
484 1614720 : if cfg!(debug_assertions) {
485 1614720 : const ALIGN: u64 = virtual_file::get_io_buffer_alignment() as u64;
486 1614720 : debug_assert_eq!(
487 1614720 : read.start % ALIGN,
488 : 0,
489 0 : "Read start at {} does not satisfy the required io buffer alignment ({} bytes)",
490 : read.start,
491 : ALIGN
492 : );
493 0 : }
494 :
495 1614720 : let buf = self
496 1614720 : .file
497 1614720 : .read_exact_at(buf.slice(0..read.size()), read.start, ctx)
498 1614720 : .await?
499 1614720 : .into_inner();
500 1614720 :
501 1614720 : let blobs_at = read.blobs_at.as_slice();
502 1614720 :
503 1614720 : let mut blobs = Vec::with_capacity(blobs_at.len());
504 : // Blobs in `read` only provide their starting offset. The end offset
505 : // of a blob is implicit: the start of the next blob if one exists
506 : // or the end of the read.
507 :
508 23224205 : for (blob_start, meta) in blobs_at.iter().copied() {
509 23224205 : let header_start = (blob_start - read.start) as usize;
510 23224205 : let header = Header::decode(&buf[header_start..])?;
511 23224205 : let data_start = header_start + header.header_len;
512 23224205 : let end = data_start + header.data_len;
513 23224205 : let compression_bits = header.compression_bits;
514 23224205 :
515 23224205 : blobs.push(VectoredBlob {
516 23224205 : header_start,
517 23224205 : data_start,
518 23224205 : end,
519 23224205 : meta,
520 23224205 : compression_bits,
521 23224205 : });
522 : }
523 :
524 1614720 : Ok(VectoredBlobsBuf { buf, blobs })
525 1614720 : }
526 : }
527 :
528 : /// Read planner used in [`crate::tenant::storage_layer::image_layer::ImageLayerIterator`].
529 : ///
530 : /// It provides a streaming API for getting read blobs. It returns a batch when
531 : /// `handle` gets called and when the current key would just exceed the read_size and
532 : /// max_cnt constraints.
533 : pub struct StreamingVectoredReadPlanner {
534 : read_builder: Option<ChunkedVectoredReadBuilder>,
535 : // Arguments for previous blob passed into [`StreamingVectoredReadPlanner::handle`]
536 : prev: Option<(Key, Lsn, u64, bool)>,
537 : /// Max read size per batch. This is not a strict limit. If there are [0, 100) and [100, 200), while the `max_read_size` is 150,
538 : /// we will produce a single batch instead of split them.
539 : max_read_size: u64,
540 : /// Max item count per batch
541 : max_cnt: usize,
542 : /// Size of the current batch
543 : cnt: usize,
544 : }
545 :
546 : impl StreamingVectoredReadPlanner {
547 4956 : pub fn new(max_read_size: u64, max_cnt: usize) -> Self {
548 4956 : assert!(max_cnt > 0);
549 4956 : assert!(max_read_size > 0);
550 4956 : Self {
551 4956 : read_builder: None,
552 4956 : prev: None,
553 4956 : max_cnt,
554 4956 : max_read_size,
555 4956 : cnt: 0,
556 4956 : }
557 4956 : }
558 :
559 12768600 : pub fn handle(
560 12768600 : &mut self,
561 12768600 : key: Key,
562 12768600 : lsn: Lsn,
563 12768600 : offset: u64,
564 12768600 : will_init: bool,
565 12768600 : ) -> Option<VectoredRead> {
566 : // Implementation note: internally lag behind by one blob such that
567 : // we have a start and end offset when initialising [`VectoredRead`]
568 12768600 : let (prev_key, prev_lsn, prev_offset, prev_will_init) = match self.prev {
569 : None => {
570 4272 : self.prev = Some((key, lsn, offset, will_init));
571 4272 : return None;
572 : }
573 12764328 : Some(prev) => prev,
574 12764328 : };
575 12764328 :
576 12764328 : let res = self.add_blob(
577 12764328 : prev_key,
578 12764328 : prev_lsn,
579 12764328 : prev_offset,
580 12764328 : offset,
581 12764328 : false,
582 12764328 : prev_will_init,
583 12764328 : );
584 12764328 :
585 12764328 : self.prev = Some((key, lsn, offset, will_init));
586 12764328 :
587 12764328 : res
588 12768600 : }
589 :
590 3948 : pub fn handle_range_end(&mut self, offset: u64) -> Option<VectoredRead> {
591 3948 : let res = if let Some((prev_key, prev_lsn, prev_offset, prev_will_init)) = self.prev {
592 3936 : self.add_blob(
593 3936 : prev_key,
594 3936 : prev_lsn,
595 3936 : prev_offset,
596 3936 : offset,
597 3936 : true,
598 3936 : prev_will_init,
599 3936 : )
600 : } else {
601 12 : None
602 : };
603 :
604 3948 : self.prev = None;
605 3948 :
606 3948 : res
607 3948 : }
608 :
609 12768264 : fn add_blob(
610 12768264 : &mut self,
611 12768264 : key: Key,
612 12768264 : lsn: Lsn,
613 12768264 : start_offset: u64,
614 12768264 : end_offset: u64,
615 12768264 : is_last_blob_in_read: bool,
616 12768264 : will_init: bool,
617 12768264 : ) -> Option<VectoredRead> {
618 12768264 : match &mut self.read_builder {
619 12524892 : Some(read_builder) => {
620 12524892 : let extended = read_builder.extend(
621 12524892 : start_offset,
622 12524892 : end_offset,
623 12524892 : BlobMeta {
624 12524892 : key,
625 12524892 : lsn,
626 12524892 : will_init,
627 12524892 : },
628 12524892 : );
629 12524892 : assert_eq!(extended, VectoredReadExtended::Yes);
630 : }
631 243372 : None => {
632 243372 : self.read_builder = {
633 243372 : Some(ChunkedVectoredReadBuilder::new_streaming(
634 243372 : start_offset,
635 243372 : end_offset,
636 243372 : BlobMeta {
637 243372 : key,
638 243372 : lsn,
639 243372 : will_init,
640 243372 : },
641 243372 : ))
642 243372 : };
643 243372 : }
644 : }
645 12768264 : let read_builder = self.read_builder.as_mut().unwrap();
646 12768264 : self.cnt += 1;
647 12768264 : if is_last_blob_in_read
648 12764328 : || read_builder.size() >= self.max_read_size as usize
649 12591264 : || self.cnt >= self.max_cnt
650 : {
651 243372 : let prev_read_builder = self.read_builder.take();
652 243372 : self.cnt = 0;
653 :
654 : // `current_read_builder` is None in the first iteration
655 243372 : if let Some(read_builder) = prev_read_builder {
656 243372 : return Some(read_builder.build());
657 0 : }
658 12524892 : }
659 12524892 : None
660 12768264 : }
661 : }
662 :
663 : #[cfg(test)]
664 : mod tests {
665 : use anyhow::Error;
666 :
667 : use super::super::blob_io::tests::{random_array, write_maybe_compressed};
668 : use super::*;
669 : use crate::context::DownloadBehavior;
670 : use crate::page_cache::PAGE_SZ;
671 : use crate::task_mgr::TaskKind;
672 :
673 288 : fn validate_read(read: &VectoredRead, offset_range: &[(Key, Lsn, u64, BlobFlag)]) {
674 : const ALIGN: u64 = virtual_file::get_io_buffer_alignment() as u64;
675 288 : assert_eq!(read.start % ALIGN, 0);
676 288 : assert_eq!(read.start / ALIGN, offset_range.first().unwrap().2 / ALIGN);
677 :
678 504 : let expected_offsets_in_read: Vec<_> = offset_range.iter().map(|o| o.2).collect();
679 288 :
680 288 : let offsets_in_read: Vec<_> = read
681 288 : .blobs_at
682 288 : .as_slice()
683 288 : .iter()
684 504 : .map(|(offset, _)| *offset)
685 288 : .collect();
686 288 :
687 288 : assert_eq!(expected_offsets_in_read, offsets_in_read);
688 288 : }
689 :
690 : #[test]
691 12 : fn planner_chunked_coalesce_all_test() {
692 : use crate::virtual_file;
693 :
694 : const CHUNK_SIZE: u64 = virtual_file::get_io_buffer_alignment() as u64;
695 :
696 12 : let max_read_size = CHUNK_SIZE as usize * 8;
697 12 : let key = Key::MIN;
698 12 : let lsn = Lsn(0);
699 12 :
700 12 : let blob_descriptions = [
701 12 : (key, lsn, CHUNK_SIZE / 8, BlobFlag::None), // Read 1 BEGIN
702 12 : (key, lsn, CHUNK_SIZE / 4, BlobFlag::Ignore), // Gap
703 12 : (key, lsn, CHUNK_SIZE / 2, BlobFlag::None),
704 12 : (key, lsn, CHUNK_SIZE - 2, BlobFlag::Ignore), // Gap
705 12 : (key, lsn, CHUNK_SIZE, BlobFlag::None),
706 12 : (key, lsn, CHUNK_SIZE * 2 - 1, BlobFlag::None),
707 12 : (key, lsn, CHUNK_SIZE * 2 + 1, BlobFlag::Ignore), // Gap
708 12 : (key, lsn, CHUNK_SIZE * 3 + 1, BlobFlag::None),
709 12 : (key, lsn, CHUNK_SIZE * 5 + 1, BlobFlag::None),
710 12 : (key, lsn, CHUNK_SIZE * 6 + 1, BlobFlag::Ignore), // skipped chunk size, but not a chunk: should coalesce.
711 12 : (key, lsn, CHUNK_SIZE * 7 + 1, BlobFlag::None),
712 12 : (key, lsn, CHUNK_SIZE * 8, BlobFlag::None), // Read 2 BEGIN (b/c max_read_size)
713 12 : (key, lsn, CHUNK_SIZE * 9, BlobFlag::Ignore), // ==== skipped a chunk
714 12 : (key, lsn, CHUNK_SIZE * 10, BlobFlag::None), // Read 3 BEGIN (cannot coalesce)
715 12 : ];
716 12 :
717 12 : let ranges = [
718 12 : &[
719 12 : blob_descriptions[0],
720 12 : blob_descriptions[2],
721 12 : blob_descriptions[4],
722 12 : blob_descriptions[5],
723 12 : blob_descriptions[7],
724 12 : blob_descriptions[8],
725 12 : blob_descriptions[10],
726 12 : ],
727 12 : &blob_descriptions[11..12],
728 12 : &blob_descriptions[13..],
729 12 : ];
730 12 :
731 12 : let mut planner = VectoredReadPlanner::new(max_read_size);
732 180 : for (key, lsn, offset, flag) in blob_descriptions {
733 168 : planner.handle(key, lsn, offset, flag);
734 168 : }
735 :
736 12 : planner.handle_range_end(652 * 1024);
737 12 :
738 12 : let reads = planner.finish();
739 12 :
740 12 : assert_eq!(reads.len(), ranges.len());
741 :
742 36 : for (idx, read) in reads.iter().enumerate() {
743 36 : validate_read(read, ranges[idx]);
744 36 : }
745 12 : }
746 :
747 : #[test]
748 12 : fn planner_max_read_size_test() {
749 12 : let max_read_size = 128 * 1024;
750 12 : let key = Key::MIN;
751 12 : let lsn = Lsn(0);
752 12 :
753 12 : let blob_descriptions = vec![
754 12 : (key, lsn, 0, BlobFlag::None),
755 12 : (key, lsn, 32 * 1024, BlobFlag::None),
756 12 : (key, lsn, 96 * 1024, BlobFlag::None), // Last in read 1
757 12 : (key, lsn, 128 * 1024, BlobFlag::None), // Last in read 2
758 12 : (key, lsn, 198 * 1024, BlobFlag::None), // Last in read 3
759 12 : (key, lsn, 268 * 1024, BlobFlag::None), // Last in read 4
760 12 : (key, lsn, 396 * 1024, BlobFlag::None), // Last in read 5
761 12 : (key, lsn, 652 * 1024, BlobFlag::None), // Last in read 6
762 12 : ];
763 12 :
764 12 : let ranges = [
765 12 : &blob_descriptions[0..3],
766 12 : &blob_descriptions[3..4],
767 12 : &blob_descriptions[4..5],
768 12 : &blob_descriptions[5..6],
769 12 : &blob_descriptions[6..7],
770 12 : &blob_descriptions[7..],
771 12 : ];
772 12 :
773 12 : let mut planner = VectoredReadPlanner::new(max_read_size);
774 96 : for (key, lsn, offset, flag) in blob_descriptions.clone() {
775 96 : planner.handle(key, lsn, offset, flag);
776 96 : }
777 :
778 12 : planner.handle_range_end(652 * 1024);
779 12 :
780 12 : let reads = planner.finish();
781 12 :
782 12 : assert_eq!(reads.len(), 6);
783 :
784 : // TODO: could remove zero reads to produce 5 reads here
785 :
786 72 : for (idx, read) in reads.iter().enumerate() {
787 72 : validate_read(read, ranges[idx]);
788 72 : }
789 12 : }
790 :
791 : #[test]
792 12 : fn planner_replacement_test() {
793 : const CHUNK_SIZE: u64 = virtual_file::get_io_buffer_alignment() as u64;
794 12 : let max_read_size = 128 * CHUNK_SIZE as usize;
795 12 : let first_key = Key::MIN;
796 12 : let second_key = first_key.next();
797 12 : let lsn = Lsn(0);
798 12 :
799 12 : let blob_descriptions = vec![
800 12 : (first_key, lsn, 0, BlobFlag::None), // First in read 1
801 12 : (first_key, lsn, CHUNK_SIZE, BlobFlag::None), // Last in read 1
802 12 : (second_key, lsn, 2 * CHUNK_SIZE, BlobFlag::ReplaceAll),
803 12 : (second_key, lsn, 3 * CHUNK_SIZE, BlobFlag::None),
804 12 : (second_key, lsn, 4 * CHUNK_SIZE, BlobFlag::ReplaceAll), // First in read 2
805 12 : (second_key, lsn, 5 * CHUNK_SIZE, BlobFlag::None), // Last in read 2
806 12 : ];
807 12 :
808 12 : let ranges = [&blob_descriptions[0..2], &blob_descriptions[4..]];
809 12 :
810 12 : let mut planner = VectoredReadPlanner::new(max_read_size);
811 72 : for (key, lsn, offset, flag) in blob_descriptions.clone() {
812 72 : planner.handle(key, lsn, offset, flag);
813 72 : }
814 :
815 12 : planner.handle_range_end(6 * CHUNK_SIZE);
816 12 :
817 12 : let reads = planner.finish();
818 12 : assert_eq!(reads.len(), 2);
819 :
820 24 : for (idx, read) in reads.iter().enumerate() {
821 24 : validate_read(read, ranges[idx]);
822 24 : }
823 12 : }
824 :
825 : #[test]
826 12 : fn streaming_planner_max_read_size_test() {
827 12 : let max_read_size = 128 * 1024;
828 12 : let key = Key::MIN;
829 12 : let lsn = Lsn(0);
830 12 :
831 12 : let blob_descriptions = vec![
832 12 : (key, lsn, 0, BlobFlag::None),
833 12 : (key, lsn, 32 * 1024, BlobFlag::None),
834 12 : (key, lsn, 96 * 1024, BlobFlag::None),
835 12 : (key, lsn, 128 * 1024, BlobFlag::None),
836 12 : (key, lsn, 198 * 1024, BlobFlag::None),
837 12 : (key, lsn, 268 * 1024, BlobFlag::None),
838 12 : (key, lsn, 396 * 1024, BlobFlag::None),
839 12 : (key, lsn, 652 * 1024, BlobFlag::None),
840 12 : ];
841 12 :
842 12 : let ranges = [
843 12 : &blob_descriptions[0..3],
844 12 : &blob_descriptions[3..5],
845 12 : &blob_descriptions[5..6],
846 12 : &blob_descriptions[6..7],
847 12 : &blob_descriptions[7..],
848 12 : ];
849 12 :
850 12 : let mut planner = StreamingVectoredReadPlanner::new(max_read_size, 1000);
851 12 : let mut reads = Vec::new();
852 96 : for (key, lsn, offset, _) in blob_descriptions.clone() {
853 96 : reads.extend(planner.handle(key, lsn, offset, false));
854 96 : }
855 12 : reads.extend(planner.handle_range_end(652 * 1024));
856 12 :
857 12 : assert_eq!(reads.len(), ranges.len());
858 :
859 60 : for (idx, read) in reads.iter().enumerate() {
860 60 : validate_read(read, ranges[idx]);
861 60 : }
862 12 : }
863 :
864 : #[test]
865 12 : fn streaming_planner_max_cnt_test() {
866 12 : let max_read_size = 1024 * 1024;
867 12 : let key = Key::MIN;
868 12 : let lsn = Lsn(0);
869 12 :
870 12 : let blob_descriptions = vec![
871 12 : (key, lsn, 0, BlobFlag::None),
872 12 : (key, lsn, 32 * 1024, BlobFlag::None),
873 12 : (key, lsn, 96 * 1024, BlobFlag::None),
874 12 : (key, lsn, 128 * 1024, BlobFlag::None),
875 12 : (key, lsn, 198 * 1024, BlobFlag::None),
876 12 : (key, lsn, 268 * 1024, BlobFlag::None),
877 12 : (key, lsn, 396 * 1024, BlobFlag::None),
878 12 : (key, lsn, 652 * 1024, BlobFlag::None),
879 12 : ];
880 12 :
881 12 : let ranges = [
882 12 : &blob_descriptions[0..2],
883 12 : &blob_descriptions[2..4],
884 12 : &blob_descriptions[4..6],
885 12 : &blob_descriptions[6..],
886 12 : ];
887 12 :
888 12 : let mut planner = StreamingVectoredReadPlanner::new(max_read_size, 2);
889 12 : let mut reads = Vec::new();
890 96 : for (key, lsn, offset, _) in blob_descriptions.clone() {
891 96 : reads.extend(planner.handle(key, lsn, offset, false));
892 96 : }
893 12 : reads.extend(planner.handle_range_end(652 * 1024));
894 12 :
895 12 : assert_eq!(reads.len(), ranges.len());
896 :
897 48 : for (idx, read) in reads.iter().enumerate() {
898 48 : validate_read(read, ranges[idx]);
899 48 : }
900 12 : }
901 :
902 : #[test]
903 12 : fn streaming_planner_edge_test() {
904 12 : let max_read_size = 1024 * 1024;
905 12 : let key = Key::MIN;
906 12 : let lsn = Lsn(0);
907 12 : {
908 12 : let mut planner = StreamingVectoredReadPlanner::new(max_read_size, 1);
909 12 : let mut reads = Vec::new();
910 12 : reads.extend(planner.handle_range_end(652 * 1024));
911 12 : assert!(reads.is_empty());
912 : }
913 : {
914 12 : let mut planner = StreamingVectoredReadPlanner::new(max_read_size, 1);
915 12 : let mut reads = Vec::new();
916 12 : reads.extend(planner.handle(key, lsn, 0, false));
917 12 : reads.extend(planner.handle_range_end(652 * 1024));
918 12 : assert_eq!(reads.len(), 1);
919 12 : validate_read(&reads[0], &[(key, lsn, 0, BlobFlag::None)]);
920 12 : }
921 12 : {
922 12 : let mut planner = StreamingVectoredReadPlanner::new(max_read_size, 1);
923 12 : let mut reads = Vec::new();
924 12 : reads.extend(planner.handle(key, lsn, 0, false));
925 12 : reads.extend(planner.handle(key, lsn, 128 * 1024, false));
926 12 : reads.extend(planner.handle_range_end(652 * 1024));
927 12 : assert_eq!(reads.len(), 2);
928 12 : validate_read(&reads[0], &[(key, lsn, 0, BlobFlag::None)]);
929 12 : validate_read(&reads[1], &[(key, lsn, 128 * 1024, BlobFlag::None)]);
930 12 : }
931 12 : {
932 12 : let mut planner = StreamingVectoredReadPlanner::new(max_read_size, 2);
933 12 : let mut reads = Vec::new();
934 12 : reads.extend(planner.handle(key, lsn, 0, false));
935 12 : reads.extend(planner.handle(key, lsn, 128 * 1024, false));
936 12 : reads.extend(planner.handle_range_end(652 * 1024));
937 12 : assert_eq!(reads.len(), 1);
938 12 : validate_read(
939 12 : &reads[0],
940 12 : &[
941 12 : (key, lsn, 0, BlobFlag::None),
942 12 : (key, lsn, 128 * 1024, BlobFlag::None),
943 12 : ],
944 12 : );
945 12 : }
946 12 : }
947 :
948 48 : async fn round_trip_test_compressed(blobs: &[Vec<u8>], compression: bool) -> Result<(), Error> {
949 48 : let ctx =
950 48 : RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error).with_scope_unit_test();
951 48 : let (_temp_dir, pathbuf, offsets) =
952 48 : write_maybe_compressed::<true>(blobs, compression, &ctx).await?;
953 :
954 48 : let file = VirtualFile::open(&pathbuf, &ctx).await?;
955 48 : let file_len = std::fs::metadata(&pathbuf)?.len();
956 48 :
957 48 : // Multiply by two (compressed data might need more space), and add a few bytes for the header
958 24720 : let reserved_bytes = blobs.iter().map(|bl| bl.len()).max().unwrap() * 2 + 16;
959 48 : let mut buf = IoBufferMut::with_capacity(reserved_bytes);
960 48 :
961 48 : let vectored_blob_reader = VectoredBlobReader::new(&file);
962 48 : let meta = BlobMeta {
963 48 : key: Key::MIN,
964 48 : lsn: Lsn(0),
965 48 : will_init: false,
966 48 : };
967 :
968 24720 : for (idx, (blob, offset)) in blobs.iter().zip(offsets.iter()).enumerate() {
969 24720 : let end = offsets.get(idx + 1).unwrap_or(&file_len);
970 24720 : if idx + 1 == offsets.len() {
971 48 : continue;
972 24672 : }
973 24672 : let read_builder = ChunkedVectoredReadBuilder::new(*offset, *end, meta, 16 * 4096);
974 24672 : let read = read_builder.build();
975 24672 : let result = vectored_blob_reader.read_blobs(&read, buf, &ctx).await?;
976 24672 : assert_eq!(result.blobs.len(), 1);
977 24672 : let read_blob = &result.blobs[0];
978 24672 : let view = BufView::new_slice(&result.buf);
979 24672 : let read_buf = read_blob.read(&view).await?;
980 24672 : assert_eq!(
981 24672 : &blob[..],
982 24672 : &read_buf[..],
983 0 : "mismatch for idx={idx} at offset={offset}"
984 : );
985 :
986 : // Check that raw_with_header returns a valid header.
987 24672 : let raw = read_blob.raw_with_header(&view);
988 24672 : let header = Header::decode(&raw)?;
989 24672 : if !compression || header.header_len == 1 {
990 12456 : assert_eq!(header.compression_bits, BYTE_UNCOMPRESSED);
991 12216 : }
992 24672 : assert_eq!(raw.len(), header.total_len());
993 :
994 24672 : buf = result.buf;
995 : }
996 48 : Ok(())
997 48 : }
998 :
999 : #[tokio::test]
1000 12 : async fn test_really_big_array() -> Result<(), Error> {
1001 12 : let blobs = &[
1002 12 : b"test".to_vec(),
1003 12 : random_array(10 * PAGE_SZ),
1004 12 : b"hello".to_vec(),
1005 12 : random_array(66 * PAGE_SZ),
1006 12 : vec![0xf3; 24 * PAGE_SZ],
1007 12 : b"foobar".to_vec(),
1008 12 : ];
1009 12 : round_trip_test_compressed(blobs, false).await?;
1010 12 : round_trip_test_compressed(blobs, true).await?;
1011 12 : Ok(())
1012 12 : }
1013 :
1014 : #[tokio::test]
1015 12 : async fn test_arrays_inc() -> Result<(), Error> {
1016 12 : let blobs = (0..PAGE_SZ / 8)
1017 12288 : .map(|v| random_array(v * 16))
1018 12 : .collect::<Vec<_>>();
1019 12 : round_trip_test_compressed(&blobs, false).await?;
1020 12 : round_trip_test_compressed(&blobs, true).await?;
1021 12 : Ok(())
1022 12 : }
1023 : }
|