1mod metrics;
4#[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
34const CONTENTS_READ_SKIP_LIMIT: usize = 3;
37const PIECES_READING_CONCURRENCY: usize = 32;
39
40#[derive(Debug, Error)]
42pub enum DiskPieceCacheError {
43 #[error("Disk piece cache I/O error: {0}")]
45 Io(#[from] io::Error),
46 #[error("Can't preallocate cache file, probably not enough space on disk: {0}")]
48 CantPreallocateCacheFile(io::Error),
49 #[error("Offset outsize of range: provided {provided}, max {max}")]
51 OffsetOutsideOfRange {
52 provided: u32,
54 max: u32,
56 },
57 #[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#[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 &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#[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 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 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 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 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 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 file.file()
291 .allocate(expected_size)
292 .map_err(DiskPieceCacheError::CantPreallocateCacheFile)?;
293 file.set_len(expected_size)?;
295 }
296 }
297
298 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 pub const fn element_size() -> u32 {
314 ELEMENT_SIZE
315 }
316
317 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 (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 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 let element = cache_element::encode(piece_index, piece);
390 self.inner.files.write().write_at(element, element_offset)?;
391
392 Ok(())
393 }
394
395 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 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 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}