syncweb-core 0.1.1-alpha.10

delay-tolerant web surfing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use iroh::address_lookup::memory::MemoryLookup;
use iroh::protocol::Router;
use iroh_blobs::BlobsProtocol;
use iroh_docs::protocol::Docs;
use iroh_gossip::net::Gossip;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use crate::error::{Result, SyncwebError};
use crate::net::RelayManager;

use super::beacon_lookup::{BeaconAddressLookup, DEFAULT_BEACON_PORT};
use super::blob_store::BlobStore;
use super::discovery::TopicTracker;
use super::docs_engine::DocsEngine;
use super::identity::IdentityManager;
use super::membership_hook::MembershipHook;

#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum RelayMode {
    Default,
    Custom { map: iroh::RelayMap, insecure: bool },
    None,
}

/// Runtime configuration for the local discovery mechanisms attached to a node.
///
/// `scope` is a 16-byte token derived from the daemon's network name. When
/// present it scopes both mDNS and the UDP beacon so that unrelated networks
/// do not discover each other; `None` keeps the default iroh mDNS service name
/// and a scope-less beacon (used by the network-agnostic default daemon).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct DiscoveryConfig {
    /// Whether the mDNS address lookup is registered.
    pub mdns: bool,
    /// Whether the UDP beacon address lookup is registered.
    pub beacon: bool,
    /// Base UDP port the beacon spreads scopes over.
    pub beacon_base_port: u16,
    /// How often the beacon re-broadcasts its endpoint data.
    pub beacon_interval: Duration,
    /// Restrict the beacon to a single network interface by name, if any.
    pub interface: Option<String>,
    /// 16-byte discovery scope derived from the network name, if any.
    pub scope: Option<[u8; 16]>,
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            mdns: true,
            beacon: true,
            beacon_base_port: DEFAULT_BEACON_PORT,
            beacon_interval: Duration::from_secs(1),
            interface: None,
            scope: None,
        }
    }
}

impl DiscoveryConfig {
    /// A discovery configuration with every mechanism disabled.
    #[must_use]
    pub const fn disabled() -> Self {
        Self {
            mdns: false,
            beacon: false,
            beacon_base_port: DEFAULT_BEACON_PORT,
            beacon_interval: Duration::from_secs(1),
            interface: None,
            scope: None,
        }
    }
}

/// mDNS service name for a scope, or the default iroh name when unscoped.
fn mdns_service_name(scope: Option<&[u8; 16]>) -> String {
    scope.map_or_else(
        || "irohv1".to_owned(),
        |bytes| format!("syncweb-{}", hex::encode(&bytes[..8])),
    )
}

/// Derive a discovery scope (first 16 bytes of the network id) from a network
/// name. `None` for networks without a name, keeping the default daemon
/// compatible with plain iroh peers on the LAN.
#[must_use]
pub fn discovery_scope(network: Option<&str>) -> Option<[u8; 16]> {
    let name = network?;
    let id = crate::net::NetworkId::from_name(name);
    let bytes = id.as_bytes();
    let mut scope = [0_u8; 16];
    scope.copy_from_slice(&bytes[..16]);
    Some(scope)
}

/// Registers the scoped mDNS and UDP beacon address lookups on an endpoint.
fn register_discovery(endpoint: &iroh::Endpoint, discovery: &DiscoveryConfig) {
    if discovery.mdns {
        register_mdns(endpoint, discovery);
    }
    if discovery.beacon {
        register_beacon(endpoint, discovery);
    }
}

fn register_mdns(endpoint: &iroh::Endpoint, discovery: &DiscoveryConfig) {
    let service_name = mdns_service_name(discovery.scope.as_ref());
    match iroh_mdns_address_lookup::MdnsAddressLookup::builder()
        .service_name(service_name)
        .build(endpoint.id())
        .map_err(|error| SyncwebError::operation("failed to build mDNS address lookup", error))
        .and_then(|mdns| {
            endpoint
                .address_lookup()
                .map_err(|error| SyncwebError::operation("no address lookup service available", error))
                .map(|lookup| lookup.add(mdns))
        }) {
        Ok(()) => tracing::debug!("mDNS address lookup registered"),
        Err(error) => tracing::warn!(
            %error,
            "mDNS address lookup registration failed — local peer discovery unavailable"
        ),
    }
}

