Skip to main content

ogmios_client/chain_synchronization/
client.rs

1//! Chain Synchronization client implementation.
2
3use crate::connection::{
4    create_interaction_context, ConnectionConfig, InteractionContext, InteractionContextOptions,
5    InteractionType,
6};
7use crate::error::Result;
8use crate::schema::{responses::NextBlockResponse, Block, Point, Tip};
9use std::sync::Arc;
10use tokio::sync::Mutex;
11use tracing::{debug, error, info, trace};
12
13use super::{find_intersection, next_block, ChainSynchronizationMessageHandlers, Intersection};
14
15/// Options for creating a chain synchronization client.
16#[derive(Default)]
17pub struct ChainSynchronizationClientOptions {
18    /// Process blocks sequentially (one at a time).
19    pub sequential: bool,
20}
21
22/// A chain synchronization client for following the Cardano blockchain.
23///
24/// This client implements the Ouroboros chain-sync mini-protocol, allowing
25/// you to follow the blockchain from a specific point and receive notifications
26/// about new blocks and rollbacks.
27///
28/// # Example
29///
30/// ```rust,no_run
31/// use ogmios_client::chain_synchronization::{
32///     ChainSynchronizationClient,
33///     ChainSynchronizationMessageHandlers,
34/// };
35/// use ogmios_client::connection::{ConnectionConfig, create_interaction_context, InteractionContextOptions, InteractionType};
36/// use ogmios_client::schema::{Block, Point, Tip};
37/// use ogmios_client::error::Result;
38///
39/// struct MyHandler;
40///
41/// impl ChainSynchronizationMessageHandlers for MyHandler {
42///     fn on_roll_forward(&mut self, block: Block, tip: Tip) -> Result<()> {
43///         println!("New block at slot {}", block.slot());
44///         Ok(())
45///     }
46///
47///     fn on_roll_backward(&mut self, point: Point, tip: Tip) -> Result<()> {
48///         println!("Rollback to {:?}", point);
49///         Ok(())
50///     }
51/// }
52///
53/// # async fn example() -> Result<()> {
54/// let context = create_interaction_context(InteractionContextOptions {
55///     connection: ConnectionConfig::default(),
56///     interaction_type: InteractionType::LongRunning,
57///     ..Default::default()
58/// }).await?;
59///
60/// let client = ChainSynchronizationClient::new(context, MyHandler, Default::default()).await?;
61///
62/// // Start syncing from origin
63/// let intersection = client.resume(Some(vec![Point::origin()]), None).await?;
64/// println!("Started at {:?}", intersection.point);
65/// # Ok(())
66/// # }
67/// ```
68pub struct ChainSynchronizationClient<H: ChainSynchronizationMessageHandlers> {
69    /// The interaction context.
70    context: Arc<InteractionContext>,
71    /// Message handlers.
72    handlers: Arc<Mutex<H>>,
73    /// Client options.
74    options: ChainSynchronizationClientOptions,
75    /// Whether the client is currently running.
76    running: Arc<std::sync::atomic::AtomicBool>,
77}
78
79impl<H: ChainSynchronizationMessageHandlers + 'static> ChainSynchronizationClient<H> {
80    /// Create a new chain synchronization client.
81    ///
82    /// # Arguments
83    ///
84    /// * `context` - The interaction context.
85    /// * `handlers` - Message handlers for block events.
86    /// * `options` - Client options.
87    pub async fn new(
88        context: InteractionContext,
89        handlers: H,
90        options: ChainSynchronizationClientOptions,
91    ) -> Result<Self> {
92        Ok(Self {
93            context: Arc::new(context),
94            handlers: Arc::new(Mutex::new(handlers)),
95            options,
96            running: Arc::new(std::sync::atomic::AtomicBool::new(false)),
97        })
98    }
99
100    /// Get a reference to the interaction context.
101    pub fn context(&self) -> &InteractionContext {
102        &self.context
103    }
104
105    /// Check if the client is currently running.
106    pub fn is_running(&self) -> bool {
107        self.running.load(std::sync::atomic::Ordering::SeqCst)
108    }
109
110    /// Resume chain synchronization from given points.
111    ///
112    /// This function finds an intersection with the provided points and starts
113    /// synchronizing from that point.
114    ///
115    /// # Arguments
116    ///
117    /// * `points` - Optional list of points to try to intersect with. If not provided,
118    ///              starts from the origin.
119    /// * `in_flight` - Optional number of blocks to request in parallel.
120    ///
121    /// # Returns
122    ///
123    /// The intersection point that was found.
124    pub async fn resume(
125        &self,
126        points: Option<Vec<Point>>,
127        _in_flight: Option<u32>,
128    ) -> Result<Intersection> {
129        let points = points.unwrap_or_else(|| vec![Point::origin()]);
130        let intersection = find_intersection(&self.context, points).await?;
131
132        info!(
133            "Chain sync resumed from {:?}, tip at {:?}",
134            intersection.point, intersection.tip
135        );
136
137        // Start the sync loop
138        self.running
139            .store(true, std::sync::atomic::Ordering::SeqCst);
140
141        let context = self.context.clone();
142        let handlers = self.handlers.clone();
143        let running = self.running.clone();
144        let sequential = self.options.sequential;
145
146        tokio::spawn(async move {
147            if let Err(e) = run_sync_loop(context, handlers, running.clone(), sequential).await {
148                error!("Chain sync error: {}", e);
149            }
150            running.store(false, std::sync::atomic::Ordering::SeqCst);
151        });
152
153        Ok(intersection)
154    }
155
156    /// Shutdown the chain synchronization client.
157    pub async fn shutdown(&self) -> Result<()> {
158        self.running
159            .store(false, std::sync::atomic::Ordering::SeqCst);
160        self.context.shutdown().await
161    }
162}
163
164/// Run the synchronization loop.
165async fn run_sync_loop<H: ChainSynchronizationMessageHandlers>(
166    context: Arc<InteractionContext>,
167    handlers: Arc<Mutex<H>>,
168    running: Arc<std::sync::atomic::AtomicBool>,
169    _sequential: bool,
170) -> Result<()> {
171    while running.load(std::sync::atomic::Ordering::SeqCst) {
172        if !context.is_socket_open() {
173            debug!("Socket closed, stopping sync loop");
174            break;
175        }
176
177        match next_block(&context).await {
178            Ok(response) => {
179                let mut handlers = handlers.lock().await;
180                match response {
181                    NextBlockResponse::Forward { block, tip } => {
182                        trace!("Received block at slot {}", block.slot());
183                        if let Err(e) = handlers.on_roll_forward(block, tip) {
184                            error!("Error in roll forward handler: {}", e);
185                            return Err(e);
186                        }
187                    }
188                    NextBlockResponse::Backward { point, tip } => {
189                        debug!("Rollback to {:?}", point);
190                        if let Err(e) = handlers.on_roll_backward(point, tip) {
191                            error!("Error in roll backward handler: {}", e);
192                            return Err(e);
193                        }
194                    }
195                }
196            }
197            Err(e) => {
198                if running.load(std::sync::atomic::Ordering::SeqCst) {
199                    error!("Error getting next block: {}", e);
200                    return Err(e);
201                }
202                break;
203            }
204        }
205    }
206
207    Ok(())
208}
209
210/// Create a chain synchronization client.
211///
212/// This is a convenience function that creates an interaction context and
213/// a chain synchronization client in one step.
214///
215/// # Arguments
216///
217/// * `connection` - Connection configuration.
218/// * `handlers` - Message handlers for block events.
219/// * `options` - Optional client options.
220///
221/// # Returns
222///
223/// A new chain synchronization client.
224pub async fn create_chain_synchronization_client<
225    H: ChainSynchronizationMessageHandlers + 'static,
226>(
227    connection: ConnectionConfig,
228    handlers: H,
229    options: Option<ChainSynchronizationClientOptions>,
230) -> Result<ChainSynchronizationClient<H>> {
231    let context = create_interaction_context(InteractionContextOptions {
232        connection,
233        interaction_type: InteractionType::LongRunning,
234        ..Default::default()
235    })
236    .await?;
237
238    ChainSynchronizationClient::new(context, handlers, options.unwrap_or_default()).await
239}
240
241/// A simple handler that collects blocks into a vector.
242///
243/// Useful for testing or batch processing.
244pub struct CollectingHandler {
245    /// Collected blocks.
246    pub blocks: Vec<Block>,
247    /// Points where rollbacks occurred.
248    pub rollbacks: Vec<Point>,
249    /// Maximum blocks to collect (None for unlimited).
250    pub max_blocks: Option<usize>,
251}
252
253impl CollectingHandler {
254    /// Create a new collecting handler.
255    pub fn new(max_blocks: Option<usize>) -> Self {
256        Self {
257            blocks: Vec::new(),
258            rollbacks: Vec::new(),
259            max_blocks,
260        }
261    }
262
263    /// Check if the handler has reached the maximum block count.
264    pub fn is_complete(&self) -> bool {
265        self.max_blocks
266            .map_or(false, |max| self.blocks.len() >= max)
267    }
268}
269
270impl ChainSynchronizationMessageHandlers for CollectingHandler {
271    fn on_roll_forward(&mut self, block: Block, _tip: Tip) -> Result<()> {
272        self.blocks.push(block);
273        Ok(())
274    }
275
276    fn on_roll_backward(&mut self, point: Point, _tip: Tip) -> Result<()> {
277        self.rollbacks.push(point);
278        Ok(())
279    }
280}
281
282/// A handler that calls closures for each event.
283///
284/// This is useful for simple use cases where you don't need a full struct.
285pub struct FnHandler<F, B>
286where
287    F: FnMut(Block, Tip) -> Result<()> + Send + Sync,
288    B: FnMut(Point, Tip) -> Result<()> + Send + Sync,
289{
290    on_forward: F,
291    on_backward: B,
292}
293
294impl<F, B> FnHandler<F, B>
295where
296    F: FnMut(Block, Tip) -> Result<()> + Send + Sync,
297    B: FnMut(Point, Tip) -> Result<()> + Send + Sync,
298{
299    /// Create a new function-based handler.
300    pub fn new(on_forward: F, on_backward: B) -> Self {
301        Self {
302            on_forward,
303            on_backward,
304        }
305    }
306}
307
308impl<F, B> ChainSynchronizationMessageHandlers for FnHandler<F, B>
309where
310    F: FnMut(Block, Tip) -> Result<()> + Send + Sync,
311    B: FnMut(Point, Tip) -> Result<()> + Send + Sync,
312{
313    fn on_roll_forward(&mut self, block: Block, tip: Tip) -> Result<()> {
314        (self.on_forward)(block, tip)
315    }
316
317    fn on_roll_backward(&mut self, point: Point, tip: Tip) -> Result<()> {
318        (self.on_backward)(point, tip)
319    }
320}