dittolive-ditto 5.2.0-preview.1

Ditto is a peer to peer cross-platform database that allows mobile, web, IoT and server apps to sync with or without an internet connection.
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use std::{collections::HashSet, path::PathBuf, time::Duration};

use serde::{Deserialize, Serialize};
use serde_with::serde_as;

pub const NO_PREFERRED_ROUTE_HINT: u32 = 0;

/// A configuration object specifying which network transports Ditto should use
/// to sync data.
///
/// A `Ditto` object comes with a default transport configuration where the
/// stable peer-to-peer transports supported on the current platform are
/// enabled. Reliable UDP multicast is excluded from this default and must be
/// enabled explicitly. You can customize the configuration by initializing a
/// `TransportConfig`, adjusting its properties, and supplying it to
/// `set_transport_config()` on `Ditto`.
///
/// When you initialize a `TransportConfig` yourself it starts with all
/// transports disabled. You must enable each one directly.
///
/// Peer-to-peer transports will automatically discover peers in the vicinity
/// and create connections without any configuration. These are configured
/// inside the `peer_to_peer` property. To turn each one on, set its `enabled`
/// property to `true`.
///
/// To connect to a peer at a known location, such as a Ditto Big Peer, add its
/// address inside the `connect` configuration. These are either `host:port`
/// strings for raw TCP sync, or a `wss://…` URL for websockets.
///
/// The `listen` configurations are for specific less common data sync
/// scenarios. Please read the documentation on the Ditto website for examples.
/// Incorrect use of `listen` can result in insecure configurations.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct TransportConfig {
    /// Configure Bluetooth and LAN transports.
    pub peer_to_peer: PeerToPeer,

    /// Configure TCP and WebSocket outbound transports.
    pub connect: Connect,

    /// Configure TCP and HTTP inbound transports.
    pub listen: Listen,

    /// Set peer-global transport settings.
    pub global: Global,
}

impl TransportConfig {
    /// Create a new [`TransportConfig`] with default settings.
    pub fn new() -> Self {
        Self {
            peer_to_peer: PeerToPeer {
                bluetooth_le: BluetoothLEConfig::new(),
                lan: LanConfig::new(),
                awdl: AwdlConfig::new(),
                wifi_aware: WifiAwareConfig::new(),
                multicast_beta: MulticastBetaConfig::new(),
            },
            connect: Connect {
                tcp_servers: HashSet::new(),
                websocket_urls: HashSet::new(),
                retry_interval: Duration::from_secs(5),
            },
            listen: Listen {
                tcp: TcpListenConfig::new(),
                http: HttpListenConfig::new(),
            },
            global: Global {
                sync_group: 0,
                routing_hint: NO_PREFERRED_ROUTE_HINT,
            },
        }
    }

    /// Enables all stable peer-to-peer transports in this config.
    ///
    /// This method does not affect the reliable UDP multicast transport.
    /// Configure [`PeerToPeer::multicast_beta`] separately.
    pub fn enable_all_peer_to_peer(&mut self) {
        self.peer_to_peer.bluetooth_le.enabled = true;
        self.peer_to_peer.lan.enabled = true;
        self.peer_to_peer.awdl.enabled = true;
        self.peer_to_peer.wifi_aware.enabled = true;
    }
}

/// Configure peer-to-peer transports such as Bluetooth and LAN.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct PeerToPeer {
    /// Bluetooth transport configurations.
    pub bluetooth_le: BluetoothLEConfig,

    /// LAN transport configurations.
    pub lan: LanConfig,

    /// AWDL transport configurations.
    pub awdl: AwdlConfig,

    /// Wi-Fi Aware transport configurations.
    pub wifi_aware: WifiAwareConfig,

    /// Private beta configuration for reliable UDP multicast transport. See
    /// [`MulticastBetaConfig`].
    #[serde(rename = "multicast")]
    pub multicast_beta: MulticastBetaConfig,
}

/// Configure outbound transports such as TCP and WebSocket dialing.
#[serde_as]
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct Connect {
    /// A set of TCP servers to attempt connection to.
    pub tcp_servers: HashSet<String>,

    /// A set of websocket servers to attempt connection to.
    pub websocket_urls: HashSet<String>,

    /// The retry interval between failed connection attempts. For
    /// cross-compatibility, this must be less than 2^32 - 1 milliseconds.
    #[serde_as(as = "::serde_with::DurationMilliSeconds<u64>")]
    pub retry_interval: Duration,
}

/// Configure inbound transports such as TCP and HTTP servers.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct Listen {
    /// Configure inbound TCP transports.
    pub tcp: TcpListenConfig,

    /// Configure inbound HTTP transports.
    pub http: HttpListenConfig,
}