fn register_beacon(endpoint: &iroh::Endpoint, discovery: &DiscoveryConfig) {
    let Ok(beacon) = BeaconAddressLookup::new(
        endpoint.id(),
        discovery.scope,
        discovery.beacon_base_port,
        discovery.beacon_interval,
        discovery.interface.as_deref(),
    ) else {
        return;
    };
    match endpoint.address_lookup() {
        Ok(lookup) => {
            lookup.add(beacon);
            tracing::debug!("beacon address lookup registered");
        }
        Err(error) => tracing::warn!(
            %error,
            "beacon address lookup registration failed — no address lookup service available"
        ),
    }
}

pub struct IrohNode {
    endpoint: iroh::Endpoint,
    router: Arc<Router>,
    blobs: iroh_blobs::BlobsProtocol,
    docs: Docs,
    gossip: Arc<Gossip>,
    blob_store: BlobStore,
    docs_engine: DocsEngine,
    topic_tracker: TopicTracker,
    /// The Syncthing (BEP) relay manager, when `bep.enabled` is set. Keeps the
    /// registration loops and the custom transport's backend alive.
    relay: Option<RelayManager>,
}

impl IrohNode {
    /// Creates a node and starts accepting the blobs, docs, and gossip protocols.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory structure cannot be created, if binding the endpoint fails, or if starting the background services fails.
    pub async fn new(
        identity: IdentityManager,
        data_dir: PathBuf,
        relay_mode: RelayMode,
        member_keys: Arc<RwLock<HashSet<iroh::PublicKey>>>,
        discovery: DiscoveryConfig,
    ) -> Result<Self> {
        Self::new_with_address_lookup(
            identity,
            data_dir,
            relay_mode,
            MemoryLookup::new(),
            discovery,
            member_keys,
        )
        .await
    }

    /// Creates a node with the Syncthing (BEP) relay transport installed.
    ///
    /// When `relay` is `Some`, the manager's custom transport is registered on
    /// the endpoint and the manager is kept alive for the node's lifetime; the
    /// node's share tickets then carry the node's relay address so peers can
    /// reach it through a Syncthing relay when direct paths fail.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory structure cannot be created, if binding the endpoint fails, or if starting the background services fails.
    pub async fn new_with_relay(
        identity: IdentityManager,
        data_dir: PathBuf,
        relay_mode: RelayMode,
        member_keys: Arc<RwLock<HashSet<iroh::PublicKey>>>,
        discovery: DiscoveryConfig,
        relay: Option<RelayManager>,
    ) -> Result<Self> {
        Self::new_with_address_lookup_and_relay(
            identity,
            data_dir,
            relay_mode,
            MemoryLookup::new(),
            discovery,
            member_keys,
            relay,
        )
        .await
    }

    /// # Errors
    ///
    /// Returns an error if the directory structure cannot be created, if binding the endpoint fails, or if starting the background services fails.
    pub async fn new_with_address_lookup(
        identity: IdentityManager,
        data_dir: PathBuf,
        relay_mode: RelayMode,
        address_lookup: MemoryLookup,
        discovery: DiscoveryConfig,
        member_keys: Arc<RwLock<HashSet<iroh::PublicKey>>>,
    ) -> Result<Self> {
        Self::new_with_address_lookup_and_relay(
            identity,
            data_dir,
            relay_mode,
            address_lookup,
            discovery,
            member_keys,
            None,
        )
        .await
    }

