Skip to main content

ab_farmer/cluster/
controller.rs

1//! Farming cluster controller
2//!
3//! Controller is responsible for managing farming cluster.
4//!
5//! This module exposes some data structures for NATS communication, custom piece getter and node
6//! client implementations designed to work with cluster controller and a service function to drive
7//! the backend part of the controller.
8
9pub mod caches;
10pub mod farms;
11mod stream_map;
12
13use crate::cluster::cache::{ClusterCacheReadPieceRequest, ClusterCacheReadPiecesRequest};
14use crate::cluster::nats_client::{
15    GenericBroadcast, GenericNotification, GenericRequest, GenericStreamRequest, NatsClient,
16};
17use crate::farm::{PieceCacheId, PieceCacheOffset};
18use crate::farmer_cache::FarmerCache;
19use crate::node_client::NodeClient;
20use ab_core_primitives::pieces::{Piece, PieceIndex};
21use ab_core_primitives::segments::{SegmentIndex, SuperSegmentHeader, SuperSegmentIndex};
22use ab_data_retrieval::piece_getter::PieceGetter;
23use ab_farmer_rpc_primitives::{
24    BlockSealInfo, BlockSealResponse, FarmerAppInfo, FarmerShardMembershipInfo, SlotInfo,
25    SolutionResponse,
26};
27use anyhow::anyhow;
28use async_nats::HeaderValue;
29use async_trait::async_trait;
30use futures::channel::mpsc;
31use futures::future::FusedFuture;
32use futures::stream::FuturesUnordered;
33use futures::{FutureExt, Stream, StreamExt, select, stream};
34use parity_scale_codec::{Decode, Encode};
35use parking_lot::Mutex;
36use rand::prelude::*;
37use std::collections::{HashMap, HashSet};
38use std::pin::Pin;
39use std::task::Poll;
40use tracing::{debug, error, trace, warn};
41use triomphe::Arc;
42
43/// Special "cache group" that all controllers subscribe to and that can be used to query any cache
44/// group. The cache group for each query is chosen at random.
45const GLOBAL_CACHE_GROUP: &str = "_";
46
47/// Broadcast sent by controllers requesting farmers to identify themselves
48#[derive(Debug, Copy, Clone, Encode, Decode)]
49pub struct ClusterControllerFarmerIdentifyBroadcast;
50
51impl GenericBroadcast for ClusterControllerFarmerIdentifyBroadcast {
52    const SUBJECT: &'static str = "ab.controller.farmer-identify";
53}
54
55/// Broadcast sent by controllers requesting caches in cache group to identify themselves
56#[derive(Debug, Copy, Clone, Encode, Decode)]
57pub struct ClusterControllerCacheIdentifyBroadcast;
58
59impl GenericBroadcast for ClusterControllerCacheIdentifyBroadcast {
60    /// `*` here stands for cache group
61    const SUBJECT: &'static str = "ab.controller.*.cache-identify";
62}
63
64/// Broadcast with slot info sent by controllers
65#[derive(Debug, Clone, Encode, Decode)]
66struct ClusterControllerSlotInfoBroadcast {
67    slot_info: SlotInfo,
68    instance: String,
69}
70
71impl GenericBroadcast for ClusterControllerSlotInfoBroadcast {
72    const SUBJECT: &'static str = "ab.controller.slot-info";
73
74    fn deterministic_message_id(&self) -> Option<HeaderValue> {
75        // TODO: Depending on answer in `https://github.com/nats-io/nats.docs/issues/663` this might
76        //  be simplified to just a slot number
77        Some(
78            HeaderValue::try_from(format!("slot-info-{}", self.slot_info.slot))
79                .expect("No `\r` or `\n`; qed"),
80        )
81    }
82}
83
84/// Broadcast with block sealing info by controllers
85#[derive(Debug, Clone, Encode, Decode)]
86struct ClusterControllerBlockSealingBroadcast {
87    block_sealing_info: BlockSealInfo,
88}
89
90impl GenericBroadcast for ClusterControllerBlockSealingBroadcast {
91    const SUBJECT: &'static str = "ab.controller.block-sealing-info";
92}
93
94/// Broadcast with new super segment headers by controllers
95#[derive(Debug, Clone, Encode, Decode)]
96struct ClusterControllerNewSuperSegmentHeaderBroadcast {
97    new_super_segment_header: SuperSegmentHeader,
98}
99
100impl GenericBroadcast for ClusterControllerNewSuperSegmentHeaderBroadcast {
101    const SUBJECT: &'static str = "ab.controller.new-super-segment-header";
102
103    fn deterministic_message_id(&self) -> Option<HeaderValue> {
104        // TODO: Depending on answer in `https://github.com/nats-io/nats.docs/issues/663` this might
105        //  be simplified to just a super segment index
106        Some(
107            HeaderValue::try_from(format!(
108                "new-super-segment-{}",
109                self.new_super_segment_header.index
110            ))
111            .expect("No `\r` or `\n`; qed"),
112        )
113    }
114}
115
116/// Notification messages with solution by farmers
117#[derive(Debug, Clone, Encode, Decode)]
118struct ClusterControllerSolutionNotification {
119    solution_response: SolutionResponse,
120}
121
122impl GenericNotification for ClusterControllerSolutionNotification {
123    const SUBJECT: &'static str = "ab.controller.*.solution";
124}
125
126/// Notification messages with block seal by farmers
127#[derive(Debug, Clone, Encode, Decode)]
128struct ClusterControllerBlockSealNotification {
129    block_seal: BlockSealResponse,
130}
131
132impl GenericNotification for ClusterControllerBlockSealNotification {
133    const SUBJECT: &'static str = "ab.controller.block-seal";
134}
135
136/// Request farmer app info from controller
137#[derive(Debug, Clone, Encode, Decode)]
138struct ClusterControllerFarmerAppInfoRequest;
139
140impl GenericRequest for ClusterControllerFarmerAppInfoRequest {
141    const SUBJECT: &'static str = "ab.controller.farmer-app-info";
142    type Response = Result<FarmerAppInfo, String>;
143}
144
145/// Request super segment headers with specified super segment indices
146#[derive(Debug, Clone, Encode, Decode)]
147struct ClusterControllerSuperSegmentHeadersRequest {
148    super_segment_indices: Vec<SuperSegmentIndex>,
149}
150
151impl GenericRequest for ClusterControllerSuperSegmentHeadersRequest {
152    const SUBJECT: &'static str = "ab.controller.super-segment-headers";
153    type Response = Vec<Option<SuperSegmentHeader>>;
154}
155
156/// Request the header of the super segment that contains a specified segment index
157#[derive(Debug, Clone, Encode, Decode)]
158struct ClusterControllerSuperSegmentHeaderForSegmentIndexRequest {
159    segment_index: SegmentIndex,
160}
161
162impl GenericRequest for ClusterControllerSuperSegmentHeaderForSegmentIndexRequest {
163    const SUBJECT: &'static str = "ab.controller.super-segment-header-for-segment-index";
164    type Response = Option<SuperSegmentHeader>;
165}
166
167/// Find piece with specified index in cache
168#[derive(Debug, Clone, Encode, Decode)]
169struct ClusterControllerFindPieceInCacheRequest {
170    piece_index: PieceIndex,
171}
172
173impl GenericRequest for ClusterControllerFindPieceInCacheRequest {
174    const SUBJECT: &'static str = "ab.controller.*.find-piece-in-cache";
175    type Response = Option<(PieceCacheId, PieceCacheOffset)>;
176}
177
178/// Find pieces with specified indices in cache
179#[derive(Debug, Clone, Encode, Decode)]
180struct ClusterControllerFindPiecesInCacheRequest {
181    piece_indices: Vec<PieceIndex>,
182}
183
184impl GenericStreamRequest for ClusterControllerFindPiecesInCacheRequest {
185    const SUBJECT: &'static str = "ab.controller.*.find-pieces-in-cache";
186    /// Only pieces that were found are returned
187    type Response = (PieceIndex, PieceCacheId, PieceCacheOffset);
188}
189
190/// Request piece with specified index
191#[derive(Debug, Clone, Encode, Decode)]
192struct ClusterControllerPieceRequest {
193    piece_index: PieceIndex,
194}
195
196impl GenericRequest for ClusterControllerPieceRequest {
197    const SUBJECT: &'static str = "ab.controller.piece";
198    type Response = Option<Piece>;
199}
200
201/// Request pieces with specified index
202#[derive(Debug, Clone, Encode, Decode)]
203struct ClusterControllerPiecesRequest {
204    piece_indices: Vec<PieceIndex>,
205}
206
207impl GenericStreamRequest for ClusterControllerPiecesRequest {
208    const SUBJECT: &'static str = "ab.controller.pieces";
209    /// Only pieces that were found are returned
210    type Response = (PieceIndex, Piece);
211}
212
213/// Cluster piece getter
214#[derive(Debug, Clone)]
215pub struct ClusterPieceGetter {
216    nats_client: NatsClient,
217    cache_group: String,
218}
219
220#[async_trait]
221impl PieceGetter for ClusterPieceGetter {
222    async fn get_piece(&self, piece_index: PieceIndex) -> anyhow::Result<Option<Piece>> {
223        if let Some((piece_cache_id, piece_cache_offset)) = self
224            .nats_client
225            .request(
226                &ClusterControllerFindPieceInCacheRequest { piece_index },
227                Some(&self.cache_group),
228            )
229            .await?
230        {
231            trace!(
232                %piece_index,
233                %piece_cache_id,
234                %piece_cache_offset,
235                "Found piece in cache, retrieving"
236            );
237
238            match self
239                .nats_client
240                .request(
241                    &ClusterCacheReadPieceRequest {
242                        offset: piece_cache_offset,
243                    },
244                    Some(&piece_cache_id.to_string()),
245                )
246                .await
247                .map_err(|error| error.to_string())
248                .flatten()
249            {
250                Ok(Some((retrieved_piece_index, piece))) => {
251                    if retrieved_piece_index == piece_index {
252                        trace!(
253                            %piece_index,
254                            %piece_cache_id,
255                            %piece_cache_offset,
256                            "Retrieved piece from cache successfully"
257                        );
258
259                        return Ok(Some(piece));
260                    }
261
262                    trace!(
263                        %piece_index,
264                        %piece_cache_id,
265                        %piece_cache_offset,
266                        "Retrieving piece was replaced in cache during retrieval"
267                    );
268                }
269                Ok(None) => {
270                    trace!(
271                        %piece_index,
272                        %piece_cache_id,
273                        %piece_cache_offset,
274                        "Piece cache didn't have piece at offset"
275                    );
276                }
277                Err(error) => {
278                    debug!(
279                        %piece_index,
280                        %piece_cache_id,
281                        %piece_cache_offset,
282                        %error,
283                        "Retrieving piece from cache failed"
284                    );
285                }
286            }
287        } else {
288            trace!(%piece_index, "Piece not found in cache");
289        }
290
291        Ok(self
292            .nats_client
293            .request(&ClusterControllerPieceRequest { piece_index }, None)
294            .await?)
295    }
296
297    async fn get_pieces<'a>(
298        &'a self,
299        piece_indices: Vec<PieceIndex>,
300    ) -> anyhow::Result<
301        Box<dyn Stream<Item = (PieceIndex, anyhow::Result<Option<Piece>>)> + Send + Unpin + 'a>,
302    > {
303        let (tx, mut rx) = mpsc::unbounded();
304
305        let piece_indices_to_get =
306            Mutex::new(piece_indices.iter().copied().collect::<HashSet<_>>());
307
308        let mut cached_pieces_by_cache_id = HashMap::<PieceCacheId, Vec<PieceCacheOffset>>::new();
309
310        {
311            let mut cached_pieces = self
312                .nats_client
313                .stream_request(
314                    &ClusterControllerFindPiecesInCacheRequest { piece_indices },
315                    Some(&self.cache_group),
316                )
317                .await?;
318
319            while let Some((_piece_index, piece_cache_id, piece_cache_offset)) =
320                cached_pieces.next().await
321            {
322                cached_pieces_by_cache_id
323                    .entry(piece_cache_id)
324                    .or_default()
325                    .push(piece_cache_offset);
326            }
327        }
328
329        let fut = async move {
330            let tx = &tx;
331
332            cached_pieces_by_cache_id
333                .into_iter()
334                .map(|(piece_cache_id, offsets)| {
335                    let piece_indices_to_get = &piece_indices_to_get;
336
337                    async move {
338                        let mut pieces_stream = match self
339                            .nats_client
340                            .stream_request(
341                                &ClusterCacheReadPiecesRequest { offsets },
342                                Some(&piece_cache_id.to_string()),
343                            )
344                            .await
345                        {
346                            Ok(pieces) => pieces,
347                            Err(error) => {
348                                warn!(
349                                    %error,
350                                    %piece_cache_id,
351                                    "Failed to request pieces from cache"
352                                );
353
354                                return;
355                            }
356                        };
357
358                        while let Some(piece_result) = pieces_stream.next().await {
359                            let (piece_offset, maybe_piece) = match piece_result {
360                                Ok(result) => result,
361                                Err(error) => {
362                                    warn!(%error, "Failed to get piece from cache");
363                                    continue;
364                                }
365                            };
366
367                            if let Some((piece_index, piece)) = maybe_piece {
368                                piece_indices_to_get.lock().remove(&piece_index);
369
370                                tx.unbounded_send((piece_index, Ok(Some(piece)))).expect(
371                                    "This future isn't polled after receiver is dropped; qed",
372                                );
373                            } else {
374                                warn!(
375                                    %piece_cache_id,
376                                    %piece_offset,
377                                    "Failed to get piece from cache, it was missing or already gone"
378                                );
379                            }
380                        }
381                    }
382                })
383                .collect::<FuturesUnordered<_>>()
384                // Simply drain everything
385                .for_each(|()| async {})
386                .await;
387
388            let mut piece_indices_to_get = piece_indices_to_get.into_inner();
389            if piece_indices_to_get.is_empty() {
390                return;
391            }
392
393            let mut pieces_from_controller = match self
394                .nats_client
395                .stream_request(
396                    &ClusterControllerPiecesRequest {
397                        piece_indices: piece_indices_to_get.iter().copied().collect(),
398                    },
399                    None,
400                )
401                .await
402            {
403                Ok(pieces_from_controller) => pieces_from_controller,
404                Err(error) => {
405                    error!(%error, "Failed to get pieces from controller");
406
407                    for piece_index in piece_indices_to_get {
408                        tx.unbounded_send((
409                            piece_index,
410                            Err(anyhow::anyhow!("Failed to get piece from controller")),
411                        ))
412                        .expect("This future isn't polled after receiver is dropped; qed");
413                    }
414                    return;
415                }
416            };
417
418            while let Some((piece_index, piece)) = pieces_from_controller.next().await {
419                piece_indices_to_get.remove(&piece_index);
420                tx.unbounded_send((piece_index, Ok(Some(piece))))
421                    .expect("This future isn't polled after receiver is dropped; qed");
422            }
423
424            for piece_index in piece_indices_to_get {
425                tx.unbounded_send((piece_index, Err(anyhow::anyhow!("Failed to get piece"))))
426                    .expect("This future isn't polled after receiver is dropped; qed");
427            }
428        };
429        let mut fut = Box::pin(fut.fuse());
430
431        // Drive above future and stream back any pieces that were downloaded so far
432        Ok(Box::new(stream::poll_fn(move |cx| {
433            if !fut.is_terminated() {
434                // Result doesn't matter, we'll need to poll stream below anyway
435                let _: Poll<()> = fut.poll_unpin(cx);
436            }
437
438            if let Poll::Ready(maybe_result) = rx.poll_next_unpin(cx) {
439                return Poll::Ready(maybe_result);
440            }
441
442            // Exit will be done by the stream above
443            Poll::Pending
444        })))
445    }
446}
447
448impl ClusterPieceGetter {
449    /// Create a new instance
450    #[inline]
451    pub fn new(nats_client: NatsClient, cache_group: Option<String>) -> Self {
452        Self {
453            nats_client,
454            cache_group: cache_group.unwrap_or_else(|| GLOBAL_CACHE_GROUP.to_string()),
455        }
456    }
457}
458
459/// [`NodeClient`] used in cluster environment that connects to node through a controller instead
460/// of to the node directly
461#[derive(Debug, Clone)]
462pub struct ClusterNodeClient {
463    nats_client: NatsClient,
464    // Store last slot info instance that can be used to send solution response to (some instances
465    // may be not synced and not able to receive solution responses)
466    last_slot_info_instance: Arc<Mutex<String>>,
467}
468
469impl ClusterNodeClient {
470    /// Create a new instance
471    pub fn new(nats_client: NatsClient) -> Self {
472        Self {
473            nats_client,
474            last_slot_info_instance: Arc::default(),
475        }
476    }
477}
478
479#[async_trait]
480impl NodeClient for ClusterNodeClient {
481    async fn farmer_app_info(&self) -> anyhow::Result<FarmerAppInfo> {
482        Ok(self
483            .nats_client
484            .request(&ClusterControllerFarmerAppInfoRequest, None)
485            .await?
486            .map_err(anyhow::Error::msg)?)
487    }
488
489    async fn subscribe_slot_info(
490        &self,
491    ) -> anyhow::Result<Pin<Box<dyn Stream<Item = SlotInfo> + Send + 'static>>> {
492        let subscription = self
493            .nats_client
494            .subscribe_to_broadcasts::<ClusterControllerSlotInfoBroadcast>(None, None)
495            .await?
496            .filter_map({
497                let mut last_slot_number = None;
498                let last_slot_info_instance = Arc::clone(&self.last_slot_info_instance);
499
500                move |broadcast| {
501                    let slot_info = broadcast.slot_info;
502
503                    let maybe_slot_info = if let Some(last_slot_number) = last_slot_number
504                        && last_slot_number >= slot_info.slot
505                    {
506                        None
507                    } else {
508                        last_slot_number.replace(slot_info.slot);
509                        *last_slot_info_instance.lock() = broadcast.instance;
510
511                        Some(slot_info)
512                    };
513
514                    async move { maybe_slot_info }
515                }
516            });
517
518        Ok(Box::pin(subscription))
519    }
520
521    async fn submit_solution_response(
522        &self,
523        solution_response: SolutionResponse,
524    ) -> anyhow::Result<()> {
525        let last_slot_info_instance = self.last_slot_info_instance.lock().clone();
526        Ok(self
527            .nats_client
528            .notification(
529                &ClusterControllerSolutionNotification { solution_response },
530                Some(&last_slot_info_instance),
531            )
532            .await?)
533    }
534
535    async fn subscribe_block_sealing(
536        &self,
537    ) -> anyhow::Result<Pin<Box<dyn Stream<Item = BlockSealInfo> + Send + 'static>>> {
538        let subscription = self
539            .nats_client
540            .subscribe_to_broadcasts::<ClusterControllerBlockSealingBroadcast>(None, None)
541            .await?
542            .map(|broadcast| broadcast.block_sealing_info);
543
544        Ok(Box::pin(subscription))
545    }
546
547    async fn submit_block_seal(&self, block_seal: BlockSealResponse) -> anyhow::Result<()> {
548        Ok(self
549            .nats_client
550            .notification(&ClusterControllerBlockSealNotification { block_seal }, None)
551            .await?)
552    }
553
554    async fn subscribe_new_super_segment_headers(
555        &self,
556    ) -> anyhow::Result<Pin<Box<dyn Stream<Item = SuperSegmentHeader> + Send + 'static>>> {
557        let subscription = self
558            .nats_client
559            .subscribe_to_broadcasts::<ClusterControllerNewSuperSegmentHeaderBroadcast>(None, None)
560            .await?
561            .filter_map({
562                let mut last_super_segment_index = None;
563
564                move |broadcast| {
565                    let new_super_segment_header = broadcast.new_super_segment_header;
566                    let super_segment_index = new_super_segment_header.index.as_inner();
567
568                    let maybe_super_segment_header = if let Some(last_super_segment_index) =
569                        last_super_segment_index
570                        && last_super_segment_index >= super_segment_index
571                    {
572                        None
573                    } else {
574                        last_super_segment_index.replace(super_segment_index);
575
576                        Some(new_super_segment_header)
577                    };
578
579                    async move { maybe_super_segment_header }
580                }
581            });
582
583        Ok(Box::pin(subscription))
584    }
585
586    async fn super_segment_headers(
587        &self,
588        super_segment_indices: Vec<SuperSegmentIndex>,
589    ) -> anyhow::Result<Vec<Option<SuperSegmentHeader>>> {
590        Ok(self
591            .nats_client
592            .request(
593                &ClusterControllerSuperSegmentHeadersRequest {
594                    super_segment_indices,
595                },
596                None,
597            )
598            .await?)
599    }
600
601    async fn super_segment_header_for_segment_index(
602        &self,
603        segment_index: SegmentIndex,
604    ) -> anyhow::Result<Option<SuperSegmentHeader>> {
605        Ok(self
606            .nats_client
607            .request(
608                &ClusterControllerSuperSegmentHeaderForSegmentIndexRequest { segment_index },
609                None,
610            )
611            .await?)
612    }
613
614    async fn piece(&self, piece_index: PieceIndex) -> anyhow::Result<Option<Piece>> {
615        Ok(self
616            .nats_client
617            .request(&ClusterControllerPieceRequest { piece_index }, None)
618            .await?)
619    }
620
621    async fn update_shard_membership_info(
622        &self,
623        _info: FarmerShardMembershipInfo,
624    ) -> anyhow::Result<()> {
625        // Controller aggregates these on its own
626        Ok(())
627    }
628}
629
630/// Create controller service that handles things like broadcasting information (for example slot
631/// notifications) as well as responding to incoming requests (like piece requests).
632///
633/// Implementation is using concurrency with multiple tokio tasks, but can be started multiple times
634/// per controller instance in order to parallelize more work across threads if needed.
635pub async fn controller_service<NC, PG>(
636    nats_client: &NatsClient,
637    node_client: &NC,
638    piece_getter: &PG,
639    farmer_caches: &[(&str, &FarmerCache)],
640    instance: &str,
641    primary_instance: bool,
642) -> anyhow::Result<()>
643where
644    NC: NodeClient,
645    PG: PieceGetter + Sync,
646{
647    if primary_instance {
648        select! {
649            result = slot_info_broadcaster(nats_client, node_client, instance).fuse() => {
650                result
651            },
652            result = block_sealing_broadcaster(nats_client, node_client, instance).fuse() => {
653                result
654            },
655            result = new_super_segment_headers_broadcaster(nats_client, node_client, instance).fuse() => {
656                result
657            },
658            result = solution_response_forwarder(nats_client, node_client, instance).fuse() => {
659                result
660            },
661            result = block_seal_forwarder(nats_client, node_client, instance).fuse() => {
662                result
663            },
664            result = farmer_app_info_responder(nats_client, node_client).fuse() => {
665                result
666            },
667            result = super_segment_headers_responder(nats_client, node_client).fuse() => {
668                result
669            },
670            result = super_segment_header_for_segment_index_responder(nats_client, node_client).fuse() => {
671                result
672            },
673            result = find_piece_responder(nats_client, farmer_caches).fuse() => {
674                result
675            },
676            result = find_pieces_responder(nats_client, farmer_caches).fuse() => {
677                result
678            },
679            result = piece_responder(nats_client, piece_getter).fuse() => {
680                result
681            },
682            result = pieces_responder(nats_client, piece_getter).fuse() => {
683                result
684            },
685        }
686    } else {
687        select! {
688            result = farmer_app_info_responder(nats_client, node_client).fuse() => {
689                result
690            },
691            result = super_segment_headers_responder(nats_client, node_client).fuse() => {
692                result
693            },
694            result = super_segment_header_for_segment_index_responder(nats_client, node_client).fuse() => {
695                result
696            },
697            result = find_piece_responder(nats_client, farmer_caches).fuse() => {
698                result
699            },
700            result = find_pieces_responder(nats_client, farmer_caches).fuse() => {
701                result
702            },
703            result = piece_responder(nats_client, piece_getter).fuse() => {
704                result
705            },
706            result = pieces_responder(nats_client, piece_getter).fuse() => {
707                result
708            },
709        }
710    }
711}
712
713async fn slot_info_broadcaster<NC>(
714    nats_client: &NatsClient,
715    node_client: &NC,
716    instance: &str,
717) -> anyhow::Result<()>
718where
719    NC: NodeClient,
720{
721    let mut slot_info_notifications = node_client
722        .subscribe_slot_info()
723        .await
724        .map_err(|error| anyhow!("Failed to subscribe to slot info notifications: {error}"))?;
725
726    while let Some(slot_info) = slot_info_notifications.next().await {
727        debug!(?slot_info, "New slot");
728
729        let slot = slot_info.slot;
730
731        if let Err(error) = nats_client
732            .broadcast(
733                &ClusterControllerSlotInfoBroadcast {
734                    slot_info,
735                    instance: instance.to_string(),
736                },
737                instance,
738            )
739            .await
740        {
741            warn!(%slot, %error, "Failed to broadcast slot info");
742        }
743    }
744
745    Ok(())
746}
747
748async fn block_sealing_broadcaster<NC>(
749    nats_client: &NatsClient,
750    node_client: &NC,
751    instance: &str,
752) -> anyhow::Result<()>
753where
754    NC: NodeClient,
755{
756    let mut block_sealing_subscription = node_client
757        .subscribe_block_sealing()
758        .await
759        .map_err(|error| anyhow!("Failed to subscribe to block sealing notifications: {error}"))?;
760
761    while let Some(block_sealing_info) = block_sealing_subscription.next().await {
762        trace!(?block_sealing_info, "New block sealing notification");
763
764        if let Err(error) = nats_client
765            .broadcast(
766                &ClusterControllerBlockSealingBroadcast { block_sealing_info },
767                instance,
768            )
769            .await
770        {
771            warn!(%error, "Failed to broadcast block sealing info");
772        }
773    }
774
775    Ok(())
776}
777
778async fn new_super_segment_headers_broadcaster<NC>(
779    nats_client: &NatsClient,
780    node_client: &NC,
781    instance: &str,
782) -> anyhow::Result<()>
783where
784    NC: NodeClient,
785{
786    let mut new_super_segments_notifications = node_client
787        .subscribe_new_super_segment_headers()
788        .await
789        .map_err(|error| {
790            anyhow!("Failed to subscribe to new super segment header notifications: {error}")
791        })?;
792
793    while let Some(new_super_segment_header) = new_super_segments_notifications.next().await {
794        trace!(
795            ?new_super_segment_header,
796            "New archived new super segment header notification"
797        );
798
799        if let Err(error) = nats_client
800            .broadcast(
801                &ClusterControllerNewSuperSegmentHeaderBroadcast {
802                    new_super_segment_header,
803                },
804                instance,
805            )
806            .await
807        {
808            warn!(%error, "Failed to broadcast new super segment header info");
809        }
810    }
811
812    Ok(())
813}
814
815async fn solution_response_forwarder<NC>(
816    nats_client: &NatsClient,
817    node_client: &NC,
818    instance: &str,
819) -> anyhow::Result<()>
820where
821    NC: NodeClient,
822{
823    let mut subscription = nats_client
824        .subscribe_to_notifications::<ClusterControllerSolutionNotification>(
825            Some(instance),
826            Some(instance.to_string()),
827        )
828        .await
829        .map_err(|error| anyhow!("Failed to subscribe to solution notifications: {error}"))?;
830
831    while let Some(notification) = subscription.next().await {
832        debug!(?notification, "Solution notification");
833
834        let slot = notification.solution_response.slot_number;
835        let public_key_hash = notification.solution_response.solution.public_key_hash;
836        let sector_index = notification.solution_response.solution.sector_index;
837
838        if let Err(error) = node_client
839            .submit_solution_response(notification.solution_response)
840            .await
841        {
842            warn!(
843                %error,
844                %slot,
845                %public_key_hash,
846                %sector_index,
847                "Failed to send solution response"
848            );
849        }
850    }
851
852    Ok(())
853}
854
855async fn block_seal_forwarder<NC>(
856    nats_client: &NatsClient,
857    node_client: &NC,
858    instance: &str,
859) -> anyhow::Result<()>
860where
861    NC: NodeClient,
862{
863    let mut subscription = nats_client
864        .subscribe_to_notifications::<ClusterControllerBlockSealNotification>(
865            None,
866            Some(instance.to_string()),
867        )
868        .await
869        .map_err(|error| anyhow!("Failed to subscribe to block seal notifications: {error}"))?;
870
871    while let Some(notification) = subscription.next().await {
872        debug!(?notification, "Block seal notification");
873
874        if let Err(error) = node_client.submit_block_seal(notification.block_seal).await {
875            warn!(%error, "Failed to send block seal");
876        }
877    }
878
879    Ok(())
880}
881
882async fn farmer_app_info_responder<NC>(
883    nats_client: &NatsClient,
884    node_client: &NC,
885) -> anyhow::Result<()>
886where
887    NC: NodeClient,
888{
889    nats_client
890        .request_responder(
891            None,
892            Some("ab.controller".to_string()),
893            |_: ClusterControllerFarmerAppInfoRequest| async move {
894                Some(
895                    node_client
896                        .farmer_app_info()
897                        .await
898                        .map_err(|error| error.to_string()),
899                )
900            },
901        )
902        .await
903}
904
905async fn super_segment_headers_responder<NC>(
906    nats_client: &NatsClient,
907    node_client: &NC,
908) -> anyhow::Result<()>
909where
910    NC: NodeClient,
911{
912    nats_client
913        .request_responder(
914            None,
915            Some("ab.controller".to_string()),
916            |ClusterControllerSuperSegmentHeadersRequest { super_segment_indices }| async move {
917                node_client
918                    .super_segment_headers(super_segment_indices.clone())
919                    .await
920                    .inspect_err(|error| {
921                        warn!(%error, ?super_segment_indices, "Failed to get super segment headers");
922                    })
923                    .ok()
924            },
925        )
926        .await
927}
928
929async fn super_segment_header_for_segment_index_responder<NC>(
930    nats_client: &NatsClient,
931    node_client: &NC,
932) -> anyhow::Result<()>
933where
934    NC: NodeClient,
935{
936    nats_client
937        .request_responder(
938            None,
939            Some("ab.controller".to_string()),
940            |ClusterControllerSuperSegmentHeaderForSegmentIndexRequest { segment_index }| async move {
941                node_client
942                    .super_segment_header_for_segment_index(segment_index)
943                    .await
944                    .inspect_err(|error| {
945                        warn!(
946                            %error,
947                            %segment_index,
948                            "Failed to get super segment header for segment index"
949                        );
950                    })
951                    .ok()
952            },
953        )
954        .await
955}
956
957async fn find_piece_responder(
958    nats_client: &NatsClient,
959    farmer_caches: &[(&str, &FarmerCache)],
960) -> anyhow::Result<()> {
961    futures::future::try_join(
962        farmer_caches
963            .iter()
964            .map(|(cache_group, farmer_cache)| {
965                nats_client.request_responder(
966                    Some(cache_group),
967                    Some("ab.controller".to_string()),
968                    move |ClusterControllerFindPieceInCacheRequest { piece_index }| async move {
969                        Some(farmer_cache.find_piece(piece_index).await)
970                    },
971                )
972            })
973            .collect::<FuturesUnordered<_>>()
974            .next()
975            .map(|result| result.unwrap_or(Ok(()))),
976        nats_client.request_responder(
977            Some(GLOBAL_CACHE_GROUP),
978            Some("ab.controller".to_string()),
979            |ClusterControllerFindPieceInCacheRequest { piece_index }| async move {
980                let (_cache_group, farmer_cache) = farmer_caches.iter().choose(&mut rand::rng())?;
981                Some(farmer_cache.find_piece(piece_index).await)
982            },
983        ),
984    )
985    .await
986    .map(|((), ())| ())
987}
988
989async fn find_pieces_responder(
990    nats_client: &NatsClient,
991    farmer_caches: &[(&str, &FarmerCache)],
992) -> anyhow::Result<()> {
993    futures::future::try_join(
994        farmer_caches
995            .iter()
996            .map(|(cache_group, farmer_cache)| {
997                nats_client.stream_request_responder(
998                    Some(cache_group),
999                    Some("ab.controller".to_string()),
1000                    move |ClusterControllerFindPiecesInCacheRequest { piece_indices }| async move {
1001                        Some(stream::iter(farmer_cache.find_pieces(piece_indices).await))
1002                    },
1003                )
1004            })
1005            .collect::<FuturesUnordered<_>>()
1006            .next()
1007            .map(|result| result.unwrap_or(Ok(()))),
1008        nats_client.stream_request_responder(
1009            Some(GLOBAL_CACHE_GROUP),
1010            Some("ab.controller".to_string()),
1011            |ClusterControllerFindPiecesInCacheRequest { piece_indices }| async move {
1012                let (_cache_group, farmer_cache) = farmer_caches.iter().choose(&mut rand::rng())?;
1013                Some(stream::iter(farmer_cache.find_pieces(piece_indices).await))
1014            },
1015        ),
1016    )
1017    .await
1018    .map(|((), ())| ())
1019}
1020
1021async fn piece_responder<PG>(nats_client: &NatsClient, piece_getter: &PG) -> anyhow::Result<()>
1022where
1023    PG: PieceGetter + Sync,
1024{
1025    nats_client
1026        .request_responder(
1027            None,
1028            Some("ab.controller".to_string()),
1029            |ClusterControllerPieceRequest { piece_index }| async move {
1030                piece_getter
1031                    .get_piece(piece_index)
1032                    .await
1033                    .inspect_err(|error| warn!(%error, %piece_index, "Failed to get piece"))
1034                    .ok()
1035            },
1036        )
1037        .await
1038}
1039
1040async fn pieces_responder<PG>(nats_client: &NatsClient, piece_getter: &PG) -> anyhow::Result<()>
1041where
1042    PG: PieceGetter + Sync,
1043{
1044    nats_client
1045        .stream_request_responder(
1046            None,
1047            Some("ab.controller".to_string()),
1048            |ClusterControllerPiecesRequest { piece_indices }| async move {
1049                piece_getter
1050                    .get_pieces(piece_indices)
1051                    .await
1052                    .map(|stream| {
1053                        Box::pin(stream.filter_map(
1054                            |(piece_index, maybe_piece_result)| async move {
1055                                match maybe_piece_result {
1056                                    Ok(Some(piece)) => Some((piece_index, piece)),
1057                                    Ok(None) => None,
1058                                    Err(error) => {
1059                                        warn!(%error, %piece_index, "Failed to get piece");
1060                                        None
1061                                    }
1062                                }
1063                            },
1064                        ))
1065                    })
1066                    .inspect_err(|error| warn!(%error, "Failed to get pieces"))
1067                    .ok()
1068            },
1069        )
1070        .await
1071}