/// Settings not associated with any specific type of transport.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct Global {
    /// The sync group for this device.
    ///
    /// When peer-to-peer transports are enabled, all devices with the same App
    /// ID will normally form an interconnected mesh network. In some
    /// situations it may be desirable to have distinct groups of devices
    /// within the same app, so that connections will only be formed within
    /// each group. The `sync_group` parameter changes that group
    /// membership. A device can only ever be in one sync group, which
    /// by default is group 0. Up to 2^32 distinct group numbers can be used in
    /// an app.
    ///
    /// This is an optimization, not a security control. If a connection is
    /// created manually, such as by specifying a `connect` transport, then
    /// devices from different sync groups will still sync as normal. If
    /// two groups of devices are intended to have access to different data
    /// sets, this must be enforced using Ditto's permissions system.
    pub sync_group: u32,

    /// The routing hint for this device.
    ///
    /// A routing hint is a performance tuning option which can improve the performance of
    /// applications that use large collections. Ditto will make a best effort to co-locate data
    /// for the same routing key. In most circumstances, this should substantially improve
    /// responsiveness of the Ditto Cloud.
    ///
    /// The value of the routing hint is application specific - you are free to choose any value.
    /// Devices which you expect to operate on much the same data should be configured to
    /// use the same value.
    ///
    /// A routing hint does not partition data. The value of the routing hint will not affect the
    /// data returned for a query. The routing hint only improves the efficiency of the Cloud's
    /// ability to satisfy the query.
    pub routing_hint: u32,
}

/// Configure inbound HTTP transports.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct HttpListenConfig {
    /// Whether inbound HTTP is enabled.
    pub enabled: bool,

    /// The IP address on which to bind a listening HTTP server.
    pub interface_ip: String,

    /// The port on which to bind a listening HTTP server.
    pub port: u16,

    /// Whether to enable Websocket sync on this transport.
    pub websocket_sync: bool,

    /// Optional path to a TLS key file.
    pub tls_key_path: Option<PathBuf>,

    /// Optional path to a TLS certificate file.
    pub tls_certificate_path: Option<PathBuf>,
}

impl HttpListenConfig {
    /// Create a new [`HttpListenConfig`] with default settings.
    pub fn new() -> Self {
        Self {
            enabled: false,
            interface_ip: "[::]".to_string(),
            port: 80,
            websocket_sync: true,
            tls_key_path: None,
            tls_certificate_path: None,
        }
    }
}

/// Configure inbound TCP transports.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct TcpListenConfig {
    /// Whether inbound TCP is enabled.
    pub enabled: bool,

    /// The address to bind a TCP listener, such as `0.0.0.0`.
    pub interface_ip: String,

    /// The port to bind the TCP listener to.
    pub port: u16,
}

impl TcpListenConfig {
    /// Create a new [`TcpListenConfig`] with default settings.
    pub fn new() -> Self {
        Self {
            enabled: false,
            interface_ip: "[::]".to_string(),
            port: 4040,
        }
    }
}

/// Configure the Bluetooth Low-Energy transport.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct BluetoothLEConfig {
    /// Whether to enable the Bluetooth Low-Energy transport.
    pub enabled: bool,
}

impl BluetoothLEConfig {
    /// Create a new [`BluetoothLEConfig`] with default settings.
    pub fn new() -> Self {
        Self { enabled: false }
    }
}

/// Configure the Local Area Network (LAN) transport.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct LanConfig {
    /// Whether to enable the LAN transport.
    pub enabled: bool,

    /// Whether to enable mDNS peer discovery.
    pub mdns_enabled: bool,

    /// Whether to enable multicast.
    pub multicast_enabled: bool,
}

impl LanConfig {
    /// Create a new [`LanConfig`] with default settings.
    pub fn new() -> Self {
        Self {
            enabled: false,
            mdns_enabled: true,
            multicast_enabled: true,
        }
    }
}

/// Configuration for Apple Wireless Direct Link (AWDL) network transport.
/// Not supported on all platforms.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct AwdlConfig {
    /// Whether to enable the AWDL transport.
    pub enabled: bool,
}

impl AwdlConfig {
    /// Create a new [`AwdlConfig`] with default settings.
    pub fn new() -> Self {
        Self { enabled: false }
    }
}

/// Configuration for Wi-Fi Aware network transport.
/// Not supported on all platforms.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct WifiAwareConfig {
    /// Whether to enable the Wi-Fi Aware transport.
    pub enabled: bool,
}

impl WifiAwareConfig {
    /// Create a new [`WifiAwareConfig`] with default settings.
    pub fn new() -> Self {
        Self { enabled: false }
    }
}

