Skip to main content

ab_farmer/
plotter.rs

1//! Plotter abstraction
2//!
3//! Plotter is abstracted away to support different implementations. Originally it was just CPU, but
4//! eventually abstract network-attached, GPU and hybrid plotters became an option as well. Having a
5//! trait with async API representing plotting functionality allows composition of different
6//! implementations without the rest of the farmer being aware of implementation details.
7
8pub mod cpu;
9pub mod gpu;
10pub mod pool;
11
12use ab_aligned_buffer::SharedAlignedBuffer;
13use ab_aligned_buffer::alignment::Align4096;
14use ab_core_primitives::ed25519::Ed25519PublicKey;
15use ab_core_primitives::sectors::SectorIndex;
16use ab_core_primitives::solutions::ShardCommitmentHash;
17use ab_farmer_components::FarmerProtocolInfo;
18use ab_farmer_components::plotting::PlottedSector;
19use async_trait::async_trait;
20use futures::Stream;
21use futures::channel::mpsc;
22use std::fmt;
23use std::pin::Pin;
24use std::time::Duration;
25use triomphe::Arc;
26
27/// Sector plotting progress
28pub enum SectorPlottingProgress {
29    /// Downloading sector pieces
30    Downloading,
31    /// Downloaded sector pieces
32    Downloaded(Duration),
33    /// Encoding sector pieces
34    Encoding,
35    /// Encoded sector pieces
36    Encoded(Duration),
37    /// Finished plotting
38    Finished {
39        /// Information about the plotted sector
40        plotted_sector: PlottedSector,
41        /// How much time it took to plot a sector
42        time: Duration,
43        /// Stream of all plotted sector bytes in chunks, whose contents are aligned to the page
44        /// size for direct I/O
45        sector: Pin<
46            Box<dyn Stream<Item = Result<SharedAlignedBuffer<Align4096>, String>> + Send + Sync>,
47        >,
48    },
49    /// Plotting failed
50    Error {
51        /// Error message
52        error: String,
53    },
54}
55
56impl fmt::Debug for SectorPlottingProgress {
57    #[inline]
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            Self::Downloading => f.write_str("Downloading"),
61            Self::Downloaded(time) => f.debug_tuple("Downloaded").field(time).finish(),
62            Self::Encoding => f.write_str("Encoding"),
63            Self::Encoded(time) => f.debug_tuple("Encoded").field(time).finish(),
64            Self::Finished {
65                plotted_sector,
66                time,
67                sector: _,
68            } => f
69                .debug_struct("Finished")
70                .field("plotted_sector", plotted_sector)
71                .field("time", time)
72                .field("sector", &format_args!("<stream>"))
73                .finish(),
74            Self::Error { error } => f.debug_struct("Error").field("error", error).finish(),
75        }
76    }
77}
78
79/// Abstract plotter implementation
80#[async_trait]
81pub trait Plotter: fmt::Debug {
82    /// Whether plotter has free capacity to encode more sectors
83    async fn has_free_capacity(&self) -> Result<bool, String>;
84
85    /// Plot one sector, sending sector plotting events via the provided stream.
86    ///
87    /// Future returns once plotting is successfully scheduled (for backpressure purposes).
88    // TODO: Struct for arguments
89    #[expect(clippy::too_many_arguments, reason = "TODO")]
90    async fn plot_sector(
91        &self,
92        public_key: Ed25519PublicKey,
93        shard_commitments_root: ShardCommitmentHash,
94        sector_index: SectorIndex,
95        farmer_protocol_info: FarmerProtocolInfo,
96        pieces_in_sector: u16,
97        replotting: bool,
98        progress_sender: mpsc::Sender<SectorPlottingProgress>,
99    );
100
101    /// Try to plot one sector, sending sector plotting events via the provided stream.
102    ///
103    /// Returns `true` if plotting started successfully and `false` if there is no capacity to start
104    /// plotting immediately.
105    // TODO: Struct for arguments
106    #[expect(clippy::too_many_arguments, reason = "TODO")]
107    async fn try_plot_sector(
108        &self,
109        public_key: Ed25519PublicKey,
110        shard_commitments_root: ShardCommitmentHash,
111        sector_index: SectorIndex,
112        farmer_protocol_info: FarmerProtocolInfo,
113        pieces_in_sector: u16,
114        replotting: bool,
115        progress_sender: mpsc::Sender<SectorPlottingProgress>,
116    ) -> bool;
117}
118
119#[async_trait]
120impl<P> Plotter for Arc<P>
121where
122    P: Plotter + Send + Sync,
123{
124    #[inline]
125    async fn has_free_capacity(&self) -> Result<bool, String> {
126        self.as_ref().has_free_capacity().await
127    }
128
129    #[inline]
130    async fn plot_sector(
131        &self,
132        public_key: Ed25519PublicKey,
133        shard_commitments_root: ShardCommitmentHash,
134        sector_index: SectorIndex,
135        farmer_protocol_info: FarmerProtocolInfo,
136        pieces_in_sector: u16,
137        replotting: bool,
138        progress_sender: mpsc::Sender<SectorPlottingProgress>,
139    ) {
140        self.as_ref()
141            .plot_sector(
142                public_key,
143                shard_commitments_root,
144                sector_index,
145                farmer_protocol_info,
146                pieces_in_sector,
147                replotting,
148                progress_sender,
149            )
150            .await;
151    }
152
153    #[inline]
154    async fn try_plot_sector(
155        &self,
156        public_key: Ed25519PublicKey,
157        shard_commitments_root: ShardCommitmentHash,
158        sector_index: SectorIndex,
159        farmer_protocol_info: FarmerProtocolInfo,
160        pieces_in_sector: u16,
161        replotting: bool,
162        progress_sender: mpsc::Sender<SectorPlottingProgress>,
163    ) -> bool {
164        self.as_ref()
165            .try_plot_sector(
166                public_key,
167                shard_commitments_root,
168                sector_index,
169                farmer_protocol_info,
170                pieces_in_sector,
171                replotting,
172                progress_sender,
173            )
174            .await
175    }
176}