Skip to main content

subspace_data_retrieval/
segment_downloading.rs

1//! Fetching segments of the archived history of Subspace Network.
2
3use crate::piece_getter::PieceGetter;
4use futures::StreamExt;
5use std::time::Duration;
6use subspace_archiving::archiver::Segment;
7use subspace_archiving::reconstructor::{Reconstructor, ReconstructorError};
8use subspace_core_primitives::pieces::Piece;
9use subspace_core_primitives::segments::{
10    ArchivedHistorySegment, RecordedHistorySegment, SegmentIndex,
11};
12use subspace_erasure_coding::ErasureCoding;
13use tokio::task::spawn_blocking;
14use tokio::time::sleep;
15use tracing::debug;
16
17/// The number of times we try to download a segment before giving up.
18/// This is a suggested default, callers can supply their own value if needed.
19pub const SEGMENT_DOWNLOAD_RETRIES: usize = 3;
20
21/// The amount of time we wait between segment download retries.
22/// This is a suggested default, callers can supply their own value if needed.
23pub const SEGMENT_DOWNLOAD_RETRY_DELAY: Duration = Duration::from_secs(10);
24
25/// Segment getter errors.
26#[derive(Debug, thiserror::Error)]
27pub enum SegmentDownloadingError {
28    /// Not enough pieces
29    #[error(
30        "Not enough ({downloaded_pieces}/{}) pieces for segment {segment_index}",
31        RecordedHistorySegment::NUM_RAW_RECORDS
32    )]
33    NotEnoughPieces {
34        /// The segment we were trying to download
35        segment_index: SegmentIndex,
36        /// Number of pieces that were downloaded
37        downloaded_pieces: usize,
38    },
39
40    /// Piece getter error
41    #[error("Piece getter error: {source}")]
42    PieceGetterError {
43        #[from]
44        source: anyhow::Error,
45    },
46
47    /// Segment reconstruction error
48    #[error("Segment reconstruction error: {source}")]
49    SegmentReconstruction {
50        #[from]
51        source: ReconstructorError,
52    },
53
54    /// Segment decoding error
55    #[error("Segment data decoding error: {source}")]
56    SegmentDecoding {
57        #[from]
58        source: parity_scale_codec::Error,
59    },
60}
61
62/// Concurrently downloads the pieces for `segment_index`, and reconstructs the segment.
63pub async fn download_segment<PG>(
64    segment_index: SegmentIndex,
65    piece_getter: &PG,
66    erasure_coding: ErasureCoding,
67    retries: usize,
68    retry_delay: Option<Duration>,
69) -> Result<Segment, SegmentDownloadingError>
70where
71    PG: PieceGetter,
72{
73    let reconstructor = Reconstructor::new(erasure_coding);
74
75    let segment_pieces =
76        download_segment_pieces(segment_index, piece_getter, retries, retry_delay).await?;
77
78    let segment =
79        spawn_blocking(move || reconstructor.reconstruct_segment(segment_pieces.as_slice()))
80            .await
81            .expect("Panic if blocking task panicked")?;
82
83    Ok(segment)
84}
85
86/// Downloads pieces of a segment so that segment can be reconstructed afterward.
87/// Repeatedly attempts to download pieces until the required number of pieces is reached.
88///
89/// Prefers source pieces if available, on error returns the number of available pieces.
90pub async fn download_segment_pieces<PG>(
91    segment_index: SegmentIndex,
92    piece_getter: &PG,
93    retries: usize,
94    retry_delay: Option<Duration>,
95) -> Result<Box<[Option<Piece>; ArchivedHistorySegment::NUM_PIECES]>, SegmentDownloadingError>
96where
97    PG: PieceGetter,
98{
99    let mut existing_pieces = Box::new([const { None }; ArchivedHistorySegment::NUM_PIECES]);
100
101    for retry in 0..=retries {
102        match download_missing_segment_pieces(segment_index, piece_getter, existing_pieces).await {
103            Ok(segment_pieces) => return Ok(segment_pieces),
104            Err((error, incomplete_segment_pieces)) => {
105                existing_pieces = incomplete_segment_pieces;
106
107                if retry < retries {
108                    debug!(
109                        %segment_index,
110                        %retry,
111                        ?retry_delay,
112                        ?error,
113                        "Failed to download segment pieces once, retrying"
114                    );
115                    if let Some(retry_delay) = retry_delay {
116                        // Wait before retrying to give the node a chance to find other peers
117                        sleep(retry_delay).await;
118                    }
119                }
120            }
121        }
122    }
123
124    debug!(
125        %segment_index,
126        %retries,
127        "Failed to download segment pieces"
128    );
129
130    Err(SegmentDownloadingError::NotEnoughPieces {
131        segment_index,
132        downloaded_pieces: existing_pieces
133            .iter()
134            .filter(|piece| piece.is_some())
135            .count(),
136    })
137}
138
139/// Tries to download pieces of a segment once, so that segment can be reconstructed afterward.
140/// Pieces that are already available are passed in `segment_pieces`, the rest are `None`.
141///
142/// Prefers source pieces if available, on error returns the incomplete piece download (including
143/// pieces that were already available).
144async fn download_missing_segment_pieces<PG>(
145    segment_index: SegmentIndex,
146    piece_getter: &PG,
147    mut segment_pieces: Box<[Option<Piece>; ArchivedHistorySegment::NUM_PIECES]>,
148) -> Result<
149    Box<[Option<Piece>; ArchivedHistorySegment::NUM_PIECES]>,
150    (
151        SegmentDownloadingError,
152        Box<[Option<Piece>; ArchivedHistorySegment::NUM_PIECES]>,
153    ),
154>
155where
156    PG: PieceGetter,
157{
158    let required_pieces_number = RecordedHistorySegment::NUM_RAW_RECORDS;
159    let mut downloaded_pieces = segment_pieces
160        .iter()
161        .filter(|piece| piece.is_some())
162        .count();
163
164    // Debugging failure patterns in piece downloads
165    let mut first_success = None;
166    let mut last_success = None;
167    let mut first_failure = None;
168    let mut last_failure = None;
169
170    let mut pieces_iter = segment_index
171        .segment_piece_indexes_source_first()
172        .into_iter();
173
174    // Download in batches until we get enough or exhaust available pieces
175    while !pieces_iter.is_empty() && downloaded_pieces != required_pieces_number {
176        let piece_indices = pieces_iter
177            .by_ref()
178            .filter(|piece_index| segment_pieces[piece_index.position() as usize].is_none())
179            .take(required_pieces_number - downloaded_pieces)
180            .collect();
181
182        let mut received_segment_pieces = match piece_getter.get_pieces(piece_indices).await {
183            Ok(pieces) => pieces,
184            Err(error) => return Err((error.into(), segment_pieces)),
185        };
186
187        while let Some((piece_index, result)) = received_segment_pieces.next().await {
188            match result {
189                Ok(Some(piece)) => {
190                    downloaded_pieces += 1;
191                    segment_pieces
192                        .get_mut(piece_index.position() as usize)
193                        .expect("Piece position is by definition within segment; qed")
194                        .replace(piece);
195
196                    if first_success.is_none() {
197                        first_success = Some(piece_index.position());
198                    }
199                    last_success = Some(piece_index.position());
200                }
201                // We often see an error where 127 pieces are downloaded successfully, but the
202                // other 129 fail. It seems like 1 request in a 128 piece batch fails, then 128
203                // single piece requests are made, and also fail.
204                // Delaying requests after a failure gives the node a chance to find other peers.
205                Ok(None) => {
206                    debug!(%piece_index, "Piece was not found");
207                    if first_failure.is_none() {
208                        first_failure = Some(piece_index.position());
209                    }
210                    last_failure = Some(piece_index.position());
211                }
212                Err(error) => {
213                    debug!(%error, %piece_index, "Failed to get piece");
214                    if first_failure.is_none() {
215                        first_failure = Some(piece_index.position());
216                    }
217                    last_failure = Some(piece_index.position());
218                }
219            }
220        }
221    }
222
223    if downloaded_pieces < required_pieces_number {
224        debug!(
225            %segment_index,
226            %downloaded_pieces,
227            %required_pieces_number,
228            // Piece positions that succeeded/failed
229            ?first_success,
230            ?last_success,
231            ?first_failure,
232            ?last_failure,
233            "Failed to retrieve pieces for segment"
234        );
235
236        return Err((
237            SegmentDownloadingError::NotEnoughPieces {
238                segment_index,
239                downloaded_pieces: segment_pieces
240                    .iter()
241                    .filter(|piece| piece.is_some())
242                    .count(),
243            },
244            segment_pieces,
245        ));
246    }
247
248    Ok(segment_pieces)
249}