/// Configuration for reliable UDP multicast transport.
///
/// Use this configuration to enable peer-to-peer data synchronization over a
/// multicast group.
///
/// This does not configure multicast-based LAN discovery. Use
/// [`LanConfig::multicast_enabled`] for that setting.
///
/// On iOS and Android, configure this transport while sync is stopped. Changes
/// requested while sync is active take effect after sync is stopped and
/// successfully started again, when Ditto validates platform prerequisites.
///
/// This feature is in private beta and should only be used in coordination
/// with Ditto support.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default)]
pub struct MulticastBetaConfig {
    /// Whether reliable UDP multicast transport is enabled. This private beta
    /// feature should only be enabled in coordination with Ditto support.
    pub enabled: bool,
    /// IPv4 multicast group address (e.g. `224.1.2.3`). All peers in the
    /// mesh must use the same address.
    pub group_address: String,
    /// UDP port. All peers must use the same port.
    pub port: u16,
    /// Network interface name to bind to (e.g. `en0`, `wlan0`). When `None`,
    /// the OS picks one — typically the default route interface.
    pub interface: Option<String>,
}

impl MulticastBetaConfig {
    /// Create a new [`MulticastBetaConfig`] with default settings.
    pub fn new() -> Self {
        Self::default()
    }
}

impl Default for MulticastBetaConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            group_address: "224.1.2.3".to_string(),
            port: 6003,
            interface: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn awdl_config_default_disabled() {
        assert!(!AwdlConfig::default().enabled);
        assert!(!AwdlConfig::new().enabled);
    }

    #[test]
    fn wifi_aware_config_default_disabled() {
        assert!(!WifiAwareConfig::default().enabled);
        assert!(!WifiAwareConfig::new().enabled);
    }

    #[test]
    fn enable_all_peer_to_peer_enables_all_transports() {
        let mut config = TransportConfig::new();
        config.enable_all_peer_to_peer();
        assert!(config.peer_to_peer.bluetooth_le.enabled);
        assert!(config.peer_to_peer.lan.enabled);
        assert!(config.peer_to_peer.awdl.enabled);
        assert!(config.peer_to_peer.wifi_aware.enabled);
    }

    #[test]
    fn enable_all_peer_to_peer_does_not_affect_multicast() {
        for multicast_enabled in [false, true] {
            let mut config = TransportConfig::new();
            config.peer_to_peer.multicast_beta.enabled = multicast_enabled;

            config.enable_all_peer_to_peer();

            assert_eq!(
                config.peer_to_peer.multicast_beta.enabled,
                multicast_enabled
            );
        }
    }

    #[test]
    fn awdl_config_serde_roundtrip() {
        let original = AwdlConfig { enabled: true };
        let json = serde_json::to_string(&original).unwrap();
        let decoded: AwdlConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn wifi_aware_config_serde_roundtrip() {
        let original = WifiAwareConfig { enabled: true };
        let json = serde_json::to_string(&original).unwrap();
        let decoded: WifiAwareConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn peer_to_peer_missing_fields_default_to_disabled() {
        let json = r#"{"bluetooth_le":{"enabled":true},"lan":{"enabled":true,"mdns_enabled":true,"multicast_enabled":true}}"#;
        let peer_to_peer: PeerToPeer = serde_json::from_str(json).unwrap();
        assert!(!peer_to_peer.awdl.enabled);
        assert!(!peer_to_peer.wifi_aware.enabled);
    }

    #[test]
    fn multicast_beta_config_default_disabled() {
        let cfg = MulticastBetaConfig::default();
        assert!(!cfg.enabled);
        assert_eq!(cfg.group_address, "224.1.2.3");
        assert_eq!(cfg.port, 6003);
        assert!(cfg.interface.is_none());
    }

    #[test]
    fn multicast_beta_config_new_equals_default() {
        assert_eq!(MulticastBetaConfig::new(), MulticastBetaConfig::default());
    }

    #[test]
    fn multicast_beta_config_serde_roundtrip() {
        let original = MulticastBetaConfig {
            enabled: true,
            group_address: "224.1.2.3".to_string(),
            port: 6003,
            interface: Some("en0".to_string()),
        };
        let json = serde_json::to_string(&original).unwrap();
        let decoded: MulticastBetaConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn transport_config_peer_to_peer_exposes_multicast_beta() {
        let mut config = TransportConfig::new();
        config.peer_to_peer.multicast_beta.enabled = true;
        config.peer_to_peer.multicast_beta.group_address = "224.5.6.7".to_string();
        config.peer_to_peer.multicast_beta.port = 7000;
        assert!(config.peer_to_peer.multicast_beta.enabled);
        assert_eq!(
            config.peer_to_peer.multicast_beta.group_address,
            "224.5.6.7"
        );
        assert_eq!(config.peer_to_peer.multicast_beta.port, 7000);

        let json = serde_json::to_value(&config.peer_to_peer).unwrap();
        assert!(json.get("multicast").is_some());
        assert!(json.get("multicast_beta").is_none());
    }
}