Skip to main content

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