Skip to main content

ab_farmer/node_client/
caching_proxy_node_client.rs

1//! Node client wrapper around another node client that caches some data for better performance and
2//! proxies other requests through
3
4use crate::node_client::{NodeClient, NodeClientExt};
5use crate::utils::AsyncJoinOnDrop;
6use ab_core_primitives::pieces::{Piece, PieceIndex};
7use ab_core_primitives::segments::{SegmentIndex, SuperSegmentHeader, SuperSegmentIndex};
8use ab_farmer_rpc_primitives::{
9    BlockSealInfo, BlockSealResponse, FarmerAppInfo, FarmerShardMembershipInfo,
10    MAX_SUPER_SEGMENT_HEADERS_PER_REQUEST, SlotInfo, SolutionResponse,
11};
12use async_lock::{
13    Mutex as AsyncMutex, RwLock as AsyncRwLock,
14    RwLockUpgradableReadGuardArc as AsyncRwLockUpgradableReadGuard,
15};
16use async_trait::async_trait;
17use futures::{FutureExt, Stream, StreamExt, select};
18use std::pin::Pin;
19use std::sync::Arc as StdArc;
20use std::time::{Duration, Instant};
21use tokio::sync::watch;
22use tokio_stream::wrappers::WatchStream;
23use tracing::{debug, info, trace, warn};
24use triomphe::Arc;
25
26const SEGMENT_HEADERS_SYNC_INTERVAL: Duration = Duration::from_secs(1);
27const FARMER_APP_INFO_DEDUPLICATION_WINDOW: Duration = Duration::from_secs(1);
28
29#[derive(Debug, Default)]
30struct SuperSegmentHeaders {
31    super_segment_headers: Vec<SuperSegmentHeader>,
32    last_synced: Option<Instant>,
33}
34
35impl SuperSegmentHeaders {
36    /// Push a new super segment header to the cache if it is the next super segment header.
37    /// Otherwise, skip the push.
38    fn push(&mut self, new_segment_header: SuperSegmentHeader) {
39        if self.super_segment_headers.len() as u64 == u64::from(new_segment_header.index.as_inner())
40        {
41            self.super_segment_headers.push(new_segment_header);
42        }
43    }
44
45    /// Get cached super segment headers for the given super segment indices.
46    ///
47    /// Returns `None` for super segment indices that are not in the cache.
48    fn get_super_segment_headers(
49        &self,
50        super_segment_indices: &[SuperSegmentIndex],
51    ) -> Vec<Option<SuperSegmentHeader>> {
52        super_segment_indices
53            .iter()
54            .map(|super_segment_index| {
55                self.super_segment_headers
56                    .get(u64::from(*super_segment_index) as usize)
57                    .copied()
58            })
59            .collect::<Vec<_>>()
60    }
61
62    /// Get the last `limit` super segment headers from the cache
63    fn last_super_segment_headers(&self, limit: u32) -> Vec<Option<SuperSegmentHeader>> {
64        self.super_segment_headers
65            .iter()
66            .rev()
67            .take(limit as usize)
68            .rev()
69            .copied()
70            .map(Some)
71            .collect()
72    }
73
74    // TODO: Maybe caching or more compact storage that points segment indices to super segments
75    //  when this is called thousands of times during replotting?
76    fn super_segment_header_for_segment_index(
77        &self,
78        segment_index: SegmentIndex,
79    ) -> Option<SuperSegmentHeader> {
80        let index = self
81            .super_segment_headers
82            .binary_search_by_key(&segment_index, |super_segment_header| {
83                super_segment_header.max_segment_index.as_inner()
84            })
85            .unwrap_or_else(|insert_index| insert_index);
86
87        let super_segment_header = self.super_segment_headers.get(index).copied()?;
88
89        super_segment_header
90            .segment_position(segment_index)
91            .is_some()
92            .then_some(super_segment_header)
93    }
94
95    /// Whether the last sync was too recent to sync again
96    fn is_sync_rate_limited(&self) -> bool {
97        self.last_synced
98            .is_some_and(|last_synced| last_synced.elapsed() < SEGMENT_HEADERS_SYNC_INTERVAL)
99    }
100
101    /// Get uncached headers from the node.
102    /// This only requires a read lock.
103    ///
104    /// Returns any extra super segment headers if the download succeeds, or an error if it fails.
105    /// The caller must write the returned super segment headers to the cache and reset the sync
106    /// rate-limit timer.
107    async fn request_uncached_headers<NC>(
108        &self,
109        client: &NC,
110    ) -> anyhow::Result<Vec<SuperSegmentHeader>>
111    where
112        NC: NodeClient,
113    {
114        let mut extra_super_segment_headers = Vec::new();
115        let mut super_segment_index_offset =
116            SuperSegmentIndex::from(self.super_segment_headers.len() as u64);
117        let segment_index_step =
118            SuperSegmentIndex::from(MAX_SUPER_SEGMENT_HEADERS_PER_REQUEST as u64);
119
120        'outer: loop {
121            let from = super_segment_index_offset;
122            let to = super_segment_index_offset + segment_index_step;
123            trace!(%from, %to, "Requesting super segment headers");
124
125            for maybe_super_segment_header in client
126                .super_segment_headers((from..to).collect::<Vec<_>>())
127                .await
128                .map_err(|error| {
129                    anyhow::anyhow!(
130                        "Failed to download super segment headers {from}..{to} from node: {error}"
131                    )
132                })?
133            {
134                let Some(super_segment_header) = maybe_super_segment_header else {
135                    // Reached non-existent super segment header
136                    break 'outer;
137                };
138
139                extra_super_segment_headers.push(super_segment_header);
140            }
141
142            super_segment_index_offset += segment_index_step;
143        }
144
145        Ok(extra_super_segment_headers)
146    }
147
148    /// Write the sync results to the cache, and reset the sync rate-limit timer.
149    fn write_cache(&mut self, extra_super_segment_headers: Vec<SuperSegmentHeader>) {
150        for super_segment_header in extra_super_segment_headers {
151            self.push(super_segment_header);
152        }
153        self.last_synced.replace(Instant::now());
154    }
155}
156
157/// Node client wrapper around another node client that caches some data for better performance and
158/// proxies other requests through.
159///
160/// NOTE: Archived segment acknowledgement is ignored in this client, all subscriptions are
161/// acknowledged implicitly and immediately.
162/// NOTE: Subscription messages that are not processed in time will be skipped for performance
163/// reasons!
164#[derive(Debug, Clone)]
165pub struct CachingProxyNodeClient<NC> {
166    inner: NC,
167    slot_info_receiver: watch::Receiver<Option<SlotInfo>>,
168    new_super_segment_headers_receiver: watch::Receiver<Option<SuperSegmentHeader>>,
169    block_sealing_receiver: watch::Receiver<Option<BlockSealInfo>>,
170    super_segment_headers: StdArc<AsyncRwLock<SuperSegmentHeaders>>,
171    last_farmer_app_info: Arc<AsyncMutex<(FarmerAppInfo, Instant)>>,
172    _background_task: Arc<AsyncJoinOnDrop<()>>,
173}
174
175impl<NC> CachingProxyNodeClient<NC>
176where
177    NC: NodeClient + Clone,
178{
179    /// Create a new instance
180    pub async fn new(client: NC) -> anyhow::Result<Self> {
181        let mut super_segment_headers = SuperSegmentHeaders::default();
182        let mut new_super_segments_notifications =
183            client.subscribe_new_super_segment_headers().await?;
184
185        info!("Downloading all super segment headers from node...");
186        // No locking is needed, we are the first and only instance right now.
187        let headers = super_segment_headers
188            .request_uncached_headers(&client)
189            .await?;
190        super_segment_headers.write_cache(headers);
191        info!("Downloaded all super segment headers from node successfully");
192
193        let super_segment_headers = StdArc::new(AsyncRwLock::new(super_segment_headers));
194
195        let (slot_info_sender, slot_info_receiver) = watch::channel(None::<SlotInfo>);
196        let slot_info_proxy_fut = {
197            let mut slot_info_subscription = client.subscribe_slot_info().await?;
198
199            async move {
200                let mut last_slot_number = None;
201                while let Some(slot_info) = slot_info_subscription.next().await {
202                    if let Some(last_slot_number) = last_slot_number
203                        && last_slot_number >= slot_info.slot
204                    {
205                        continue;
206                    }
207                    last_slot_number.replace(slot_info.slot);
208
209                    if let Err(error) = slot_info_sender.send(Some(slot_info)) {
210                        warn!(%error, "Failed to proxy slot info notification");
211                        return;
212                    }
213                }
214            }
215        };
216
217        let (new_super_segment_headers_sender, new_super_segment_headers_receiver) =
218            watch::channel(None::<SuperSegmentHeader>);
219        let super_segment_headers_maintenance_fut = {
220            let client = client.clone();
221            let super_segment_headers = StdArc::clone(&super_segment_headers);
222
223            async move {
224                let mut last_super_segment_index = None;
225                while let Some(new_segment_header) = new_super_segments_notifications.next().await {
226                    let super_segment_index = new_segment_header.index;
227                    trace!(?new_segment_header, "New super segment header notification");
228
229                    if let Some(last_super_segment_index) = last_super_segment_index
230                        && last_super_segment_index >= super_segment_index
231                    {
232                        continue;
233                    }
234                    last_super_segment_index.replace(super_segment_index);
235
236                    // Notifications are not guaranteed to be delivered (for example, they are
237                    // skipped when not processed in time or lost while the source is restarting),
238                    // download missing headers before handling this one to not end up with a gap
239                    loop {
240                        let cached_count = super_segment_headers
241                            .read()
242                            .await
243                            .super_segment_headers
244                            .len() as u64;
245                        if cached_count >= u64::from(super_segment_index.as_inner()) {
246                            break;
247                        }
248
249                        let result = super_segment_headers
250                            .read()
251                            .await
252                            .request_uncached_headers(&client)
253                            .await;
254                        match result {
255                            Ok(extra_super_segment_headers) => {
256                                if !extra_super_segment_headers.is_empty() {
257                                    super_segment_headers
258                                        .write()
259                                        .await
260                                        .write_cache(extra_super_segment_headers);
261                                    continue;
262                                }
263
264                                debug!(
265                                    %super_segment_index,
266                                    "Missing super segment headers are not available yet, \
267                                    retrying"
268                                );
269                            }
270                            Err(error) => {
271                                warn!(
272                                    %error,
273                                    %super_segment_index,
274                                    "Failed to download missing super segment headers, retrying"
275                                );
276                            }
277                        }
278
279                        tokio::time::sleep(SEGMENT_HEADERS_SYNC_INTERVAL).await;
280                    }
281
282                    // Usually already downloaded above, but the source might not have it yet
283                    super_segment_headers.write().await.push(new_segment_header);
284
285                    if let Err(error) =
286                        new_super_segment_headers_sender.send(Some(new_segment_header))
287                    {
288                        warn!(%error, "Failed to proxy new super segment header notification");
289                        return;
290                    }
291                }
292            }
293        };
294
295        let (block_sealing_sender, block_sealing_receiver) = watch::channel(None::<BlockSealInfo>);
296        let block_sealing_proxy_fut = {
297            let mut block_sealing_subscription = client.subscribe_block_sealing().await?;
298
299            async move {
300                while let Some(block_sealing_info) = block_sealing_subscription.next().await {
301                    if let Err(error) = block_sealing_sender.send(Some(block_sealing_info)) {
302                        warn!(%error, "Failed to proxy block sealing notification");
303                        return;
304                    }
305                }
306            }
307        };
308
309        let farmer_app_info = client
310            .farmer_app_info()
311            .await
312            .map_err(|error| anyhow::anyhow!("Failed to get farmer app info: {error}"))?;
313        let last_farmer_app_info = Arc::new(AsyncMutex::new((farmer_app_info, Instant::now())));
314
315        let background_task = tokio::spawn(async move {
316            select! {
317                () = slot_info_proxy_fut.fuse() => {},
318                () = super_segment_headers_maintenance_fut.fuse() => {},
319                () = block_sealing_proxy_fut.fuse() => {},
320            }
321        });
322
323        let node_client = Self {
324            inner: client,
325            slot_info_receiver,
326            new_super_segment_headers_receiver,
327            block_sealing_receiver,
328            super_segment_headers,
329            last_farmer_app_info,
330            _background_task: Arc::new(AsyncJoinOnDrop::new(background_task, true)),
331        };
332
333        Ok(node_client)
334    }
335}
336
337impl<NC> CachingProxyNodeClient<NC>
338where
339    NC: NodeClient,
340{
341    /// Sync cached super segment headers with the node, unless the last sync was too recent
342    async fn sync_super_segment_headers(&self) -> anyhow::Result<()> {
343        // If we took a write lock here, a queue of writers could starve all the readers, even if
344        // those writers are rate-limited. So we take an upgradable read lock for the rate limit
345        // check.
346        let super_segment_headers = self.super_segment_headers.upgradable_read_arc().await;
347
348        // Skip the sync if we're still within the sync rate limit
349        if super_segment_headers.is_sync_rate_limited() {
350            return Ok(());
351        }
352
353        let extra_super_segment_headers = super_segment_headers
354            .request_uncached_headers(&self.inner)
355            .await?;
356
357        if !extra_super_segment_headers.is_empty() {
358            // Need to update the cached super segment headers, so take the write lock
359            AsyncRwLockUpgradableReadGuard::upgrade(super_segment_headers)
360                .await
361                .write_cache(extra_super_segment_headers);
362        }
363
364        Ok(())
365    }
366}
367
368#[async_trait]
369impl<NC> NodeClient for CachingProxyNodeClient<NC>
370where
371    NC: NodeClient,
372{
373    async fn farmer_app_info(&self) -> anyhow::Result<FarmerAppInfo> {
374        let (last_farmer_app_info, last_farmer_app_info_request) =
375            &mut *self.last_farmer_app_info.lock().await;
376
377        if last_farmer_app_info_request.elapsed() > FARMER_APP_INFO_DEDUPLICATION_WINDOW {
378            let new_last_farmer_app_info = self.inner.farmer_app_info().await?;
379
380            *last_farmer_app_info = new_last_farmer_app_info;
381            *last_farmer_app_info_request = Instant::now();
382        }
383
384        Ok(last_farmer_app_info.clone())
385    }
386
387    async fn subscribe_slot_info(
388        &self,
389    ) -> anyhow::Result<Pin<Box<dyn Stream<Item = SlotInfo> + Send + 'static>>> {
390        Ok(Box::pin(
391            WatchStream::new(self.slot_info_receiver.clone())
392                .filter_map(|maybe_slot_info| async move { maybe_slot_info }),
393        ))
394    }
395
396    async fn submit_solution_response(
397        &self,
398        solution_response: SolutionResponse,
399    ) -> anyhow::Result<()> {
400        self.inner.submit_solution_response(solution_response).await
401    }
402
403    async fn subscribe_block_sealing(
404        &self,
405    ) -> anyhow::Result<Pin<Box<dyn Stream<Item = BlockSealInfo> + Send + 'static>>> {
406        Ok(Box::pin(
407            WatchStream::new(self.block_sealing_receiver.clone())
408                .filter_map(|maybe_block_sealing_info| async move { maybe_block_sealing_info }),
409        ))
410    }
411
412    async fn submit_block_seal(&self, block_seal: BlockSealResponse) -> anyhow::Result<()> {
413        self.inner.submit_block_seal(block_seal).await
414    }
415
416    async fn subscribe_new_super_segment_headers(
417        &self,
418    ) -> anyhow::Result<Pin<Box<dyn Stream<Item = SuperSegmentHeader> + Send + 'static>>> {
419        Ok(Box::pin(
420            WatchStream::new(self.new_super_segment_headers_receiver.clone())
421                .filter_map(|maybe_super_segment_header| async move { maybe_super_segment_header }),
422        ))
423    }
424
425    async fn super_segment_headers(
426        &self,
427        super_segment_indices: Vec<SuperSegmentIndex>,
428    ) -> anyhow::Result<Vec<Option<SuperSegmentHeader>>> {
429        let retrieved_super_segment_headers = self
430            .super_segment_headers
431            .read()
432            .await
433            .get_super_segment_headers(&super_segment_indices);
434
435        if retrieved_super_segment_headers.iter().all(Option::is_some) {
436            return Ok(retrieved_super_segment_headers);
437        }
438
439        // We might be missing a requested super segment header
440        self.sync_super_segment_headers().await?;
441
442        Ok(self
443            .super_segment_headers
444            .read()
445            .await
446            .get_super_segment_headers(&super_segment_indices))
447    }
448
449    async fn super_segment_header_for_segment_index(
450        &self,
451        segment_index: SegmentIndex,
452    ) -> anyhow::Result<Option<SuperSegmentHeader>> {
453        let maybe_super_segment_header = self
454            .super_segment_headers
455            .read()
456            .await
457            .super_segment_header_for_segment_index(segment_index);
458
459        if maybe_super_segment_header.is_some() {
460            return Ok(maybe_super_segment_header);
461        }
462
463        // Segments past the history size reported by the node don't exist yet, which is routinely
464        // the case for sector expiration checks, so the cache is only synced for segments the node
465        // should already have, like those of pieces being validated
466        let history_size = self
467            .last_farmer_app_info
468            .lock()
469            .await
470            .0
471            .protocol_info
472            .history_size;
473        if segment_index > history_size.segment_index() {
474            return Ok(None);
475        }
476
477        self.sync_super_segment_headers().await?;
478
479        Ok(self
480            .super_segment_headers
481            .read()
482            .await
483            .super_segment_header_for_segment_index(segment_index))
484    }
485
486    async fn piece(&self, piece_index: PieceIndex) -> anyhow::Result<Option<Piece>> {
487        self.inner.piece(piece_index).await
488    }
489
490    async fn update_shard_membership_info(
491        &self,
492        info: FarmerShardMembershipInfo,
493    ) -> anyhow::Result<()> {
494        self.inner.update_shard_membership_info(info).await
495    }
496}
497
498#[async_trait]
499impl<NC> NodeClientExt for CachingProxyNodeClient<NC>
500where
501    NC: NodeClientExt,
502{
503    async fn cached_super_segment_headers(
504        &self,
505        super_segment_indices: Vec<SuperSegmentIndex>,
506    ) -> anyhow::Result<Vec<Option<SuperSegmentHeader>>> {
507        // To avoid remote denial of service, we don't update the cache here because it is called
508        // from network code
509        Ok(self
510            .super_segment_headers
511            .read()
512            .await
513            .get_super_segment_headers(&super_segment_indices))
514    }
515
516    async fn last_super_segment_headers(
517        &self,
518        limit: u32,
519    ) -> anyhow::Result<Vec<Option<SuperSegmentHeader>>> {
520        Ok(self
521            .super_segment_headers
522            .read()
523            .await
524            .last_super_segment_headers(limit))
525    }
526}