    /// # Errors
    ///
    /// Returns an error if the directory structure cannot be created, if binding the endpoint fails, or if starting the background services fails.
    pub async fn new_with_address_lookup_and_relay(
        identity: IdentityManager,
        data_dir: PathBuf,
        relay_mode: RelayMode,
        address_lookup: MemoryLookup,
        discovery: DiscoveryConfig,
        member_keys: Arc<RwLock<HashSet<iroh::PublicKey>>>,
        relay: Option<RelayManager>,
    ) -> Result<Self> {
        tokio::fs::create_dir_all(&data_dir)
            .await
            .map_err(|error| SyncwebError::operation("failed to create node data directory", error))?;
        let docs_dir = data_dir.join("docs");
        tokio::fs::create_dir_all(&docs_dir)
            .await
            .map_err(|error| SyncwebError::operation("failed to create docs directory", error))?;

        let base = match relay_mode {
            RelayMode::Default => iroh::Endpoint::builder(iroh::endpoint::presets::N0),
            RelayMode::Custom { map, insecure } => {
                let mut b = iroh::Endpoint::builder(iroh::endpoint::presets::N0)
                    .relay_mode(iroh::endpoint::RelayMode::Custom(map));
                if insecure {
                    b = b.ca_tls_config(iroh::tls::CaTlsConfig::insecure_skip_verify());
                }
                b
            }
            RelayMode::None => {
                iroh::Endpoint::builder(iroh::endpoint::presets::N0).relay_mode(iroh::endpoint::RelayMode::Disabled)
            }
        };

        let hook = MembershipHook {
            member_keys: member_keys.clone(),
        };
        let mut builder = base
            .address_lookup(address_lookup.clone())
            .secret_key(identity.secret_key().clone())
            .hooks(hook);
        if let Some(manager) = &relay {
            builder = builder.add_custom_transport(Arc::new(manager.transport()));
        }
        let endpoint = builder
            .bind()
            .await
            .map_err(|error| SyncwebError::operation("failed to bind Iroh endpoint", error))?;

        // Register mDNS and UDP beacon address lookups for local peer discovery.
        // Both are scoped by `discovery.scope` when the daemon belongs to a
        // network; failures are logged and leave the other discovery mechanism
        // (or remote relay/DHT discovery) in charge.
        register_discovery(&endpoint, &discovery);

        let fs_blob_store = iroh_blobs::store::fs::FsStore::load(data_dir.join("blobs"))
            .await
            .map_err(|error| SyncwebError::operation("failed to open blob store", error))?;
        let blobs = BlobsProtocol::new(fs_blob_store.as_ref(), None);

        let gossip = Arc::new(Gossip::builder().spawn(endpoint.clone()));

        let docs = Docs::persistent(docs_dir)
            .spawn(endpoint.clone(), blobs.store().clone(), gossip.as_ref().clone())
            .await
            .map_err(|error| SyncwebError::operation("failed to open docs store", error))?;

        let router = Router::builder(endpoint.clone())
            .accept(iroh_blobs::protocol::ALPN, blobs.clone())
            .accept(iroh_docs::ALPN, docs.clone())
            .accept(iroh_gossip::ALPN, gossip.clone())
            .spawn();

        let blob_store = BlobStore::new_with_address_lookup(&blobs, address_lookup);
        let relay_addr = relay.as_ref().map(RelayManager::local_addr);
        let docs_engine = DocsEngine::new(&docs, blobs.store(), endpoint.id(), relay_addr.clone());
        let topic_tracker = TopicTracker::new(&gossip, &endpoint, relay_addr);

        Ok(Self {
            endpoint,
            router: Arc::new(router),
            blobs,
            docs,
            gossip,
            blob_store,
            docs_engine,
            topic_tracker,
            relay,
        })
    }

    /// The relay custom address this node advertises, when Syncthing (BEP)
    /// relaying is enabled.
    #[must_use]
    pub fn relay_addr(&self) -> Option<iroh_base::CustomAddr> {
        self.relay.as_ref().map(RelayManager::local_addr)
    }

    #[must_use]
    pub const fn endpoint(&self) -> &iroh::Endpoint {
        &self.endpoint
    }

    #[must_use]
    pub const fn blobs(&self) -> &BlobsProtocol {
        &self.blobs
    }

    #[must_use]
    pub const fn docs(&self) -> &Docs {
        &self.docs
    }

    #[must_use]
    pub fn gossip(&self) -> &Gossip {
        &self.gossip
    }

    #[must_use]
    pub const fn blob_store(&self) -> &BlobStore {
        &self.blob_store
    }

    #[must_use]
    pub const fn docs_engine(&self) -> &DocsEngine {
        &self.docs_engine
    }

    #[must_use]
    pub const fn topic_tracker(&self) -> &TopicTracker {
        &self.topic_tracker
    }

    #[must_use]
    pub fn is_running(&self) -> bool {
        !self.router.is_shutdown()
    }

    /// # Errors
    ///
    /// Returns an error if the router fails to shutdown properly.
    pub async fn stop(&self) -> Result<()> {
        self.blob_store
            .inner()
            .sync_db()
            .await
            .map_err(|error| SyncwebError::operation("failed to flush blob store", error))?;
        self.router
            .shutdown()
            .await
            .map_err(|error| SyncwebError::operation("failed to stop node router", error))?;
        if let Some(relay) = &self.relay {
            relay.shutdown().await;
        }
        Ok(())
    }

    /// # Errors
    ///
    /// Returns an error if stopping the node fails.
    pub async fn shutdown(self) -> Result<()> {
        self.stop().await
    }
}

impl Drop for IrohNode {
    fn drop(&mut self) {
        if !self.router.is_shutdown() {
            tracing::warn!("IrohNode dropped without calling stop() — router shutdown may be incomplete");
        }
    }
}