Skip to main content

ab_farmer/
disk_piece_cache.rs

1//! Disk piece cache implementation
2
3mod metrics;
4// TODO: Not supported under Miri: https://github.com/rust-lang/miri/issues/5137
5#[cfg(not(miri))]
6#[cfg(test)]
7mod tests;
8
9use crate::cache_element::{ChecksumMismatch, ELEMENT_PAGES, ELEMENT_SIZE};
10use crate::disk_piece_cache::metrics::DiskPieceCacheMetrics;
11use crate::farm::{FarmError, PieceCacheId, PieceCacheOffset};
12use crate::utils::AsyncJoinOnDrop;
13use crate::{cache_element, farm};
14use ab_core_primitives::pieces::{Piece, PieceIndex};
15use ab_direct_io_file::{DirectIoFile, IoBufError, OwnedPages};
16use async_trait::async_trait;
17use fs4::FileExt;
18use futures::channel::mpsc;
19use futures::{SinkExt, Stream, StreamExt, stream};
20use parking_lot::Mutex;
21use prometheus_client::registry::Registry;
22use std::fs::OpenOptions;
23use std::num::NonZeroU32;
24use std::path::Path;
25use std::sync::atomic::{AtomicU8, Ordering};
26use std::task::Poll;
27use std::{fs, io, iter, mem};
28use thiserror::Error;
29use tokio::runtime::Handle;
30use tokio::task;
31use tracing::{Span, debug, info, warn};
32use triomphe::Arc;
33
34/// How many pieces should be skipped before stopping to check the rest of contents, this allows to
35/// not miss most of the pieces after one or two corrupted pieces
36const CONTENTS_READ_SKIP_LIMIT: usize = 3;
37/// How many piece to read from disk at the same time (using tokio thread pool)
38const PIECES_READING_CONCURRENCY: usize = 32;
39
40/// Disk piece cache open error
41#[derive(Debug, Error)]
42pub enum DiskPieceCacheError {
43    /// I/O error occurred
44    #[error("Disk piece cache I/O error: {0}")]
45    Io(#[from] io::Error),
46    /// Can't preallocate cache file, probably not enough space on disk
47    #[error("Can't preallocate cache file, probably not enough space on disk: {0}")]
48    CantPreallocateCacheFile(io::Error),
49    /// Offset outsize of range
50    #[error("Offset outsize of range: provided {provided}, max {max}")]
51    OffsetOutsideOfRange {
52        /// Provided offset
53        provided: u32,
54        /// Max offset
55        max: u32,
56    },
57    /// Checksum mismatch
58    #[error("Checksum mismatch")]
59    ChecksumMismatch,
60}
61
62impl<B> From<IoBufError<B>> for DiskPieceCacheError {
63    #[inline]
64    fn from(error: IoBufError<B>) -> Self {
65        Self::Io(error.into())
66    }
67}
68
69/// The same file opened [`PIECES_READING_CONCURRENCY`] times for concurrent reads.
70///
71/// Multiple handles were measured to give much better parallel read performance (especially on
72/// Windows) than a single one, so the pool stays even though one [`DirectIoFile`] can be used
73/// concurrently.
74#[derive(Debug)]
75struct FilePool {
76    files: Box<[DirectIoFile; PIECES_READING_CONCURRENCY]>,
77    cursor: AtomicU8,
78}
79
80impl FilePool {
81    fn open(path: &Path) -> io::Result<Self> {
82        let mut open_options = OpenOptions::new();
83        open_options
84            .read(true)
85            .write(true)
86            .create(true)
87            .truncate(false);
88
89        let files = iter::repeat_with(|| DirectIoFile::open(open_options.clone(), path))
90            .take(PIECES_READING_CONCURRENCY)
91            .collect::<Result<Box<_>, _>>()?
92            .try_into()
93            .expect("Statically correct length; qed");
94        Ok(Self {
95            files,
96            cursor: AtomicU8::new(0),
97        })
98    }
99
100    fn read(&self) -> &DirectIoFile {
101        let position = usize::from(self.cursor.fetch_add(1, Ordering::Relaxed));
102        &self.files[position % PIECES_READING_CONCURRENCY]
103    }
104
105    fn write(&self) -> &DirectIoFile {
106        // Elements are whole pages written at page-aligned offsets, so writes don't need
107        // read/modify/write and don't take a lock, any file would work
108        &self.files[0]
109    }
110}
111
112#[derive(Debug)]
113struct Inner {
114    id: PieceCacheId,
115    files: FilePool,
116    max_num_elements: u32,
117    metrics: Option<DiskPieceCacheMetrics>,
118}
119
120/// Dedicated piece cache stored on one disk, is used both to accelerate DSN queries and to plot
121/// faster.
122///
123/// Implementation is backed by a file on disk.
124#[derive(Debug, Clone)]
125pub struct DiskPieceCache {
126    inner: Arc<Inner>,
127}
128
129#[async_trait]
130impl farm::PieceCache for DiskPieceCache {
131    fn id(&self) -> &PieceCacheId {
132        &self.inner.id
133    }
134
135    #[inline]
136    fn max_num_elements(&self) -> u32 {
137        self.inner.max_num_elements
138    }
139
140    async fn contents(
141        &self,
142    ) -> Result<
143        Box<
144            dyn Stream<Item = Result<(PieceCacheOffset, Option<PieceIndex>), FarmError>>
145                + Unpin
146                + Send
147                + '_,
148        >,
149        FarmError,
150    > {
151        let this = self.clone();
152        let (mut sender, receiver) = mpsc::channel(100_000);
153        let span = Span::current();
154        let read_contents = task::spawn_blocking(move || {
155            let _guard = span.enter();
156
157            let contents = this.contents();
158            for (piece_cache_offset, maybe_piece) in contents {
159                if let Err(error) =
160                    Handle::current().block_on(sender.send(Ok((piece_cache_offset, maybe_piece))))
161                {
162                    debug!(%error, "Aborting contents iteration due to receiver dropping");
163                    break;
164                }
165            }
166        });
167        let read_contents = Mutex::new(Some(AsyncJoinOnDrop::new(read_contents, false)));
168        // Change order such that in closure below `receiver` is dropped before `read_contents`
169        let mut receiver = receiver;
170
171        Ok(Box::new(stream::poll_fn(move |ctx| {
172            let poll_result = receiver.poll_next_unpin(ctx);
173
174            if matches!(poll_result, Poll::Ready(None)) {
175                read_contents.lock().take();
176            }
177
178            poll_result
179        })))
180    }
181
182    async fn write_piece(
183        &self,
184        offset: PieceCacheOffset,
185        piece_index: PieceIndex,
186        piece: &Piece,
187    ) -> Result<(), FarmError> {
188        let piece = piece.clone();
189        let piece_cache = self.clone();
190        Ok(AsyncJoinOnDrop::new(
191            task::spawn_blocking(move || piece_cache.write_piece(offset, piece_index, &piece)),
192            false,
193        )
194        .await??)
195    }
196
197    async fn read_piece_index(
198        &self,
199        offset: PieceCacheOffset,
200    ) -> Result<Option<PieceIndex>, FarmError> {
201        let piece_cache = self.clone();
202        let span = Span::current();
203        Ok(AsyncJoinOnDrop::new(
204            task::spawn_blocking(move || {
205                let _guard = span.enter();
206
207                piece_cache.read_piece_index(offset)
208            }),
209            false,
210        )
211        .await??)
212    }
213
214    async fn read_piece(
215        &self,
216        offset: PieceCacheOffset,
217    ) -> Result<Option<(PieceIndex, Piece)>, FarmError> {
218        let span = Span::current();
219
220        // TODO: On Windows spawning blocking task that allows concurrent reads causes huge memory
221        //  usage. No idea why it happens, but not spawning anything at all helps for some reason.
222        //  Someone at some point should figure it out and fix, but it will probably be not me
223        //  (Nazar).
224        //  See https://github.com/autonomys/subspace/issues/2813 and linked forum post for details.
225        //  This TODO exists in multiple files
226        if cfg!(windows) {
227            Ok(task::block_in_place(|| {
228                let _guard = span.enter();
229
230                self.read_piece(offset)
231            })?)
232        } else {
233            let piece_cache = self.clone();
234            Ok(AsyncJoinOnDrop::new(
235                task::spawn_blocking(move || {
236                    let _guard = span.enter();
237
238                    piece_cache.read_piece(offset)
239                }),
240                false,
241            )
242            .await??)
243        }
244    }
245
246    async fn read_pieces(
247        &self,
248        offsets: Box<dyn Iterator<Item = PieceCacheOffset> + Send>,
249    ) -> Result<
250        Box<
251            dyn Stream<Item = Result<(PieceCacheOffset, Option<(PieceIndex, Piece)>), FarmError>>
252                + Send
253                + Unpin
254                + '_,
255        >,
256        FarmError,
257    > {
258        let iter = offsets.map(move |offset| async move {
259            Ok((offset, farm::PieceCache::read_piece(self, offset).await?))
260        });
261        Ok(Box::new(
262            // Constrain concurrency to avoid excessive memory usage, while still getting
263            // performance of concurrent reads
264            stream::iter(iter).buffer_unordered(PIECES_READING_CONCURRENCY),
265        ))
266    }
267}
268
269impl DiskPieceCache {
270    pub(crate) const FILE_NAME: &'static str = "piece_cache.bin";
271
272    /// Open cache, capacity is measured in elements of [`DiskPieceCache::element_size()`] size
273    pub fn open(
274        directory: &Path,
275        capacity: NonZeroU32,
276        id: Option<PieceCacheId>,
277        registry: Option<&mut Registry>,
278    ) -> Result<Self, DiskPieceCacheError> {
279        let capacity = capacity.get();
280        let files = FilePool::open(&directory.join(Self::FILE_NAME))?;
281
282        let expected_size = u64::from(Self::element_size()) * u64::from(capacity);
283        // Align plot file size for disk sector size
284        let expected_size = expected_size.next_multiple_of(u64::from(OwnedPages::ALIGN));
285        {
286            let file = files.write();
287            if file.len()? != expected_size {
288                // Allocating the whole file (`set_len` below can create a sparse file, which will
289                // cause writes to fail later)
290                file.file()
291                    .allocate(expected_size)
292                    .map_err(DiskPieceCacheError::CantPreallocateCacheFile)?;
293                // Truncating file (if necessary)
294                file.set_len(expected_size)?;
295            }
296        }
297
298        // ID for cache is ephemeral unless provided explicitly
299        let id = id.unwrap_or_else(PieceCacheId::new);
300        let metrics = registry.map(|registry| DiskPieceCacheMetrics::new(registry, &id, capacity));
301
302        Ok(Self {
303            inner: Arc::new(Inner {
304                id,
305                files,
306                max_num_elements: capacity,
307                metrics,
308            }),
309        })
310    }
311
312    /// Size of a single piece cache element
313    pub const fn element_size() -> u32 {
314        ELEMENT_SIZE
315    }
316
317    /// Contents of this piece cache
318    ///
319    /// NOTE: it is possible to do concurrent reads and writes, higher level logic must ensure this
320    /// doesn't happen for the same piece being accessed!
321    pub(crate) fn contents(
322        &self,
323    ) -> impl ExactSizeIterator<Item = (PieceCacheOffset, Option<PieceIndex>)> + '_ {
324        let mut element = OwnedPages::EMPTY;
325        let count_total = self.inner.metrics.as_ref().is_some_and(|metrics| {
326            metrics.contents.inc();
327            metrics.capacity_used.get() == 0
328        });
329        let mut current_skip = 0;
330
331        // TODO: Parallelize or read in larger batches
332        (0..self.inner.max_num_elements).map(move |offset| {
333            if current_skip > CONTENTS_READ_SKIP_LIMIT {
334                return (PieceCacheOffset(offset), None);
335            }
336
337            match self.read_piece_internal(offset, &mut element) {
338                Ok(maybe_piece_index) => {
339                    if maybe_piece_index.is_none() {
340                        current_skip += 1;
341                    } else {
342                        if count_total && let Some(metrics) = &self.inner.metrics {
343                            metrics.capacity_used.inc();
344                        }
345                        current_skip = 0;
346                    }
347
348                    (PieceCacheOffset(offset), maybe_piece_index)
349                }
350                Err(error) => {
351                    warn!(%error, %offset, "Failed to read cache element");
352
353                    current_skip += 1;
354
355                    (PieceCacheOffset(offset), None)
356                }
357            }
358        })
359    }
360
361    /// Store piece in cache at specified offset, replacing existing piece if there is one.
362    ///
363    /// NOTE: it is possible to do concurrent reads and writes, higher level logic must ensure this
364    /// doesn't happen for the same piece being accessed!
365    pub(crate) fn write_piece(
366        &self,
367        offset: PieceCacheOffset,
368        piece_index: PieceIndex,
369        piece: &Piece,
370    ) -> Result<(), DiskPieceCacheError> {
371        let PieceCacheOffset(offset) = offset;
372        if offset >= self.inner.max_num_elements {
373            return Err(DiskPieceCacheError::OffsetOutsideOfRange {
374                provided: offset,
375                max: self.inner.max_num_elements - 1,
376            });
377        }
378
379        if let Some(metrics) = &self.inner.metrics {
380            metrics.write_piece.inc();
381            let capacity_used = i64::from(offset + 1);
382            if metrics.capacity_used.get() != capacity_used {
383                metrics.capacity_used.set(capacity_used);
384            }
385        }
386        let element_offset = u64::from(offset) * u64::from(ELEMENT_SIZE);
387
388        // The whole element is written at once
389        let element = cache_element::encode(piece_index, piece);
390        self.inner.files.write().write_at(element, element_offset)?;
391
392        Ok(())
393    }
394
395    /// Read piece index from cache at specified offset.
396    ///
397    /// Returns `None` if offset is out of range.
398    ///
399    /// NOTE: it is possible to do concurrent reads and writes, higher level logic must ensure this
400    /// doesn't happen for the same piece being accessed!
401    pub(crate) fn read_piece_index(
402        &self,
403        offset: PieceCacheOffset,
404    ) -> Result<Option<PieceIndex>, DiskPieceCacheError> {
405        let PieceCacheOffset(offset) = offset;
406        if offset >= self.inner.max_num_elements {
407            warn!(%offset, "Trying to read piece out of range, this must be an implementation bug");
408            return Err(DiskPieceCacheError::OffsetOutsideOfRange {
409                provided: offset,
410                max: self.inner.max_num_elements - 1,
411            });
412        }
413
414        if let Some(metrics) = &self.inner.metrics {
415            metrics.read_piece_index.inc();
416        }
417        self.read_piece_internal(offset, &mut OwnedPages::default())
418    }
419
420    /// Read piece from cache at specified offset.
421    ///
422    /// Returns `None` if offset is out of range.
423    ///
424    /// NOTE: it is possible to do concurrent reads and writes, higher level logic must ensure this
425    /// doesn't happen for the same piece being accessed!
426    pub(crate) fn read_piece(
427        &self,
428        offset: PieceCacheOffset,
429    ) -> Result<Option<(PieceIndex, Piece)>, DiskPieceCacheError> {
430        let PieceCacheOffset(offset) = offset;
431        if offset >= self.inner.max_num_elements {
432            warn!(%offset, "Trying to read piece out of range, this must be an implementation bug");
433            return Err(DiskPieceCacheError::OffsetOutsideOfRange {
434                provided: offset,
435                max: self.inner.max_num_elements - 1,
436            });
437        }
438
439        if let Some(metrics) = &self.inner.metrics {
440            metrics.read_piece.inc();
441        }
442        let mut element = OwnedPages::EMPTY;
443        if let Some(piece_index) = self.read_piece_internal(offset, &mut element)? {
444            let piece = cache_element::into_piece(element)
445                .expect("Successfully read element has the whole size; qed");
446            Ok(Some((piece_index, piece)))
447        } else {
448            Ok(None)
449        }
450    }
451
452    /// Read element at `offset` into `element`, replacing its contents, and verify its checksum
453    fn read_piece_internal(
454        &self,
455        offset: u32,
456        element: &mut OwnedPages,
457    ) -> Result<Option<PieceIndex>, DiskPieceCacheError> {
458        *element = self.inner.files.read().read_pages_at(
459            mem::take(element),
460            ELEMENT_PAGES,
461            u64::from(offset) * u64::from(ELEMENT_PAGES),
462        )?;
463
464        cache_element::verify_checksum(
465            element
466                .as_array()
467                .expect("Exactly one element was read; qed"),
468        )
469        .map_err(|ChecksumMismatch| DiskPieceCacheError::ChecksumMismatch)
470    }
471
472    pub(crate) fn wipe(directory: &Path) -> io::Result<()> {
473        let piece_cache = directory.join(Self::FILE_NAME);
474        if !piece_cache.exists() {
475            return Ok(());
476        }
477        info!("Deleting piece cache file at {}", piece_cache.display());
478        fs::remove_file(piece_cache)
479    }
480}