Skip to main content

ab_farmer/cluster/
plotter.rs

1//! Farming cluster plotter
2//!
3//! Plotter is responsible for plotting sectors in response to farmer requests.
4//!
5//! This module exposes some data structures for NATS communication, custom plotter
6//! implementation designed to work with cluster plotter and a service function to drive the backend
7//! part of the plotter.
8
9#[cfg(test)]
10mod tests;
11
12use crate::cluster::nats_client::{GenericRequest, GenericStreamRequest, NatsClient};
13use crate::plotter::{Plotter, SectorPlottingProgress};
14use crate::utils::AsyncJoinOnDrop;
15use ab_aligned_buffer::alignment::Align4096;
16use ab_aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
17use ab_core_primitives::ed25519::Ed25519PublicKey;
18use ab_core_primitives::sectors::SectorIndex;
19use ab_core_primitives::solutions::ShardCommitmentHash;
20use ab_direct_io_file::OwnedPages;
21use ab_farmer_components::FarmerProtocolInfo;
22use ab_farmer_components::plotting::PlottedSector;
23use ab_farmer_components::sector::sector_size;
24use anyhow::anyhow;
25use async_nats::RequestErrorKind;
26use async_trait::async_trait;
27use backon::{BackoffBuilder, ExponentialBackoff, ExponentialBuilder};
28use derive_more::Display;
29use event_listener_primitives::{Bag, HandlerId};
30use futures::channel::mpsc;
31use futures::future::FusedFuture;
32use futures::stream::FuturesUnordered;
33use futures::{FutureExt, Sink, SinkExt, StreamExt, select, stream};
34use parity_scale_codec::{Compact, CompactLen, Decode, Encode, Input, Output};
35use std::error::Error;
36use std::future::pending;
37use std::num::NonZeroUsize;
38use std::pin::pin;
39use std::sync::Arc as StdArc;
40use std::task::Poll;
41use std::time::{Duration, Instant};
42use tokio::sync::{OwnedSemaphorePermit, Semaphore};
43use tokio::time::MissedTickBehavior;
44use tracing::{Instrument, debug, info, info_span, trace, warn};
45use triomphe::Arc;
46use ulid::Ulid;
47
48const FREE_CAPACITY_CHECK_INTERVAL: Duration = Duration::from_secs(1);
49/// Intervals between pings from plotter server to client
50const PING_INTERVAL: Duration = Duration::from_secs(10);
51/// Timeout after which plotter that doesn't send pings is assumed to be down
52const PING_TIMEOUT: Duration = Duration::from_mins(1);
53
54/// Type alias used for event handlers
55pub type HandlerFn3<A, B, C> = StdArc<dyn Fn(&A, &B, &C) + Send + Sync + 'static>;
56type Handler3<A, B, C> = Bag<HandlerFn3<A, B, C>, A, B, C>;
57
58/// An ephemeral identifier for a plotter
59#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Display)]
60pub enum ClusterPlotterId {
61    /// Plotter ID
62    Ulid(Ulid),
63}
64
65#[expect(
66    clippy::new_without_default,
67    reason = "Default has different semantics"
68)]
69impl ClusterPlotterId {
70    /// Creates new ID
71    pub fn new() -> Self {
72        Self::Ulid(Ulid::generate())
73    }
74}
75
76/// Request for free plotter instance
77#[derive(Debug, Clone, Encode, Decode)]
78struct ClusterPlotterFreeInstanceRequest;
79
80impl GenericRequest for ClusterPlotterFreeInstanceRequest {
81    const SUBJECT: &'static str = "ab.plotter.free-instance";
82    /// Might be `None` if instance had to respond, but turned out it was fully occupied already
83    type Response = Option<String>;
84}
85
86/// Chunk of a plotted sector, whose contents are aligned to the page size.
87///
88/// Encoded the same way as bytes with SCALE codec, decoding copies the contents into a new buffer
89/// that is aligned to the page size. Decoding rejects lengths that are not a multiple of the page
90/// size, such that chunks can be written to disk without read-modify-write.
91#[derive(Debug)]
92struct SectorChunk(SharedAlignedBuffer<Align4096>);
93
94impl Encode for SectorChunk {
95    #[inline]
96    fn size_hint(&self) -> usize {
97        Compact::<u32>::compact_len(&self.0.len()) + self.0.len() as usize
98    }
99
100    #[inline]
101    fn encode_to<O>(&self, dest: &mut O)
102    where
103        O: Output + ?Sized,
104    {
105        Compact(self.0.len()).encode_to(dest);
106        dest.write(&self.0);
107    }
108}
109
110impl Decode for SectorChunk {
111    fn decode<I>(input: &mut I) -> Result<Self, parity_scale_codec::Error>
112    where
113        I: Input,
114    {
115        let Compact(length) = Compact::<u32>::decode(input)?;
116
117        // Honest plotters only send whole pages, see `sector_chunk_size()`
118        if !length.is_multiple_of(OwnedPages::ALIGN) {
119            return Err("Sector chunk length is not a multiple of the page size".into());
120        }
121        // The length comes from a remote plotter, check it before allocating memory
122        if let Some(remaining) = input.remaining_len()?
123            && remaining < length as usize
124        {
125            return Err("Not enough bytes for a sector chunk".into());
126        }
127        input.on_before_alloc_mem(length as usize)?;
128
129        let mut buffer = OwnedAlignedBuffer::<Align4096>::try_zeroed(length)
130            .map_err(|_error| "Failed to allocate sector chunk")?;
131        input.read(buffer.as_mut_slice())?;
132
133        Ok(Self(buffer.into_shared()))
134    }
135}
136
137#[derive(Debug, Encode, Decode)]
138enum ClusterSectorPlottingProgress {
139    /// Plotter is already fully occupied with other work
140    Occupied,
141    /// Periodic ping indicating plotter is still busy
142    Ping,
143    /// Downloading sector pieces
144    Downloading,
145    /// Downloaded sector pieces
146    Downloaded(Duration),
147    /// Encoding sector pieces
148    Encoding,
149    /// Encoded sector pieces
150    Encoded(Duration),
151    /// Finished plotting, followed by a series of sector chunks
152    Finished {
153        /// Information about plotted sector
154        plotted_sector: PlottedSector,
155        /// How much time it took to plot a sector
156        time: Duration,
157    },
158    /// Sector chunk after finished plotting
159    SectorChunk(Result<SectorChunk, String>),
160    /// Plotting failed
161    Error {
162        /// Error message
163        error: String,
164    },
165}
166
167/// Request to plot sector from plotter
168#[derive(Debug, Clone, Encode, Decode)]
169struct ClusterPlotterPlotSectorRequest {
170    public_key: Ed25519PublicKey,
171    shard_commitments_root: ShardCommitmentHash,
172    sector_index: SectorIndex,
173    farmer_protocol_info: FarmerProtocolInfo,
174    pieces_in_sector: u16,
175}
176
177impl GenericStreamRequest for ClusterPlotterPlotSectorRequest {
178    const SUBJECT: &'static str = "ab.plotter.*.plot-sector";
179    type Response = ClusterSectorPlottingProgress;
180}
181
182/// Size of sector chunks sent from plotter to farmer.
183///
184/// It is a multiple of disk page size, such that farmer can write chunks to disk without
185/// read-modify-write.
186fn sector_chunk_size(nats_client: &NatsClient) -> u32 {
187    let max_message_size = u32::try_from(nats_client.approximate_max_message_size())
188        .expect("NATS messages are much smaller than 4 GiB; qed");
189    max_message_size / OwnedPages::ALIGN * OwnedPages::ALIGN
190}
191
192#[derive(Default, Debug)]
193struct Handlers {
194    plotting_progress: Handler3<Ed25519PublicKey, SectorIndex, SectorPlottingProgress>,
195}
196
197/// Cluster plotter
198#[derive(Debug)]
199pub struct ClusterPlotter {
200    sector_encoding_semaphore: StdArc<Semaphore>,
201    retry_backoff_policy: ExponentialBuilder,
202    nats_client: NatsClient,
203    handlers: Arc<Handlers>,
204    tasks_sender: mpsc::Sender<AsyncJoinOnDrop<()>>,
205    _background_tasks: AsyncJoinOnDrop<()>,
206}
207
208impl Drop for ClusterPlotter {
209    #[inline]
210    fn drop(&mut self) {
211        self.tasks_sender.close_channel();
212    }
213}
214
215#[async_trait]
216impl Plotter for ClusterPlotter {
217    async fn has_free_capacity(&self) -> Result<bool, String> {
218        Ok(self.sector_encoding_semaphore.available_permits() > 0
219            && self
220                .nats_client
221                .request(&ClusterPlotterFreeInstanceRequest, None)
222                .await
223                .map_err(|error| error.to_string())?
224                .is_some())
225    }
226
227    async fn plot_sector(
228        &self,
229        public_key: Ed25519PublicKey,
230        shard_commitments_root: ShardCommitmentHash,
231        sector_index: SectorIndex,
232        farmer_protocol_info: FarmerProtocolInfo,
233        pieces_in_sector: u16,
234        _replotting: bool,
235        mut progress_sender: mpsc::Sender<SectorPlottingProgress>,
236    ) {
237        let start = Instant::now();
238
239        // Done outside the future below as a backpressure, ensuring that it is not possible to
240        // schedule unbounded number of plotting tasks
241        let sector_encoding_permit = match StdArc::clone(&self.sector_encoding_semaphore)
242            .acquire_owned()
243            .await
244        {
245            Ok(sector_encoding_permit) => sector_encoding_permit,
246            Err(error) => {
247                warn!(%error, "Failed to acquire sector encoding permit");
248
249                let progress_updater = ProgressUpdater {
250                    public_key,
251                    sector_index,
252                    handlers: Arc::clone(&self.handlers),
253                };
254
255                progress_updater
256                    .update_progress_and_events(
257                        &mut progress_sender,
258                        SectorPlottingProgress::Error {
259                            error: format!("Failed to acquire sector encoding permit: {error}"),
260                        },
261                    )
262                    .await;
263
264                return;
265            }
266        };
267
268        self.plot_sector_internal(
269            start,
270            sector_encoding_permit,
271            public_key,
272            shard_commitments_root,
273            sector_index,
274            farmer_protocol_info,
275            pieces_in_sector,
276            progress_sender,
277        )
278        .await;
279    }
280
281    async fn try_plot_sector(
282        &self,
283        public_key: Ed25519PublicKey,
284        shard_commitments_root: ShardCommitmentHash,
285        sector_index: SectorIndex,
286        farmer_protocol_info: FarmerProtocolInfo,
287        pieces_in_sector: u16,
288        _replotting: bool,
289        progress_sender: mpsc::Sender<SectorPlottingProgress>,
290    ) -> bool {
291        let start = Instant::now();
292
293        let Ok(sector_encoding_permit) =
294            StdArc::clone(&self.sector_encoding_semaphore).try_acquire_owned()
295        else {
296            return false;
297        };
298
299        self.plot_sector_internal(
300            start,
301            sector_encoding_permit,
302            public_key,
303            shard_commitments_root,
304            sector_index,
305            farmer_protocol_info,
306            pieces_in_sector,
307            progress_sender,
308        )
309        .await;
310
311        true
312    }
313}
314
315impl ClusterPlotter {
316    /// Create a new instance
317    pub fn new(
318        nats_client: NatsClient,
319        sector_encoding_concurrency: NonZeroUsize,
320        retry_backoff_policy: ExponentialBuilder,
321    ) -> Self {
322        let sector_encoding_semaphore =
323            StdArc::new(Semaphore::new(sector_encoding_concurrency.get()));
324
325        let (tasks_sender, mut tasks_receiver) = mpsc::channel(1);
326
327        // Basically runs plotting tasks in the background and allows to abort on drop
328        let background_tasks = AsyncJoinOnDrop::new(
329            tokio::spawn(async move {
330                let background_tasks = FuturesUnordered::new();
331                let mut background_tasks = pin!(background_tasks);
332                // Just so that `FuturesUnordered` will never end
333                background_tasks.push(AsyncJoinOnDrop::new(tokio::spawn(pending::<()>()), true));
334
335                loop {
336                    select! {
337                        maybe_background_task = tasks_receiver.next().fuse() => {
338                            let Some(background_task) = maybe_background_task else {
339                                break;
340                            };
341
342                            background_tasks.push(background_task);
343                        },
344                        _ = background_tasks.select_next_some() => {
345                            // Nothing to do
346                        }
347                    }
348                }
349            }),
350            true,
351        );
352
353        Self {
354            sector_encoding_semaphore,
355            retry_backoff_policy,
356            nats_client,
357            handlers: Arc::default(),
358            tasks_sender,
359            _background_tasks: background_tasks,
360        }
361    }
362
363    /// Subscribe to plotting progress notifications
364    pub fn on_plotting_progress(
365        &self,
366        callback: HandlerFn3<Ed25519PublicKey, SectorIndex, SectorPlottingProgress>,
367    ) -> HandlerId {
368        self.handlers.plotting_progress.add(callback)
369    }
370
371    #[expect(clippy::too_many_arguments, reason = "Internal API")]
372    async fn plot_sector_internal<PS>(
373        &self,
374        start: Instant,
375        sector_encoding_permit: OwnedSemaphorePermit,
376        public_key: Ed25519PublicKey,
377        shard_commitments_root: ShardCommitmentHash,
378        sector_index: SectorIndex,
379        farmer_protocol_info: FarmerProtocolInfo,
380        pieces_in_sector: u16,
381        mut progress_sender: PS,
382    ) where
383        PS: Sink<SectorPlottingProgress, Error: Error> + Unpin + Send + 'static,
384    {
385        trace!("Starting plotting, getting plotting permit");
386
387        let progress_updater = ProgressUpdater {
388            public_key,
389            sector_index,
390            handlers: Arc::clone(&self.handlers),
391        };
392
393        let mut retry_backoff_policy = self.retry_backoff_policy.build();
394
395        // Try to get plotter instance here first as a backpressure measure
396        let free_plotter_instance_fut = get_free_plotter_instance(
397            &self.nats_client,
398            &progress_updater,
399            &mut progress_sender,
400            &mut retry_backoff_policy,
401        );
402        let mut maybe_free_instance = free_plotter_instance_fut.await;
403        if maybe_free_instance.is_none() {
404            return;
405        }
406
407        trace!("Got plotting permit #1");
408
409        let nats_client = self.nats_client.clone();
410
411        let plotting_fut = async move {
412            'outer: loop {
413                // Take free instance that was found earlier if available or try to find a new one
414                let free_instance = if let Some(free_instance) = maybe_free_instance.take() {
415                    free_instance
416                } else {
417                    let free_plotter_instance_fut = get_free_plotter_instance(
418                        &nats_client,
419                        &progress_updater,
420                        &mut progress_sender,
421                        &mut retry_backoff_policy,
422                    );
423                    let Some(free_instance) = free_plotter_instance_fut.await else {
424                        break;
425                    };
426                    trace!("Got plotting permit #2");
427                    free_instance
428                };
429
430                let response_stream_result = nats_client
431                    .stream_request(
432                        &ClusterPlotterPlotSectorRequest {
433                            public_key,
434                            shard_commitments_root,
435                            sector_index,
436                            farmer_protocol_info,
437                            pieces_in_sector,
438                        },
439                        Some(&free_instance),
440                    )
441                    .await;
442                trace!("Subscribed to plotting notifications");
443
444                let mut response_stream = match response_stream_result {
445                    Ok(response_stream) => response_stream,
446                    Err(error) => {
447                        progress_updater
448                            .update_progress_and_events(
449                                &mut progress_sender,
450                                SectorPlottingProgress::Error {
451                                    error: format!("Failed make stream request: {error}"),
452                                },
453                            )
454                            .await;
455
456                        break;
457                    }
458                };
459
460                // Allow to buffer up to the whole sector in memory to not block plotter on the
461                // other side
462                let (mut sector_sender, sector_receiver) = mpsc::channel(
463                    sector_size(pieces_in_sector)
464                        .div_ceil(sector_chunk_size(&nats_client) as usize),
465                );
466                let mut maybe_sector_receiver = Some(sector_receiver);
467                loop {
468                    match tokio::time::timeout(PING_TIMEOUT, response_stream.next()).await {
469                        Ok(Some(response)) => {
470                            match process_response_notification(
471                                &start,
472                                &free_instance,
473                                &progress_updater,
474                                &mut progress_sender,
475                                &mut retry_backoff_policy,
476                                response,
477                                &mut sector_sender,
478                                &mut maybe_sector_receiver,
479                            )
480                            .await
481                            {
482                                ResponseProcessingResult::Retry => {
483                                    debug!("Retrying");
484                                    continue 'outer;
485                                }
486                                ResponseProcessingResult::Abort => {
487                                    debug!("Aborting");
488                                    break 'outer;
489                                }
490                                ResponseProcessingResult::Continue => {
491                                    trace!("Continue");
492                                    // Nothing to do
493                                }
494                            }
495                        }
496                        Ok(None) => {
497                            trace!("Plotting done");
498                            break;
499                        }
500                        Err(_error) => {
501                            progress_updater
502                                .update_progress_and_events(
503                                    &mut progress_sender,
504                                    SectorPlottingProgress::Error {
505                                        error: "Timed out without ping from plotter".to_string(),
506                                    },
507                                )
508                                .await;
509                            break;
510                        }
511                    }
512                }
513
514                break;
515            }
516
517            drop(sector_encoding_permit);
518        };
519
520        let plotting_task =
521            AsyncJoinOnDrop::new(tokio::spawn(plotting_fut.in_current_span()), true);
522        if let Err(error) = self.tasks_sender.clone().send(plotting_task).await {
523            warn!(%error, "Failed to send plotting task");
524
525            let progress = SectorPlottingProgress::Error {
526                error: format!("Failed to send plotting task: {error}"),
527            };
528
529            self.handlers
530                .plotting_progress
531                .call_simple(&public_key, &sector_index, &progress);
532        }
533    }
534}
535
536// Try to get free plotter instance and return `None` if it is not possible
537async fn get_free_plotter_instance<PS>(
538    nats_client: &NatsClient,
539    progress_updater: &ProgressUpdater,
540    progress_sender: &mut PS,
541    retry_backoff_policy: &mut ExponentialBackoff,
542) -> Option<String>
543where
544    PS: Sink<SectorPlottingProgress, Error: Error> + Unpin + Send + 'static,
545{
546    loop {
547        match nats_client
548            .request(&ClusterPlotterFreeInstanceRequest, None)
549            .await
550        {
551            Ok(Some(free_instance)) => {
552                return Some(free_instance);
553            }
554            Ok(None) => {
555                let Some(delay) = retry_backoff_policy.next() else {
556                    progress_updater
557                        .update_progress_and_events(
558                            progress_sender,
559                            SectorPlottingProgress::Error {
560                                error: "Instance was occupied, exiting #1".to_string(),
561                            },
562                        )
563                        .await;
564                    return None;
565                };
566
567                debug!("Instance was occupied, retrying #1");
568
569                tokio::time::sleep(delay).await;
570            }
571            Err(error) => match error.kind() {
572                RequestErrorKind::TimedOut => {
573                    let Some(delay) = retry_backoff_policy.next() else {
574                        progress_updater
575                            .update_progress_and_events(
576                                progress_sender,
577                                SectorPlottingProgress::Error {
578                                    error: "Plotter request timed out, exiting".to_string(),
579                                },
580                            )
581                            .await;
582                        return None;
583                    };
584
585                    debug!("Plotter request timed out, retrying");
586
587                    tokio::time::sleep(delay).await;
588                }
589                RequestErrorKind::NoResponders => {
590                    let Some(delay) = retry_backoff_policy.next() else {
591                        progress_updater
592                            .update_progress_and_events(
593                                progress_sender,
594                                SectorPlottingProgress::Error {
595                                    error: "No plotters, exiting".to_string(),
596                                },
597                            )
598                            .await;
599                        return None;
600                    };
601
602                    debug!("No plotters, retrying");
603
604                    tokio::time::sleep(delay).await;
605                }
606                RequestErrorKind::InvalidSubject
607                | RequestErrorKind::MaxPayloadExceeded
608                | RequestErrorKind::Other => {
609                    progress_updater
610                        .update_progress_and_events(
611                            progress_sender,
612                            SectorPlottingProgress::Error {
613                                error: format!("Failed to get free plotter instance: {error}"),
614                            },
615                        )
616                        .await;
617                    return None;
618                }
619            },
620        }
621    }
622}
623
624enum ResponseProcessingResult {
625    Retry,
626    Abort,
627    Continue,
628}
629
630#[expect(clippy::too_many_arguments, reason = "Internal API")]
631async fn process_response_notification<PS>(
632    start: &Instant,
633    free_instance: &str,
634    progress_updater: &ProgressUpdater,
635    progress_sender: &mut PS,
636    retry_backoff_policy: &mut ExponentialBackoff,
637    response: ClusterSectorPlottingProgress,
638    sector_sender: &mut mpsc::Sender<Result<SharedAlignedBuffer<Align4096>, String>>,
639    maybe_sector_receiver: &mut Option<
640        mpsc::Receiver<Result<SharedAlignedBuffer<Align4096>, String>>,
641    >,
642) -> ResponseProcessingResult
643where
644    PS: Sink<SectorPlottingProgress, Error: Error> + Unpin + Send + 'static,
645{
646    if matches!(response, ClusterSectorPlottingProgress::SectorChunk(_)) {
647        trace!("Processing plotting response notification (sector chunk)");
648    } else {
649        trace!(?response, "Processing plotting response notification");
650    }
651
652    match response {
653        ClusterSectorPlottingProgress::Occupied => {
654            debug!(%free_instance, "Instance was occupied, retrying #2");
655
656            return if let Some(delay) = retry_backoff_policy.next() {
657                debug!("Instance was occupied, retrying #2");
658
659                tokio::time::sleep(delay).await;
660                ResponseProcessingResult::Retry
661            } else {
662                debug!("Instance was occupied, exiting #2");
663                ResponseProcessingResult::Abort
664            };
665        }
666        ClusterSectorPlottingProgress::Ping => {
667            // Expected
668        }
669        ClusterSectorPlottingProgress::Downloading => {
670            if !progress_updater
671                .update_progress_and_events(progress_sender, SectorPlottingProgress::Downloading)
672                .await
673            {
674                return ResponseProcessingResult::Abort;
675            }
676        }
677        ClusterSectorPlottingProgress::Downloaded(time) => {
678            if !progress_updater
679                .update_progress_and_events(
680                    progress_sender,
681                    SectorPlottingProgress::Downloaded(time),
682                )
683                .await
684            {
685                return ResponseProcessingResult::Abort;
686            }
687        }
688        ClusterSectorPlottingProgress::Encoding => {
689            if !progress_updater
690                .update_progress_and_events(progress_sender, SectorPlottingProgress::Encoding)
691                .await
692            {
693                return ResponseProcessingResult::Abort;
694            }
695        }
696        ClusterSectorPlottingProgress::Encoded(time) => {
697            if !progress_updater
698                .update_progress_and_events(progress_sender, SectorPlottingProgress::Encoded(time))
699                .await
700            {
701                return ResponseProcessingResult::Abort;
702            }
703        }
704        ClusterSectorPlottingProgress::Finished {
705            plotted_sector,
706            time: _,
707        } => {
708            let Some(sector_receiver) = maybe_sector_receiver.take() else {
709                debug!("Unexpected duplicated sector plotting progress Finished");
710
711                progress_updater
712                    .update_progress_and_events(
713                        progress_sender,
714                        SectorPlottingProgress::Error {
715                            error: "Unexpected duplicated sector plotting progress Finished"
716                                .to_string(),
717                        },
718                    )
719                    .await;
720                return ResponseProcessingResult::Abort;
721            };
722
723            let progress = SectorPlottingProgress::Finished {
724                plotted_sector,
725                // Use local time instead of reported by remote plotter
726                time: start.elapsed(),
727                sector: Box::pin(sector_receiver),
728            };
729            if !progress_updater
730                .update_progress_and_events(progress_sender, progress)
731                .await
732            {
733                return ResponseProcessingResult::Abort;
734            }
735
736            return ResponseProcessingResult::Continue;
737        }
738        // This variant must be sent after Finished and it handled above
739        ClusterSectorPlottingProgress::SectorChunk(maybe_sector_chunk) => {
740            let maybe_sector_chunk =
741                maybe_sector_chunk.map(|SectorChunk(sector_chunk)| sector_chunk);
742            if let Err(error) = sector_sender.send(maybe_sector_chunk).await {
743                warn!(%error, "Failed to send sector chunk");
744                return ResponseProcessingResult::Abort;
745            }
746            return ResponseProcessingResult::Continue;
747        }
748        ClusterSectorPlottingProgress::Error { error } => {
749            if !progress_updater
750                .update_progress_and_events(
751                    progress_sender,
752                    SectorPlottingProgress::Error { error },
753                )
754                .await
755            {
756                return ResponseProcessingResult::Abort;
757            }
758        }
759    }
760
761    ResponseProcessingResult::Continue
762}
763
764struct ProgressUpdater {
765    public_key: Ed25519PublicKey,
766    sector_index: SectorIndex,
767    handlers: Arc<Handlers>,
768}
769
770impl ProgressUpdater {
771    /// Returns `true` on success and `false` if progress receiver channel is gone
772    async fn update_progress_and_events<PS>(
773        &self,
774        progress_sender: &mut PS,
775        progress: SectorPlottingProgress,
776    ) -> bool
777    where
778        PS: Sink<SectorPlottingProgress, Error: Error> + Unpin,
779    {
780        self.handlers.plotting_progress.call_simple(
781            &self.public_key,
782            &self.sector_index,
783            &progress,
784        );
785
786        if let Err(error) = progress_sender.send(progress).await {
787            warn!(%error, "Failed to send error progress update");
788
789            false
790        } else {
791            true
792        }
793    }
794}
795
796/// Create plotter service that will be processing incoming requests.
797///
798/// Implementation is using concurrency with multiple tokio tasks, but can be started multiple times
799/// per controller instance in order to parallelize more work across threads if needed.
800pub async fn plotter_service<P>(nats_client: &NatsClient, plotter: &P) -> anyhow::Result<()>
801where
802    P: Plotter + Sync,
803{
804    let plotter_id = ClusterPlotterId::new();
805
806    select! {
807        result = free_instance_responder(&plotter_id, nats_client, plotter).fuse() => {
808            result
809        }
810        result = plot_sector_responder(&plotter_id, nats_client, plotter).fuse() => {
811            result
812        }
813    }
814}
815
816async fn free_instance_responder<P>(
817    plotter_id: &ClusterPlotterId,
818    nats_client: &NatsClient,
819    plotter: &P,
820) -> anyhow::Result<()>
821where
822    P: Plotter + Sync,
823{
824    loop {
825        while !plotter.has_free_capacity().await.unwrap_or_default() {
826            tokio::time::sleep(FREE_CAPACITY_CHECK_INTERVAL).await;
827        }
828
829        let mut subscription = nats_client
830            .queue_subscribe(
831                ClusterPlotterFreeInstanceRequest::SUBJECT,
832                "ab.plotter".to_string(),
833            )
834            .await
835            .map_err(|error| anyhow!("Failed to subscribe to free instance requests: {error}"))?;
836        debug!(?subscription, "Free instance subscription");
837
838        while let Some(message) = subscription.next().await {
839            let Some(reply_subject) = message.reply else {
840                continue;
841            };
842
843            debug!(%reply_subject, "Free instance request");
844
845            let has_free_capacity = plotter.has_free_capacity().await.unwrap_or_default();
846            let response: <ClusterPlotterFreeInstanceRequest as GenericRequest>::Response =
847                has_free_capacity.then(|| plotter_id.to_string());
848
849            if let Err(error) = nats_client
850                .publish(reply_subject, response.encode().into())
851                .await
852            {
853                warn!(%error, "Failed to send free instance response");
854            }
855
856            if !has_free_capacity {
857                subscription.unsubscribe().await.map_err(|error| {
858                    anyhow!("Failed to unsubscribe from free instance requests: {error}")
859                })?;
860            }
861        }
862    }
863}
864
865async fn plot_sector_responder<P>(
866    plotter_id: &ClusterPlotterId,
867    nats_client: &NatsClient,
868    plotter: &P,
869) -> anyhow::Result<()>
870where
871    P: Plotter + Sync,
872{
873    let plotter_id_string = plotter_id.to_string();
874
875    nats_client
876        .stream_request_responder(
877            Some(&plotter_id_string),
878            Some(plotter_id_string.clone()),
879            |request| async move {
880                let (progress_sender, mut progress_receiver) = mpsc::channel(10);
881
882                let fut =
883                    process_plot_sector_request(nats_client, plotter, request, progress_sender);
884                let mut fut = Box::pin(fut.fuse());
885
886                Some(
887                    // Drive above future and stream back any pieces that were downloaded so far
888                    stream::poll_fn(move |cx| {
889                        if !fut.is_terminated() {
890                            // Result doesn't matter, we'll need to poll stream below anyway
891                            let _: Poll<()> = fut.poll_unpin(cx);
892                        }
893
894                        if let Poll::Ready(maybe_result) = progress_receiver.poll_next_unpin(cx) {
895                            return Poll::Ready(maybe_result);
896                        }
897
898                        // Exit will be done by the stream above
899                        Poll::Pending
900                    }),
901                )
902            },
903        )
904        .await
905}
906
907async fn process_plot_sector_request<P>(
908    nats_client: &NatsClient,
909    plotter: &P,
910    request: ClusterPlotterPlotSectorRequest,
911    mut response_proxy_sender: mpsc::Sender<ClusterSectorPlottingProgress>,
912) where
913    P: Plotter,
914{
915    let ClusterPlotterPlotSectorRequest {
916        public_key,
917        shard_commitments_root,
918        sector_index,
919        farmer_protocol_info,
920        pieces_in_sector,
921    } = request;
922
923    // Wrapper future just for instrumentation below
924    let inner_fut = async {
925        info!("Plot sector request");
926
927        let (progress_sender, mut progress_receiver) = mpsc::channel(1);
928
929        if !plotter
930            .try_plot_sector(
931                public_key,
932                shard_commitments_root,
933                sector_index,
934                farmer_protocol_info,
935                pieces_in_sector,
936                false,
937                progress_sender,
938            )
939            .await
940        {
941            debug!("Plotter is currently occupied and can't plot more sectors");
942
943            if let Err(error) = response_proxy_sender
944                .send(ClusterSectorPlottingProgress::Occupied)
945                .await
946            {
947                warn!(%error, "Failed to send plotting progress");
948                return;
949            }
950            return;
951        }
952
953        let progress_proxy_fut = {
954            let mut response_proxy_sender = response_proxy_sender.clone();
955            let sector_chunk_size = sector_chunk_size(nats_client);
956
957            async move {
958                while let Some(progress) = progress_receiver.next().await {
959                    send_publish_progress(&mut response_proxy_sender, progress, sector_chunk_size)
960                        .await;
961                }
962            }
963        };
964
965        let mut ping_interval = tokio::time::interval(PING_INTERVAL);
966        ping_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
967        let ping_fut = async {
968            loop {
969                ping_interval.tick().await;
970                if let Err(error) = response_proxy_sender
971                    .send(ClusterSectorPlottingProgress::Ping)
972                    .await
973                {
974                    warn!(%error, "Failed to send plotting ping");
975                    return;
976                }
977            }
978        };
979
980        select! {
981            () = progress_proxy_fut.fuse() => {
982                // Done
983            }
984            () = ping_fut.fuse() => {
985                unreachable!("Ping loop never ends");
986            }
987        }
988
989        info!("Finished plotting sector successfully");
990    };
991
992    inner_fut
993        .instrument(info_span!("", %public_key, %sector_index))
994        .await;
995}
996
997async fn send_publish_progress(
998    response_sender: &mut mpsc::Sender<ClusterSectorPlottingProgress>,
999    progress: SectorPlottingProgress,
1000    sector_chunk_size: u32,
1001) {
1002    // Finished response is large and needs special care
1003    let cluster_progress = match progress {
1004        SectorPlottingProgress::Downloading => ClusterSectorPlottingProgress::Downloading,
1005        SectorPlottingProgress::Downloaded(time) => ClusterSectorPlottingProgress::Downloaded(time),
1006        SectorPlottingProgress::Encoding => ClusterSectorPlottingProgress::Encoding,
1007        SectorPlottingProgress::Encoded(time) => ClusterSectorPlottingProgress::Encoded(time),
1008        SectorPlottingProgress::Finished {
1009            plotted_sector,
1010            time,
1011            mut sector,
1012        } => {
1013            if let Err(error) = response_sender
1014                .send(ClusterSectorPlottingProgress::Finished {
1015                    plotted_sector,
1016                    time,
1017                })
1018                .await
1019            {
1020                warn!(%error, "Failed to send plotting progress");
1021                return;
1022            }
1023
1024            while let Some(maybe_sector_chunk) = sector.next().await {
1025                match maybe_sector_chunk {
1026                    Ok(sector_chunk) => {
1027                        // Slice large chunks into smaller ones before publishing
1028                        let mut start = 0;
1029                        while start < sector_chunk.len() {
1030                            let end = start
1031                                .saturating_add(sector_chunk_size)
1032                                .min(sector_chunk.len());
1033                            let small_sector_chunk = sector_chunk
1034                                .get_slice(start..end)
1035                                .expect("Within the sector chunk; qed")
1036                                .try_into_start_align::<Align4096>()
1037                                .expect(
1038                                    "Sector chunk is aligned to the page size, and the chunk size \
1039                                    is a multiple of it; qed",
1040                                );
1041                            start = end;
1042
1043                            if let Err(error) = response_sender
1044                                .send(ClusterSectorPlottingProgress::SectorChunk(Ok(SectorChunk(
1045                                    small_sector_chunk,
1046                                ))))
1047                                .await
1048                            {
1049                                warn!(%error, "Failed to send plotting progress");
1050                                return;
1051                            }
1052                        }
1053                    }
1054                    Err(error) => {
1055                        if let Err(error) = response_sender
1056                            .send(ClusterSectorPlottingProgress::SectorChunk(Err(error)))
1057                            .await
1058                        {
1059                            warn!(%error, "Failed to send plotting progress");
1060                            return;
1061                        }
1062                    }
1063                }
1064            }
1065
1066            return;
1067        }
1068        SectorPlottingProgress::Error { error } => ClusterSectorPlottingProgress::Error { error },
1069    };
1070
1071    if let Err(error) = response_sender.send(cluster_progress).await {
1072        warn!(%error, "Failed to send plotting progress");
1073    }
1074}