Skip to main content

subspace_farmer/
farmer_cache.rs

1//! A container that caches pieces
2//!
3//! Farmer cache is a container that orchestrates a bunch of piece and plot caches that together
4//! persist pieces in a way that is easy to retrieve comparing to decoding pieces from plots.
5
6mod metrics;
7mod piece_cache_state;
8#[cfg(test)]
9mod tests;
10
11use crate::farm::{MaybePieceStoredResult, PieceCache, PieceCacheId, PieceCacheOffset, PlotCache};
12use crate::farmer_cache::metrics::FarmerCacheMetrics;
13use crate::farmer_cache::piece_cache_state::PieceCachesState;
14use crate::node_client::NodeClient;
15use async_lock::RwLock as AsyncRwLock;
16use event_listener_primitives::{Bag, HandlerId};
17use futures::channel::mpsc;
18use futures::future::{Either, FusedFuture};
19use futures::stream::{FuturesOrdered, FuturesUnordered};
20use futures::{FutureExt, SinkExt, Stream, StreamExt, select, stream};
21use parking_lot::RwLock;
22use prometheus_client::registry::Registry;
23use rand::prelude::*;
24use rayon::prelude::*;
25use std::collections::hash_map::Entry;
26use std::collections::{HashMap, HashSet};
27use std::future::join;
28use std::sync::Arc;
29use std::sync::atomic::{AtomicUsize, Ordering};
30use std::task::Poll;
31use std::time::Duration;
32use std::{fmt, mem};
33use subspace_core_primitives::pieces::{Piece, PieceIndex};
34use subspace_core_primitives::segments::{SegmentHeader, SegmentIndex};
35use subspace_data_retrieval::piece_getter::PieceGetter;
36use subspace_networking::KeyWithDistance;
37use subspace_networking::libp2p::PeerId;
38use subspace_networking::libp2p::kad::RecordKey;
39use subspace_networking::utils::multihash::ToMultihash;
40use subspace_process::run_future_in_dedicated_thread;
41use tokio::sync::Semaphore;
42use tokio::task::yield_now;
43use tracing::{Instrument, debug, error, info, info_span, trace, warn};
44
45const WORKER_CHANNEL_CAPACITY: usize = 100;
46const SYNC_BATCH_SIZE: usize = 256;
47const SYNC_CONCURRENT_BATCHES: usize = 4;
48/// Interval in pieces after which piece cache sync progress is logged
49const SYNC_PROGRESS_LOG_INTERVAL: usize = 100;
50const INITIAL_SYNC_FARM_INFO_CHECK_INTERVAL: Duration = Duration::from_secs(1);
51
52type HandlerFn<A> = Arc<dyn Fn(&A) + Send + Sync + 'static>;
53type Handler<A> = Bag<HandlerFn<A>, A>;
54type CacheIndex = u8;
55
56#[derive(Default, Debug)]
57struct Handlers {
58    progress: Handler<f32>,
59}
60
61#[derive(Debug, Clone, Copy)]
62struct FarmerCacheOffset {
63    cache_index: CacheIndex,
64    piece_offset: PieceCacheOffset,
65}
66
67impl FarmerCacheOffset {
68    fn new(cache_index: CacheIndex, piece_offset: PieceCacheOffset) -> Self {
69        Self {
70            cache_index,
71            piece_offset,
72        }
73    }
74}
75
76#[derive(Debug, Clone)]
77struct CacheBackend {
78    backend: Arc<dyn PieceCache>,
79    used_capacity: u32,
80    total_capacity: u32,
81}
82
83impl std::ops::Deref for CacheBackend {
84    type Target = Arc<dyn PieceCache>;
85
86    fn deref(&self) -> &Self::Target {
87        &self.backend
88    }
89}
90
91impl CacheBackend {
92    fn new(backend: Arc<dyn PieceCache>, total_capacity: u32) -> Self {
93        Self {
94            backend,
95            used_capacity: 0,
96            total_capacity,
97        }
98    }
99
100    fn next_free(&mut self) -> Option<PieceCacheOffset> {
101        let offset = self.used_capacity;
102        if offset < self.total_capacity {
103            self.used_capacity += 1;
104            Some(PieceCacheOffset(offset))
105        } else {
106            debug!(?offset, total_capacity = ?self.total_capacity, "No free space in cache backend");
107            None
108        }
109    }
110
111    fn free_size(&self) -> u32 {
112        self.total_capacity - self.used_capacity
113    }
114}
115
116#[derive(Debug)]
117struct CacheState {
118    cache_stored_pieces: HashMap<KeyWithDistance, FarmerCacheOffset>,
119    cache_free_offsets: Vec<FarmerCacheOffset>,
120    backend: CacheBackend,
121}
122
123#[derive(Debug)]
124enum WorkerCommand {
125    ReplaceBackingCaches {
126        new_piece_caches: Vec<Arc<dyn PieceCache>>,
127    },
128    ForgetKey {
129        key: RecordKey,
130    },
131}
132
133/// Farmer cache worker used to drive the farmer cache backend
134#[derive(Debug)]
135#[must_use = "Farmer cache will not work unless its worker is running"]
136pub struct FarmerCacheWorker<NC>
137where
138    NC: fmt::Debug,
139{
140    peer_id: PeerId,
141    node_client: NC,
142    piece_caches: Arc<AsyncRwLock<PieceCachesState>>,
143    plot_caches: Arc<PlotCaches>,
144    handlers: Arc<Handlers>,
145    worker_receiver: Option<mpsc::Receiver<WorkerCommand>>,
146    metrics: Option<Arc<FarmerCacheMetrics>>,
147}
148
149impl<NC> FarmerCacheWorker<NC>
150where
151    NC: NodeClient,
152{
153    /// Run the cache worker with provided piece getter.
154    ///
155    /// NOTE: Piece getter must not depend on farmer cache in order to avoid reference cycles!
156    pub async fn run<PG>(mut self, piece_getter: PG)
157    where
158        PG: PieceGetter,
159    {
160        // Limit is dynamically set later
161        let mut last_segment_index_internal = SegmentIndex::ZERO;
162
163        let mut worker_receiver = self
164            .worker_receiver
165            .take()
166            .expect("Always set during worker instantiation");
167
168        if let Some(WorkerCommand::ReplaceBackingCaches { new_piece_caches }) =
169            worker_receiver.next().await
170        {
171            self.initialize(
172                &piece_getter,
173                &mut last_segment_index_internal,
174                new_piece_caches,
175            )
176            .await;
177        } else {
178            // Piece cache is dropped before backing caches were sent
179            return;
180        }
181
182        let mut segment_headers_notifications =
183            match self.node_client.subscribe_archived_segment_headers().await {
184                Ok(segment_headers_notifications) => segment_headers_notifications,
185                Err(error) => {
186                    error!(%error, "Failed to subscribe to archived segments notifications");
187                    return;
188                }
189            };
190
191        // Keep up with segment indices that were potentially created since reinitialization,
192        // depending on the size of the diff this may pause block production for a while (due to
193        // subscription we have created above)
194        self.keep_up_after_initial_sync(&piece_getter, &mut last_segment_index_internal)
195            .await;
196
197        loop {
198            select! {
199                maybe_command = worker_receiver.next() => {
200                    let Some(command) = maybe_command else {
201                        // Nothing else left to do
202                        return;
203                    };
204
205                    self.handle_command(command, &piece_getter, &mut last_segment_index_internal).await;
206                }
207                maybe_segment_header = segment_headers_notifications.next().fuse() => {
208                    if let Some(segment_header) = maybe_segment_header {
209                        self.process_segment_header(&piece_getter, segment_header, &mut last_segment_index_internal).await;
210                    } else {
211                        // Keep-up sync only ends with subscription, which lasts for duration of an
212                        // instance
213                        return;
214                    }
215                }
216            }
217        }
218    }
219
220    async fn handle_command<PG>(
221        &self,
222        command: WorkerCommand,
223        piece_getter: &PG,
224        last_segment_index_internal: &mut SegmentIndex,
225    ) where
226        PG: PieceGetter,
227    {
228        match command {
229            WorkerCommand::ReplaceBackingCaches { new_piece_caches } => {
230                self.initialize(piece_getter, last_segment_index_internal, new_piece_caches)
231                    .await;
232            }
233            // TODO: Consider implementing optional re-sync of the piece instead of just forgetting
234            WorkerCommand::ForgetKey { key } => {
235                let mut caches = self.piece_caches.write().await;
236                let key = KeyWithDistance::new_with_record_key(self.peer_id, key);
237                let Some(offset) = caches.remove_stored_piece(&key) else {
238                    // Key not exist
239                    return;
240                };
241
242                let cache_index = offset.cache_index;
243                let piece_offset = offset.piece_offset;
244                let Some(backend) = caches.get_backend(cache_index).cloned() else {
245                    // Cache backend not exist
246                    return;
247                };
248
249                caches.push_dangling_free_offset(offset);
250                match backend.read_piece_index(piece_offset).await {
251                    Ok(Some(piece_index)) => {
252                        trace!(%piece_index, %cache_index, %piece_offset, "Forget piece");
253                    }
254                    Ok(None) => {
255                        warn!(
256                            %cache_index,
257                            %piece_offset,
258                            "Piece index out of range, this is likely an implementation bug, \
259                            not freeing heap element"
260                        );
261                    }
262                    Err(error) => {
263                        error!(
264                            %error,
265                            %cache_index,
266                            ?key,
267                            %piece_offset,
268                            "Error while reading piece from cache"
269                        );
270                    }
271                }
272            }
273        }
274    }
275
276    async fn initialize<PG>(
277        &self,
278        piece_getter: &PG,
279        last_segment_index_internal: &mut SegmentIndex,
280        new_piece_caches: Vec<Arc<dyn PieceCache>>,
281    ) where
282        PG: PieceGetter,
283    {
284        info!("Initializing piece cache");
285
286        // Pull old cache state since it will be replaced with a new one and reuse its allocations
287        let (mut stored_pieces, mut dangling_free_offsets) =
288            mem::take(&mut *self.piece_caches.write().await).reuse();
289
290        debug!("Collecting pieces that were in the cache before");
291
292        if let Some(metrics) = &self.metrics {
293            metrics.piece_cache_capacity_total.set(0);
294            metrics.piece_cache_capacity_used.set(0);
295        }
296
297        let peer_id = self.peer_id;
298
299        // Build cache state of all backends
300        let piece_caches_number = new_piece_caches.len();
301        let maybe_caches_futures = new_piece_caches
302            .into_iter()
303            .enumerate()
304            .filter_map(|(cache_index, new_cache)| {
305                let total_capacity = new_cache.max_num_elements();
306                let mut backend = CacheBackend::new(new_cache, total_capacity);
307                let Ok(cache_index) = CacheIndex::try_from(cache_index) else {
308                    warn!(
309                        ?piece_caches_number,
310                        "Too many piece caches provided, {cache_index} cache will be ignored",
311                    );
312                    return None;
313                };
314
315                if let Some(metrics) = &self.metrics {
316                    metrics
317                        .piece_cache_capacity_total
318                        .inc_by(total_capacity as i64);
319                }
320
321                let init_fut = async move {
322                    let used_capacity = &mut backend.used_capacity;
323
324                    // Hack with first collecting into `Option` with `Option::take()` call
325                    // later is to satisfy compiler that gets confused about ownership
326                    // otherwise
327                    let mut maybe_contents = match backend.backend.contents().await {
328                        Ok(contents) => Some(contents),
329                        Err(error) => {
330                            warn!(%error, "Failed to get cache contents");
331
332                            None
333                        }
334                    };
335
336                    #[allow(clippy::mutable_key_type)]
337                    let mut cache_stored_pieces = HashMap::new();
338                    let mut cache_free_offsets = Vec::new();
339
340                    let Some(mut contents) = maybe_contents.take() else {
341                        drop(maybe_contents);
342
343                        return CacheState {
344                            cache_stored_pieces,
345                            cache_free_offsets,
346                            backend,
347                        };
348                    };
349
350                    while let Some(maybe_element_details) = contents.next().await {
351                        let (piece_offset, maybe_piece_index) = match maybe_element_details {
352                            Ok(element_details) => element_details,
353                            Err(error) => {
354                                warn!(%error, "Failed to get cache contents element details");
355                                break;
356                            }
357                        };
358                        let offset = FarmerCacheOffset::new(cache_index, piece_offset);
359                        match maybe_piece_index {
360                            Some(piece_index) => {
361                                *used_capacity = piece_offset.0 + 1;
362                                let record_key = RecordKey::from(piece_index.to_multihash());
363                                let key = KeyWithDistance::new_with_record_key(peer_id, record_key);
364                                cache_stored_pieces.insert(key, offset);
365                            }
366                            None => {
367                                // TODO: Optimize to not store all free offsets, only dangling
368                                //  offsets are actually necessary
369                                cache_free_offsets.push(offset);
370                            }
371                        }
372
373                        // Allow for task to be aborted
374                        yield_now().await;
375                    }
376
377                    drop(maybe_contents);
378                    drop(contents);
379
380                    CacheState {
381                        cache_stored_pieces,
382                        cache_free_offsets,
383                        backend,
384                    }
385                };
386
387                Some(run_future_in_dedicated_thread(
388                    move || init_fut.instrument(info_span!("", %cache_index)),
389                    format!("piece-cache.{cache_index:02}"),
390                ))
391            })
392            .collect::<Result<Vec<_>, _>>();
393
394        let caches_futures = match maybe_caches_futures {
395            Ok(caches_futures) => caches_futures,
396            Err(error) => {
397                error!(%error, "Failed to spawn piece cache reading thread");
398
399                return;
400            }
401        };
402
403        let mut backends = Vec::with_capacity(caches_futures.len());
404        let mut caches_futures = caches_futures.into_iter().collect::<FuturesOrdered<_>>();
405
406        while let Some(maybe_cache) = caches_futures.next().await {
407            match maybe_cache {
408                Ok(cache) => {
409                    let backend = cache.backend;
410                    for (key, cache_offset) in cache.cache_stored_pieces {
411                        if let Some(old_cache_offset) = stored_pieces.insert(key, cache_offset) {
412                            dangling_free_offsets.push_front(old_cache_offset);
413                        }
414                    }
415                    dangling_free_offsets.extend(
416                        cache.cache_free_offsets.into_iter().filter(|free_offset| {
417                            free_offset.piece_offset.0 < backend.used_capacity
418                        }),
419                    );
420                    backends.push(backend);
421                }
422                Err(_cancelled) => {
423                    error!("Piece cache reading thread panicked");
424
425                    return;
426                }
427            };
428        }
429
430        let mut caches = PieceCachesState::new(stored_pieces, dangling_free_offsets, backends);
431
432        info!("Synchronizing piece cache");
433
434        let last_segment_index = loop {
435            match self.node_client.farmer_app_info().await {
436                Ok(farmer_app_info) => {
437                    let last_segment_index =
438                        farmer_app_info.protocol_info.history_size.segment_index();
439                    // Wait for node to be either fully synced or to be aware of non-zero segment
440                    // index, which would indicate it has started DSN sync and knows about
441                    // up-to-date archived history.
442                    //
443                    // While this doesn't account for situations where node was offline for a long
444                    // time and is aware of old segment headers, this is good enough for piece cache
445                    // sync to proceed and should result in better user experience on average.
446                    if !farmer_app_info.syncing || last_segment_index > SegmentIndex::ZERO {
447                        break last_segment_index;
448                    }
449                }
450                Err(error) => {
451                    error!(
452                        %error,
453                        "Failed to get farmer app info from node, keeping old cache state without \
454                        updates"
455                    );
456
457                    // Not the latest, but at least something
458                    *self.piece_caches.write().await = caches;
459                    return;
460                }
461            }
462
463            tokio::time::sleep(INITIAL_SYNC_FARM_INFO_CHECK_INTERVAL).await;
464        };
465
466        debug!(%last_segment_index, "Identified last segment index");
467
468        // Collect all the piece indices that need to be stored, we will sort them later
469        let segment_indices = Vec::from_iter(SegmentIndex::ZERO..=last_segment_index);
470        // TODO: This may eventually be too much to store in memory, though right now it is a
471        //  non-issue in practice
472        let mut piece_indices_to_store = segment_indices
473            .into_par_iter()
474            .flat_map(|segment_index| {
475                segment_index
476                    .segment_piece_indexes()
477                    .into_par_iter()
478                    .map(|piece_index| {
479                        (
480                            KeyWithDistance::new(self.peer_id, piece_index.to_multihash()),
481                            piece_index,
482                        )
483                    })
484            })
485            .collect::<Vec<_>>();
486
487        // Sort pieces by distance from peer to piece such that they are in ascending order
488        // and have higher chance of download
489        piece_indices_to_store.par_sort_unstable_by(|(a_key, _), (b_key, _)| a_key.cmp(b_key));
490
491        // `HashMap` is faster than `BTreeMap`
492        let mut piece_indices_to_store = piece_indices_to_store
493            .into_iter()
494            .take(caches.total_capacity())
495            .collect::<HashMap<_, _>>();
496
497        let mut piece_caches_capacity_used = vec![0u32; caches.backends().len()];
498        // Filter-out piece indices that are stored, but should not be as well as clean
499        // `inserted_piece_indices` from already stored piece indices, leaving just those that are
500        // still missing in cache
501        caches.free_unneeded_stored_pieces(&mut piece_indices_to_store);
502
503        if let Some(metrics) = &self.metrics {
504            for offset in caches.stored_pieces_offsets() {
505                piece_caches_capacity_used[usize::from(offset.cache_index)] += 1;
506            }
507
508            for cache_used in piece_caches_capacity_used {
509                metrics
510                    .piece_cache_capacity_used
511                    .inc_by(i64::from(cache_used));
512            }
513        }
514
515        let stored_count = caches.stored_pieces_offsets().len();
516        // Store whatever correct pieces are immediately available after restart, the rest is
517        // updated in place as pieces are downloaded, so readers always see the latest state
518        *self.piece_caches.write().await = caches;
519
520        debug!(
521            %stored_count,
522            count = %piece_indices_to_store.len(),
523            "Identified piece indices that should be cached",
524        );
525
526        let pieces_to_download_total = piece_indices_to_store.len() + stored_count;
527        let piece_indices_to_store = piece_indices_to_store
528            .into_values()
529            .collect::<Vec<_>>()
530            // TODO: Allocating chunks here shouldn't be necessary, but otherwise it fails with
531            //  confusing error described in https://github.com/rust-lang/rust/issues/64552 and
532            //  similar upstream issues
533            .chunks(SYNC_BATCH_SIZE)
534            .map(|chunk| chunk.to_vec())
535            .collect::<Vec<_>>();
536
537        let downloaded_pieces_count = AtomicUsize::new(stored_count);
538        self.handlers.progress.call_simple(&0.0);
539        let batch_count = piece_indices_to_store.len();
540        let piece_indices_to_store = piece_indices_to_store.into_iter().enumerate();
541
542        let downloading_semaphore = &Semaphore::new(SYNC_BATCH_SIZE * SYNC_CONCURRENT_BATCHES);
543        let ignored_cache_indices = &RwLock::new(HashSet::new());
544
545        let downloading_pieces_stream =
546            stream::iter(piece_indices_to_store.map(|(batch, piece_indices)| {
547                let downloaded_pieces_count = &downloaded_pieces_count;
548                let num_pieces = piece_indices.len();
549
550                trace!(
551                    %num_pieces,
552                    %batch,
553                    %batch_count,
554                    first_piece_index = ?piece_indices.first().expect("chunks are never empty"),
555                    last_piece_index = ?piece_indices.last().expect("chunks are never empty"),
556                    downloaded_pieces_count = %downloaded_pieces_count.load(Ordering::Relaxed),
557                    %pieces_to_download_total,
558                    available_permits = %downloading_semaphore.available_permits(),
559                    "Started piece cache sync batch",
560                );
561
562                async move {
563                    let mut permit = downloading_semaphore
564                        .acquire_many(SYNC_BATCH_SIZE as u32)
565                        .await
566                        .expect("Semaphore is never closed; qed");
567                    debug!(%batch, %num_pieces, "Downloading pieces");
568
569                    let pieces_stream = match piece_getter.get_pieces(piece_indices).await {
570                        Ok(pieces_stream) => pieces_stream,
571                        Err(error) => {
572                            error!(
573                                %error,
574                                "Failed to get pieces from piece getter"
575                            );
576                            return;
577                        }
578                    };
579                    let mut pieces_stream = pieces_stream.enumerate();
580
581                    while let Some((index, (piece_index, result))) = pieces_stream.next().await {
582                        debug!(%batch, %index, %piece_index, "Downloaded piece");
583                        // Release slot for future batches, by dropping it along with the piece.
584                        let _permit = permit.split(1);
585
586                        let piece = match result {
587                            Ok(Some(piece)) => {
588                                trace!(%batch, %piece_index, "Downloaded piece successfully");
589                                piece
590                            }
591                            Ok(None) => {
592                                debug!(%batch, %piece_index, "Couldn't find piece");
593                                continue;
594                            }
595                            Err(error) => {
596                                debug!(
597                                    %batch,
598                                    %error,
599                                    %piece_index,
600                                    "Failed to get piece for piece cache"
601                                );
602                                continue;
603                            }
604                        };
605
606                        let (offset, maybe_backend) = {
607                            let mut caches = self.piece_caches.write().await;
608
609                            // Find plot in which there is a place for new piece to be stored
610                            let Some(offset) = caches.pop_free_offset() else {
611                                error!(
612                                    %batch,
613                                    %piece_index,
614                                    "Failed to store piece in cache, there was no space"
615                                );
616                                break;
617                            };
618
619                            (offset, caches.get_backend(offset.cache_index).cloned())
620                        };
621
622                        let cache_index = offset.cache_index;
623                        let piece_offset = offset.piece_offset;
624
625                        let skip_write = ignored_cache_indices.read().contains(&cache_index);
626                        if skip_write {
627                            trace!(
628                                %batch,
629                                %cache_index,
630                                %piece_index,
631                                %piece_offset,
632                                "Skipping known problematic cache index"
633                            );
634                        } else {
635                            if let Some(backend) = maybe_backend
636                                && let Err(error) =
637                                    backend.write_piece(piece_offset, piece_index, &piece).await
638                            {
639                                error!(
640                                    %error,
641                                    %batch,
642                                    %cache_index,
643                                    %piece_index,
644                                    %piece_offset,
645                                    "Failed to write piece into cache, ignoring this cache going \
646                                    forward"
647                                );
648                                ignored_cache_indices.write().insert(cache_index);
649                                continue;
650                            }
651
652                            let key =
653                                KeyWithDistance::new(self.peer_id, piece_index.to_multihash());
654                            self.piece_caches
655                                .write()
656                                .await
657                                .push_stored_piece(key, offset);
658                        }
659
660                        let prev_downloaded_pieces_count =
661                            downloaded_pieces_count.fetch_add(1, Ordering::Relaxed);
662                        // Do not print anything or send progress notification after last piece
663                        // until piece cache is written fully below
664                        if prev_downloaded_pieces_count != pieces_to_download_total {
665                            let progress = prev_downloaded_pieces_count as f32
666                                / pieces_to_download_total as f32
667                                * 100.0;
668                            if prev_downloaded_pieces_count
669                                .is_multiple_of(SYNC_PROGRESS_LOG_INTERVAL)
670                            {
671                                info!(
672                                    "Piece cache sync {progress:.2}% complete ({} / {})",
673                                    bytesize::ByteSize::b(
674                                        (prev_downloaded_pieces_count * Piece::SIZE) as u64,
675                                    )
676                                    .display()
677                                    .iec(),
678                                    bytesize::ByteSize::b(
679                                        (pieces_to_download_total * Piece::SIZE) as u64,
680                                    )
681                                    .display()
682                                    .iec(),
683                                );
684                            }
685
686                            self.handlers.progress.call_simple(&progress);
687                        }
688                    }
689
690                    trace!(
691                        %num_pieces,
692                        %batch,
693                        %batch_count,
694                        downloaded_pieces_count = %downloaded_pieces_count.load(Ordering::Relaxed),
695                        %pieces_to_download_total,
696                        available_permits = %downloading_semaphore.available_permits(),
697                        "Finished piece cache sync batch",
698                    );
699                }
700            }));
701
702        // Download several batches concurrently to make sure slow tail of one is compensated by
703        // another
704        downloading_pieces_stream
705            // This allows to schedule new batch while previous batches partially completed, but
706            // avoids excessive memory usage like when all futures are created upfront
707            .buffer_unordered(SYNC_CONCURRENT_BATCHES * 10)
708            // Simply drain everything
709            .for_each(|()| async {})
710            .await;
711
712        self.handlers.progress.call_simple(&100.0);
713        *last_segment_index_internal = last_segment_index;
714
715        info!("Finished piece cache synchronization");
716    }
717
718    async fn process_segment_header<PG>(
719        &self,
720        piece_getter: &PG,
721        segment_header: SegmentHeader,
722        last_segment_index_internal: &mut SegmentIndex,
723    ) where
724        PG: PieceGetter,
725    {
726        let segment_index = segment_header.segment_index();
727        debug!(%segment_index, "Starting to process newly archived segment");
728
729        if *last_segment_index_internal < segment_index {
730            debug!(%segment_index, "Downloading potentially useful pieces");
731
732            // We do not insert pieces into cache/heap yet, so we don't know if all of these pieces
733            // will be included, but there is a good chance they will be, and we want to acknowledge
734            // new segment header as soon as possible
735            let pieces_to_maybe_include = segment_index
736                .segment_piece_indexes()
737                .into_iter()
738                .map(|piece_index| async move {
739                    let should_store_in_piece_cache = self
740                        .piece_caches
741                        .read()
742                        .await
743                        .should_include_key(self.peer_id, piece_index);
744
745                    let key = RecordKey::from(piece_index.to_multihash());
746                    let should_store_in_plot_cache =
747                        self.plot_caches.should_store(piece_index, &key).await;
748
749                    if !(should_store_in_piece_cache || should_store_in_plot_cache) {
750                        trace!(%piece_index, "Piece doesn't need to be cached #1");
751
752                        return None;
753                    }
754
755                    let maybe_piece_result =
756                        self.node_client
757                            .piece(piece_index)
758                            .await
759                            .inspect_err(|error| {
760                                debug!(
761                                    %error,
762                                    %segment_index,
763                                    %piece_index,
764                                    "Failed to retrieve piece from node right after archiving"
765                                );
766                            });
767
768                    if let Ok(Some(piece)) = maybe_piece_result {
769                        return Some((piece_index, piece));
770                    }
771
772                    match piece_getter.get_piece(piece_index).await {
773                        Ok(Some(piece)) => Some((piece_index, piece)),
774                        Ok(None) => {
775                            warn!(
776                                %segment_index,
777                                %piece_index,
778                                "Failed to retrieve piece right after archiving"
779                            );
780
781                            None
782                        }
783                        Err(error) => {
784                            warn!(
785                                %error,
786                                %segment_index,
787                                %piece_index,
788                                "Failed to retrieve piece right after archiving"
789                            );
790
791                            None
792                        }
793                    }
794                })
795                .collect::<FuturesUnordered<_>>()
796                .filter_map(|maybe_piece| async move { maybe_piece })
797                .collect::<Vec<_>>()
798                .await;
799
800            debug!(%segment_index, "Downloaded potentially useful pieces");
801
802            self.acknowledge_archived_segment_processing(segment_index)
803                .await;
804
805            // Go through potentially matching pieces again now that segment was acknowledged and
806            // try to persist them if necessary
807            for (piece_index, piece) in pieces_to_maybe_include {
808                if !self
809                    .plot_caches
810                    .store_additional_piece(piece_index, &piece)
811                    .await
812                {
813                    trace!(%piece_index, "Piece could not be cached in plot cache");
814                }
815
816                if !self
817                    .piece_caches
818                    .read()
819                    .await
820                    .should_include_key(self.peer_id, piece_index)
821                {
822                    trace!(%piece_index, "Piece doesn't need to be cached #2");
823
824                    continue;
825                }
826
827                trace!(%piece_index, "Piece needs to be cached #1");
828
829                self.persist_piece_in_cache(piece_index, piece).await;
830            }
831
832            *last_segment_index_internal = segment_index;
833        } else {
834            self.acknowledge_archived_segment_processing(segment_index)
835                .await;
836        }
837
838        debug!(%segment_index, "Finished processing newly archived segment");
839    }
840
841    async fn acknowledge_archived_segment_processing(&self, segment_index: SegmentIndex) {
842        match self
843            .node_client
844            .acknowledge_archived_segment_header(segment_index)
845            .await
846        {
847            Ok(()) => {
848                debug!(%segment_index, "Acknowledged archived segment");
849            }
850            Err(error) => {
851                error!(%segment_index, ?error, "Failed to acknowledge archived segment");
852            }
853        };
854    }
855
856    async fn keep_up_after_initial_sync<PG>(
857        &self,
858        piece_getter: &PG,
859        last_segment_index_internal: &mut SegmentIndex,
860    ) where
861        PG: PieceGetter,
862    {
863        let last_segment_index = match self.node_client.farmer_app_info().await {
864            Ok(farmer_app_info) => farmer_app_info.protocol_info.history_size.segment_index(),
865            Err(error) => {
866                error!(
867                    %error,
868                    "Failed to get farmer app info from node, keeping old cache state without \
869                    updates"
870                );
871                return;
872            }
873        };
874
875        if last_segment_index <= *last_segment_index_internal {
876            return;
877        }
878
879        info!(
880            "Syncing piece cache to the latest history size, this may pause block production if \
881            takes too long"
882        );
883
884        // Keep up with segment indices that were potentially created since reinitialization
885        let piece_indices = (*last_segment_index_internal..=last_segment_index)
886            .flat_map(|segment_index| segment_index.segment_piece_indexes());
887
888        // TODO: Download pieces concurrently
889        for piece_index in piece_indices {
890            if !self
891                .piece_caches
892                .read()
893                .await
894                .should_include_key(self.peer_id, piece_index)
895            {
896                trace!(%piece_index, "Piece doesn't need to be cached #3");
897
898                continue;
899            }
900
901            trace!(%piece_index, "Piece needs to be cached #2");
902
903            let result = piece_getter.get_piece(piece_index).await;
904
905            let piece = match result {
906                Ok(Some(piece)) => piece,
907                Ok(None) => {
908                    debug!(%piece_index, "Couldn't find piece");
909                    continue;
910                }
911                Err(error) => {
912                    debug!(
913                        %error,
914                        %piece_index,
915                        "Failed to get piece for piece cache"
916                    );
917                    continue;
918                }
919            };
920
921            self.persist_piece_in_cache(piece_index, piece).await;
922        }
923
924        info!("Finished syncing piece cache to the latest history size");
925
926        *last_segment_index_internal = last_segment_index;
927    }
928
929    /// This assumes it was already checked that piece needs to be stored, no verification for this
930    /// is done internally and invariants will break if this assumption doesn't hold true
931    async fn persist_piece_in_cache(&self, piece_index: PieceIndex, piece: Piece) {
932        let key = KeyWithDistance::new(self.peer_id, piece_index.to_multihash());
933        let mut caches = self.piece_caches.write().await;
934        match caches.should_replace(&key) {
935            // Entry is already occupied, we need to find and replace old piece with new one
936            Some((old_key, offset)) => {
937                let cache_index = offset.cache_index;
938                let piece_offset = offset.piece_offset;
939                let Some(backend) = caches.get_backend(cache_index) else {
940                    // Cache backend not exist
941                    warn!(
942                        %cache_index,
943                        %piece_index,
944                        "Should have a cached backend, but it didn't exist, this is an \
945                        implementation bug"
946                    );
947                    return;
948                };
949                if let Err(error) = backend.write_piece(piece_offset, piece_index, &piece).await {
950                    error!(
951                        %error,
952                        %cache_index,
953                        %piece_index,
954                        %piece_offset,
955                        "Failed to write piece into cache"
956                    );
957                } else {
958                    let old_piece_index = decode_piece_index_from_record_key(old_key.record_key());
959                    trace!(
960                        %cache_index,
961                        %old_piece_index,
962                        %piece_index,
963                        %piece_offset,
964                        "Successfully replaced old cached piece"
965                    );
966                    caches.push_stored_piece(key, offset);
967                }
968            }
969            // There is free space in cache, need to find a free spot and place piece there
970            None => {
971                let Some(offset) = caches.pop_free_offset() else {
972                    warn!(
973                        %piece_index,
974                        "Should have inserted piece into cache, but it didn't happen, this is an \
975                        implementation bug"
976                    );
977                    return;
978                };
979                let cache_index = offset.cache_index;
980                let piece_offset = offset.piece_offset;
981                let Some(backend) = caches.get_backend(cache_index) else {
982                    // Cache backend not exist
983                    warn!(
984                        %cache_index,
985                        %piece_index,
986                        "Should have a cached backend, but it didn't exist, this is an \
987                        implementation bug"
988                    );
989                    return;
990                };
991
992                if let Err(error) = backend.write_piece(piece_offset, piece_index, &piece).await {
993                    error!(
994                        %error,
995                        %cache_index,
996                        %piece_index,
997                        %piece_offset,
998                        "Failed to write piece into cache"
999                    );
1000                } else {
1001                    trace!(
1002                        %cache_index,
1003                        %piece_index,
1004                        %piece_offset,
1005                        "Successfully stored piece in cache"
1006                    );
1007                    if let Some(metrics) = &self.metrics {
1008                        metrics.piece_cache_capacity_used.inc();
1009                    }
1010                    caches.push_stored_piece(key, offset);
1011                }
1012            }
1013        };
1014    }
1015}
1016
1017#[derive(Debug)]
1018struct PlotCaches {
1019    /// Additional piece caches
1020    caches: AsyncRwLock<Vec<Arc<dyn PlotCache>>>,
1021    /// Next plot cache to use for storing pieces
1022    next_plot_cache: AtomicUsize,
1023}
1024
1025impl PlotCaches {
1026    /// Returns true if there might be space to add a piece to a cache.
1027    /// Returns false if it is already in a cache, or it can't be added to any of the caches.
1028    ///
1029    /// Available space can be overwritten by a sector at any time, so the piece write can still
1030    /// fail even if this returns `true`.
1031    async fn should_store(&self, piece_index: PieceIndex, key: &RecordKey) -> bool {
1032        for (cache_index, cache) in self.caches.read().await.iter().enumerate() {
1033            match cache.is_piece_maybe_stored(key).await {
1034                Ok(MaybePieceStoredResult::No) => {
1035                    // Isn't stored or can't be stored, try another cache if there is one
1036                }
1037                Ok(MaybePieceStoredResult::Vacant) => {
1038                    return true;
1039                }
1040                Ok(MaybePieceStoredResult::Yes) => {
1041                    // Already stored, nothing else left to do
1042                    return false;
1043                }
1044                Err(error) => {
1045                    warn!(
1046                        %cache_index,
1047                        %piece_index,
1048                        %error,
1049                        "Failed to check piece stored in cache"
1050                    );
1051                }
1052            }
1053        }
1054
1055        false
1056    }
1057
1058    /// Store a piece in additional downloaded pieces, if there is space for it.
1059    /// Returns `true` if the piece was added to a cache, and `false` if it couldn't be stored,
1060    /// typically because the cache is full.
1061    async fn store_additional_piece(&self, piece_index: PieceIndex, piece: &Piece) -> bool {
1062        let plot_caches = self.caches.read().await;
1063        let plot_caches_len = plot_caches.len();
1064
1065        // Store pieces in plots using round-robin distribution
1066        for _ in 0..plot_caches_len {
1067            let plot_cache_index =
1068                self.next_plot_cache.fetch_add(1, Ordering::Relaxed) % plot_caches_len;
1069
1070            match plot_caches[plot_cache_index]
1071                .try_store_piece(piece_index, piece)
1072                .await
1073            {
1074                Ok(true) => {
1075                    return true;
1076                }
1077                Ok(false) => {
1078                    continue;
1079                }
1080                Err(error) => {
1081                    error!(
1082                        %error,
1083                        %piece_index,
1084                        %plot_cache_index,
1085                        "Failed to store additional piece in cache"
1086                    );
1087                    continue;
1088                }
1089            }
1090        }
1091
1092        false
1093    }
1094}
1095
1096/// Farmer cache that aggregates different kinds of caches of multiple disks.
1097///
1098/// Pieces in [`PieceCache`] are stored based on capacity and proximity of piece index to farmer's
1099/// network identity. If capacity is not enough to store all pieces in cache then pieces that are
1100/// further from network identity will be evicted, this is helpful for quick retrieval of pieces
1101/// from DSN as well as plotting purposes.
1102///
1103/// [`PlotCache`] is used as a supplementary cache and is primarily helpful for smaller farmers
1104/// where piece cache is not enough to store all the pieces on the network, while there is a lot of
1105/// space in the plot that is not used by sectors yet and can be leverage as extra caching space.
1106#[derive(Debug, Clone)]
1107pub struct FarmerCache {
1108    peer_id: PeerId,
1109    /// Individual dedicated piece caches
1110    piece_caches: Arc<AsyncRwLock<PieceCachesState>>,
1111    /// Additional piece caches
1112    plot_caches: Arc<PlotCaches>,
1113    handlers: Arc<Handlers>,
1114    // We do not want to increase capacity unnecessarily on clone
1115    worker_sender: mpsc::Sender<WorkerCommand>,
1116    metrics: Option<Arc<FarmerCacheMetrics>>,
1117}
1118
1119impl FarmerCache {
1120    /// Create new piece cache instance and corresponding worker.
1121    ///
1122    /// NOTE: Returned future is async, but does blocking operations and should be running in
1123    /// dedicated thread.
1124    pub fn new<NC>(
1125        node_client: NC,
1126        peer_id: PeerId,
1127        registry: Option<&mut Registry>,
1128    ) -> (Self, FarmerCacheWorker<NC>)
1129    where
1130        NC: NodeClient,
1131    {
1132        let caches = Arc::default();
1133        let (worker_sender, worker_receiver) = mpsc::channel(WORKER_CHANNEL_CAPACITY);
1134        let handlers = Arc::new(Handlers::default());
1135
1136        let plot_caches = Arc::new(PlotCaches {
1137            caches: AsyncRwLock::default(),
1138            next_plot_cache: AtomicUsize::new(0),
1139        });
1140        let metrics = registry.map(|registry| Arc::new(FarmerCacheMetrics::new(registry)));
1141
1142        let instance = Self {
1143            peer_id,
1144            piece_caches: Arc::clone(&caches),
1145            plot_caches: Arc::clone(&plot_caches),
1146            handlers: Arc::clone(&handlers),
1147            worker_sender,
1148            metrics: metrics.clone(),
1149        };
1150        let worker = FarmerCacheWorker {
1151            peer_id,
1152            node_client,
1153            piece_caches: caches,
1154            plot_caches,
1155            handlers,
1156            worker_receiver: Some(worker_receiver),
1157            metrics,
1158        };
1159
1160        (instance, worker)
1161    }
1162
1163    /// Get piece from cache
1164    pub async fn get_piece<Key>(&self, key: Key) -> Option<Piece>
1165    where
1166        RecordKey: From<Key>,
1167    {
1168        let key = RecordKey::from(key);
1169        let maybe_piece_found = {
1170            let key = KeyWithDistance::new_with_record_key(self.peer_id, key.clone());
1171            let caches = self.piece_caches.read().await;
1172
1173            caches.get_stored_piece(&key).and_then(|offset| {
1174                let cache_index = offset.cache_index;
1175                let piece_offset = offset.piece_offset;
1176                Some((
1177                    piece_offset,
1178                    cache_index,
1179                    caches.get_backend(cache_index)?.clone(),
1180                ))
1181            })
1182        };
1183
1184        if let Some((piece_offset, cache_index, backend)) = maybe_piece_found {
1185            match backend.read_piece(piece_offset).await {
1186                Ok(maybe_piece) => {
1187                    return match maybe_piece {
1188                        Some((_piece_index, piece)) => {
1189                            if let Some(metrics) = &self.metrics {
1190                                metrics.cache_get_hit.inc();
1191                            }
1192                            Some(piece)
1193                        }
1194                        None => {
1195                            error!(
1196                                %cache_index,
1197                                %piece_offset,
1198                                ?key,
1199                                "Piece was expected to be in cache, but wasn't found there"
1200                            );
1201                            if let Some(metrics) = &self.metrics {
1202                                metrics.cache_get_error.inc();
1203                            }
1204                            None
1205                        }
1206                    };
1207                }
1208                Err(error) => {
1209                    error!(
1210                        %error,
1211                        %cache_index,
1212                        ?key,
1213                        %piece_offset,
1214                        "Error while reading piece from cache"
1215                    );
1216
1217                    if let Err(error) = self
1218                        .worker_sender
1219                        .clone()
1220                        .send(WorkerCommand::ForgetKey { key })
1221                        .await
1222                    {
1223                        trace!(%error, "Failed to send ForgetKey command to worker");
1224                    }
1225
1226                    if let Some(metrics) = &self.metrics {
1227                        metrics.cache_get_error.inc();
1228                    }
1229                    return None;
1230                }
1231            }
1232        }
1233
1234        for cache in self.plot_caches.caches.read().await.iter() {
1235            if let Ok(Some(piece)) = cache.read_piece(&key).await {
1236                if let Some(metrics) = &self.metrics {
1237                    metrics.cache_get_hit.inc();
1238                }
1239                return Some(piece);
1240            }
1241        }
1242
1243        if let Some(metrics) = &self.metrics {
1244            metrics.cache_get_miss.inc();
1245        }
1246        None
1247    }
1248
1249    /// Get pieces from cache.
1250    ///
1251    /// Number of elements in returned stream is the same as number of unique `piece_indices`.
1252    pub async fn get_pieces<'a, PieceIndices>(
1253        &'a self,
1254        piece_indices: PieceIndices,
1255    ) -> impl Stream<Item = (PieceIndex, Option<Piece>)> + Send + Unpin + 'a
1256    where
1257        PieceIndices: IntoIterator<Item = PieceIndex, IntoIter: Send + 'a> + Send + 'a,
1258    {
1259        let mut pieces_to_get_from_plot_cache = Vec::new();
1260
1261        let pieces_to_read_from_piece_cache = {
1262            let caches = self.piece_caches.read().await;
1263            // Pieces to read from piece cache grouped by backend for efficiency reasons
1264            let mut pieces_to_read_from_piece_cache =
1265                HashMap::<CacheIndex, (CacheBackend, HashMap<_, _>)>::new();
1266
1267            for piece_index in piece_indices {
1268                let key = RecordKey::from(piece_index.to_multihash());
1269
1270                let offset = match caches.get_stored_piece(&KeyWithDistance::new_with_record_key(
1271                    self.peer_id,
1272                    key.clone(),
1273                )) {
1274                    Some(offset) => offset,
1275                    None => {
1276                        pieces_to_get_from_plot_cache.push((piece_index, key));
1277                        continue;
1278                    }
1279                };
1280
1281                let cache_index = offset.cache_index;
1282                let piece_offset = offset.piece_offset;
1283
1284                match pieces_to_read_from_piece_cache.entry(cache_index) {
1285                    Entry::Occupied(mut entry) => {
1286                        let (_backend, pieces) = entry.get_mut();
1287                        pieces.insert(piece_offset, (piece_index, key));
1288                    }
1289                    Entry::Vacant(entry) => {
1290                        let backend = match caches.get_backend(cache_index) {
1291                            Some(backend) => backend.clone(),
1292                            None => {
1293                                pieces_to_get_from_plot_cache.push((piece_index, key));
1294                                continue;
1295                            }
1296                        };
1297                        entry
1298                            .insert((backend, HashMap::from([(piece_offset, (piece_index, key))])));
1299                    }
1300                }
1301            }
1302
1303            pieces_to_read_from_piece_cache
1304        };
1305
1306        let (tx, mut rx) = mpsc::unbounded();
1307
1308        let fut = async move {
1309            let tx = &tx;
1310
1311            let mut reading_from_piece_cache = pieces_to_read_from_piece_cache
1312                .into_iter()
1313                .map(|(cache_index, (backend, mut pieces_to_get))| async move {
1314                    let mut pieces_stream = match backend
1315                        .read_pieces(Box::new(
1316                            pieces_to_get
1317                                .keys()
1318                                .copied()
1319                                .collect::<Vec<_>>()
1320                                .into_iter(),
1321                        ))
1322                        .await
1323                    {
1324                        Ok(pieces_stream) => pieces_stream,
1325                        Err(error) => {
1326                            error!(
1327                                %error,
1328                                %cache_index,
1329                                "Error while reading pieces from cache"
1330                            );
1331
1332                            if let Some(metrics) = &self.metrics {
1333                                metrics.cache_get_error.inc_by(pieces_to_get.len() as u64);
1334                            }
1335                            for (piece_index, _key) in pieces_to_get.into_values() {
1336                                tx.unbounded_send((piece_index, None)).expect(
1337                                    "This future isn't polled after receiver is dropped; qed",
1338                                );
1339                            }
1340                            return;
1341                        }
1342                    };
1343
1344                    while let Some(maybe_piece) = pieces_stream.next().await {
1345                        let result = match maybe_piece {
1346                            Ok((piece_offset, Some((piece_index, piece)))) => {
1347                                pieces_to_get.remove(&piece_offset);
1348
1349                                if let Some(metrics) = &self.metrics {
1350                                    metrics.cache_get_hit.inc();
1351                                }
1352                                (piece_index, Some(piece))
1353                            }
1354                            Ok((piece_offset, None)) => {
1355                                let Some((piece_index, key)) = pieces_to_get.remove(&piece_offset)
1356                                else {
1357                                    debug!(
1358                                        %cache_index,
1359                                        %piece_offset,
1360                                        "Received piece offset that was not expected"
1361                                    );
1362                                    continue;
1363                                };
1364
1365                                error!(
1366                                    %cache_index,
1367                                    %piece_index,
1368                                    %piece_offset,
1369                                    ?key,
1370                                    "Piece was expected to be in cache, but wasn't found there"
1371                                );
1372                                if let Some(metrics) = &self.metrics {
1373                                    metrics.cache_get_error.inc();
1374                                }
1375                                (piece_index, None)
1376                            }
1377                            Err(error) => {
1378                                error!(
1379                                    %error,
1380                                    %cache_index,
1381                                    "Error while reading piece from cache"
1382                                );
1383
1384                                if let Some(metrics) = &self.metrics {
1385                                    metrics.cache_get_error.inc();
1386                                }
1387                                continue;
1388                            }
1389                        };
1390
1391                        tx.unbounded_send(result)
1392                            .expect("This future isn't polled after receiver is dropped; qed");
1393                    }
1394
1395                    if pieces_to_get.is_empty() {
1396                        return;
1397                    }
1398
1399                    if let Some(metrics) = &self.metrics {
1400                        metrics.cache_get_error.inc_by(pieces_to_get.len() as u64);
1401                    }
1402                    for (piece_offset, (piece_index, key)) in pieces_to_get {
1403                        error!(
1404                            %cache_index,
1405                            %piece_index,
1406                            %piece_offset,
1407                            ?key,
1408                            "Piece cache didn't return an entry for offset"
1409                        );
1410
1411                        // Uphold invariant of the method that some result should be returned
1412                        // for every unique piece index
1413                        tx.unbounded_send((piece_index, None))
1414                            .expect("This future isn't polled after receiver is dropped; qed");
1415                    }
1416                })
1417                .collect::<FuturesUnordered<_>>();
1418            // TODO: Can't use this due to https://github.com/rust-lang/rust/issues/64650
1419            // Simply drain everything
1420            // .for_each(|()| async {})
1421
1422            // TODO: Remove once https://github.com/rust-lang/rust/issues/64650 is resolved
1423            let reading_from_piece_cache_fut = async move {
1424                while let Some(()) = reading_from_piece_cache.next().await {
1425                    // Simply drain everything
1426                }
1427            };
1428
1429            let reading_from_plot_cache_fut = async {
1430                if pieces_to_get_from_plot_cache.is_empty() {
1431                    return;
1432                }
1433
1434                for cache in self.plot_caches.caches.read().await.iter() {
1435                    // Iterating over offsets in reverse order to both traverse elements in async code
1436                    // and being able to efficiently remove entries without extra allocations
1437                    for offset in (0..pieces_to_get_from_plot_cache.len()).rev() {
1438                        let (piece_index, key) = &pieces_to_get_from_plot_cache[offset];
1439
1440                        if let Ok(Some(piece)) = cache.read_piece(key).await {
1441                            if let Some(metrics) = &self.metrics {
1442                                metrics.cache_get_hit.inc();
1443                            }
1444                            tx.unbounded_send((*piece_index, Some(piece)))
1445                                .expect("This future isn't polled after receiver is dropped; qed");
1446
1447                            // Due to iteration in reverse order and swapping using elements at the end,
1448                            // this doesn't affect processing of the elements
1449                            pieces_to_get_from_plot_cache.swap_remove(offset);
1450                        }
1451                    }
1452
1453                    if pieces_to_get_from_plot_cache.is_empty() {
1454                        return;
1455                    }
1456                }
1457
1458                if let Some(metrics) = &self.metrics {
1459                    metrics
1460                        .cache_get_miss
1461                        .inc_by(pieces_to_get_from_plot_cache.len() as u64);
1462                }
1463
1464                for (piece_index, _key) in pieces_to_get_from_plot_cache {
1465                    tx.unbounded_send((piece_index, None))
1466                        .expect("This future isn't polled after receiver is dropped; qed");
1467                }
1468            };
1469
1470            join!(reading_from_piece_cache_fut, reading_from_plot_cache_fut).await
1471        };
1472        let mut fut = Box::pin(fut.fuse());
1473
1474        // Drive above future and stream back any pieces that were downloaded so far
1475        stream::poll_fn(move |cx| {
1476            if !fut.is_terminated() {
1477                // Result doesn't matter, we'll need to poll stream below anyway
1478                let _ = fut.poll_unpin(cx);
1479            }
1480
1481            if let Poll::Ready(maybe_result) = rx.poll_next_unpin(cx) {
1482                return Poll::Ready(maybe_result);
1483            }
1484
1485            // Exit will be done by the stream above
1486            Poll::Pending
1487        })
1488    }
1489
1490    /// Returns a filtered list of pieces that were found in farmer cache, order is not guaranteed
1491    pub async fn has_pieces(&self, mut piece_indices: Vec<PieceIndex>) -> Vec<PieceIndex> {
1492        let mut pieces_to_find = HashMap::<PieceIndex, RecordKey>::from_iter(
1493            piece_indices
1494                .iter()
1495                .map(|piece_index| (*piece_index, RecordKey::from(piece_index.to_multihash()))),
1496        );
1497
1498        // Quick check in piece caches
1499        {
1500            let piece_caches = self.piece_caches.read().await;
1501            pieces_to_find.retain(|_piece_index, key| {
1502                let distance_key = KeyWithDistance::new(self.peer_id, key.clone());
1503                !piece_caches.contains_stored_piece(&distance_key)
1504            });
1505        }
1506
1507        // Early exit if everything is cached
1508        if pieces_to_find.is_empty() {
1509            return piece_indices;
1510        }
1511
1512        // Check plot caches concurrently
1513        if let Some(plot_caches) = self.plot_caches.caches.try_read() {
1514            let plot_caches = &plot_caches;
1515            let not_found = pieces_to_find
1516                .into_iter()
1517                .map(|(piece_index, key)| async move {
1518                    let key = &key;
1519
1520                    let found = plot_caches
1521                        .iter()
1522                        .map(|plot_cache| async {
1523                            matches!(
1524                                plot_cache.is_piece_maybe_stored(key).await,
1525                                Ok(MaybePieceStoredResult::Yes)
1526                            )
1527                        })
1528                        .collect::<FuturesUnordered<_>>()
1529                        .any(|found| async move { found })
1530                        .await;
1531
1532                    if found { None } else { Some(piece_index) }
1533                })
1534                .collect::<FuturesUnordered<_>>()
1535                .filter_map(|maybe_piece_index| async move { maybe_piece_index })
1536                .collect::<HashSet<_>>()
1537                .await;
1538            piece_indices.retain(|piece_index| !not_found.contains(piece_index));
1539        }
1540        piece_indices
1541    }
1542
1543    /// Find piece in cache and return its retrieval details
1544    pub async fn find_piece(
1545        &self,
1546        piece_index: PieceIndex,
1547    ) -> Option<(PieceCacheId, PieceCacheOffset)> {
1548        let caches = self.piece_caches.read().await;
1549
1550        self.find_piece_internal(&caches, piece_index)
1551    }
1552
1553    /// Find pieces in cache and return their retrieval details
1554    pub async fn find_pieces<PieceIndices>(
1555        &self,
1556        piece_indices: PieceIndices,
1557    ) -> Vec<(PieceIndex, PieceCacheId, PieceCacheOffset)>
1558    where
1559        PieceIndices: IntoIterator<Item = PieceIndex>,
1560    {
1561        let caches = self.piece_caches.read().await;
1562
1563        piece_indices
1564            .into_iter()
1565            .filter_map(|piece_index| {
1566                self.find_piece_internal(&caches, piece_index)
1567                    .map(|(cache_id, piece_offset)| (piece_index, cache_id, piece_offset))
1568            })
1569            .collect()
1570    }
1571
1572    fn find_piece_internal(
1573        &self,
1574        caches: &PieceCachesState,
1575        piece_index: PieceIndex,
1576    ) -> Option<(PieceCacheId, PieceCacheOffset)> {
1577        let key = KeyWithDistance::new(self.peer_id, piece_index.to_multihash());
1578
1579        let Some(offset) = caches.get_stored_piece(&key) else {
1580            if let Some(metrics) = &self.metrics {
1581                metrics.cache_find_miss.inc();
1582            }
1583
1584            return None;
1585        };
1586        let piece_offset = offset.piece_offset;
1587
1588        if let Some(backend) = caches.get_backend(offset.cache_index) {
1589            if let Some(metrics) = &self.metrics {
1590                metrics.cache_find_hit.inc();
1591            }
1592            return Some((*backend.id(), piece_offset));
1593        }
1594
1595        if let Some(metrics) = &self.metrics {
1596            metrics.cache_find_miss.inc();
1597        }
1598        None
1599    }
1600
1601    /// Try to store a piece in additional downloaded pieces, if there is space for it.
1602    /// Returns `true` if the piece was added to this cache, and `false` if it was already stored,
1603    /// or there was no space.
1604    pub async fn maybe_store_additional_piece(
1605        &self,
1606        piece_index: PieceIndex,
1607        piece: &Piece,
1608    ) -> bool {
1609        let key = RecordKey::from(piece_index.to_multihash());
1610
1611        let should_store = self.plot_caches.should_store(piece_index, &key).await;
1612
1613        if !should_store {
1614            return false;
1615        }
1616
1617        self.plot_caches
1618            .store_additional_piece(piece_index, piece)
1619            .await
1620    }
1621
1622    /// Initialize replacement of backing caches
1623    pub async fn replace_backing_caches(
1624        &self,
1625        new_piece_caches: Vec<Arc<dyn PieceCache>>,
1626        new_plot_caches: Vec<Arc<dyn PlotCache>>,
1627    ) {
1628        if let Err(error) = self
1629            .worker_sender
1630            .clone()
1631            .send(WorkerCommand::ReplaceBackingCaches { new_piece_caches })
1632            .await
1633        {
1634            warn!(%error, "Failed to replace backing caches, worker exited");
1635        }
1636
1637        *self.plot_caches.caches.write().await = new_plot_caches;
1638    }
1639
1640    /// Subscribe to cache sync notifications
1641    pub fn on_sync_progress(&self, callback: HandlerFn<f32>) -> HandlerId {
1642        self.handlers.progress.add(callback)
1643    }
1644}
1645
1646/// Collection of [`FarmerCache`] instances for load balancing
1647#[derive(Debug, Clone)]
1648pub struct FarmerCaches {
1649    caches: Arc<[FarmerCache]>,
1650}
1651
1652impl From<Arc<[FarmerCache]>> for FarmerCaches {
1653    fn from(caches: Arc<[FarmerCache]>) -> Self {
1654        Self { caches }
1655    }
1656}
1657
1658impl From<FarmerCache> for FarmerCaches {
1659    fn from(cache: FarmerCache) -> Self {
1660        Self {
1661            caches: Arc::new([cache]),
1662        }
1663    }
1664}
1665
1666impl FarmerCaches {
1667    /// Get piece from cache
1668    pub async fn get_piece<Key>(&self, key: Key) -> Option<Piece>
1669    where
1670        RecordKey: From<Key>,
1671    {
1672        let farmer_cache = self.caches.choose(&mut rand::rng())?;
1673        farmer_cache.get_piece(key).await
1674    }
1675
1676    /// Get pieces from cache.
1677    ///
1678    /// Number of elements in returned stream is the same as number of unique `piece_indices`.
1679    pub async fn get_pieces<'a, PieceIndices>(
1680        &'a self,
1681        piece_indices: PieceIndices,
1682    ) -> impl Stream<Item = (PieceIndex, Option<Piece>)> + Send + Unpin + 'a
1683    where
1684        PieceIndices: IntoIterator<Item = PieceIndex, IntoIter: Send + 'a> + Send + 'a,
1685    {
1686        let Some(farmer_cache) = self.caches.choose(&mut rand::rng()) else {
1687            return Either::Left(stream::iter(
1688                piece_indices
1689                    .into_iter()
1690                    .map(|piece_index| (piece_index, None)),
1691            ));
1692        };
1693
1694        Either::Right(farmer_cache.get_pieces(piece_indices).await)
1695    }
1696
1697    /// Returns a filtered list of pieces that were found in farmer cache, order is not guaranteed
1698    pub async fn has_pieces(&self, piece_indices: Vec<PieceIndex>) -> Vec<PieceIndex> {
1699        let Some(farmer_cache) = self.caches.choose(&mut rand::rng()) else {
1700            return Vec::new();
1701        };
1702
1703        farmer_cache.has_pieces(piece_indices).await
1704    }
1705
1706    /// Try to store a piece in additional downloaded pieces, if there is space for it.
1707    /// Returns `true` if the piece was added to one or more caches, and `false` if it was already
1708    /// stored, or there was no space.
1709    pub async fn maybe_store_additional_piece(
1710        &self,
1711        piece_index: PieceIndex,
1712        piece: &Piece,
1713    ) -> bool {
1714        // Run all the futures to completion, and take a non-short-circuiting any() on the results.
1715        self.caches
1716            .iter()
1717            .map(|farmer_cache| farmer_cache.maybe_store_additional_piece(piece_index, piece))
1718            .collect::<FuturesUnordered<_>>()
1719            .fold::<bool, _, _>(false, |acc, stored| async move { acc || stored })
1720            .await
1721    }
1722}
1723
1724/// Extracts the `PieceIndex` from a `RecordKey`.
1725fn decode_piece_index_from_record_key(key: &RecordKey) -> PieceIndex {
1726    let len = key.as_ref().len();
1727    let s = len - PieceIndex::SIZE;
1728
1729    let mut piece_index_bytes = [0u8; PieceIndex::SIZE];
1730    piece_index_bytes.copy_from_slice(&key.as_ref()[s..]);
1731
1732    PieceIndex::from_bytes(piece_index_bytes)
1733}