Skip to main content

nodedb_lite/sync/transport/
run.rs

1//! The reconnecting sync loop: connect, handshake, push and receive, then
2//! back off and reconnect.
3
4use std::sync::Arc;
5
6use crate::sync::client::{SyncClient, SyncState};
7use crate::sync::delegate::SyncDelegate;
8
9/// Run the sync loop — connects, handshakes, pushes/receives, reconnects.
10///
11/// Runs forever (until the task is cancelled). On disconnect it sleeps for
12/// [`SyncClient::backoff_duration`] and retries; on a clean close the
13/// backoff resets to zero.
14pub async fn run_sync_loop(client: Arc<SyncClient>, delegate: Arc<dyn SyncDelegate>) {
15    let mut attempt: u32 = 0;
16
17    loop {
18        client.set_state(SyncState::Connecting).await;
19        tracing::info!(url = %client.config().url, attempt, "connecting to Origin");
20
21        match super::connect::connect_and_run(&client, &delegate).await {
22            Ok(()) => {
23                tracing::info!("sync connection closed cleanly");
24                attempt = 0;
25            }
26            Err(e) => {
27                tracing::warn!(error = %e, attempt, "sync connection failed");
28            }
29        }
30
31        client.set_state(SyncState::Reconnecting).await;
32        let backoff = client.backoff_duration(attempt);
33        tracing::info!(
34            backoff_ms = backoff.as_millis(),
35            "reconnecting after backoff"
36        );
37        tokio::time::sleep(backoff).await;
38        attempt = attempt.saturating_add(1);
39    }
40}