synapse-rs 1.1.0

A standardized metric system (Vortex, Radiance, Axon) to evaluate real-world network quality beyond simple speed tests.
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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Network quality metrics: Vortex, Radiance, and Axon.
//!
//! # Metric overview
//!
//! | Metric    | What it measures                         | Typical inputs                          |
//! |-----------|------------------------------------------|-----------------------------------------|
//! | **Vortex**   | Flow / performance efficiency         | speeds, ping, jitter, packet loss       |
//! | **Radiance** | Wireless physical-layer quality       | RSSI, noise floor, channel width        |
//! | **Axon**     | Unified connection health             | Vortex × Radiance (or Vortex on wired)  |
//!
//! Scores are dimensionless and unbounded. Use [`ScoreBand`] for a coarse
//! qualitative reading; absolute thresholds are heuristics, not standards.

use std::fmt;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::error::{Result, SynapseError};

/// Represents raw network connection measurements.
///
/// All fields are optional so partial snapshots are valid (e.g. Ethernet
/// without Wi-Fi signal data, or signal-only samples without a speed test).
///
/// # Field units
///
/// - Speeds: Mbps
/// - Latency / jitter: milliseconds
/// - Packet loss: percent (`0.0`..=`100.0`)
/// - RSSI / noise: dBm (typically negative)
/// - Channel width: MHz (`20`, `40`, `80`, `160`, …)
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct NetworkData {
    /// Download speed in Mbps.
    pub down_mbps: Option<f64>,
    /// Upload speed in Mbps.
    pub up_mbps: Option<f64>,
    /// Round-trip latency in milliseconds.
    pub ping_ms: Option<f64>,
    /// Latency variation (jitter) in milliseconds.
    pub jitter_ms: Option<f64>,
    /// Packet loss percentage (`0.0` for none, `100.0` for total loss).
    pub packet_loss_percent: Option<f64>,
    /// Received Signal Strength Indicator in dBm (e.g. `-65.0`). Wireless only.
    pub rssi_dbm: Option<f64>,
    /// Noise floor in dBm (e.g. `-90.0`). Wireless only.
    pub noise_dbm: Option<f64>,
    /// Wi-Fi channel width in MHz (e.g. `20`, `40`, `80`, `160`).
    pub channel_width_mhz: Option<f64>,
}

/// Coarse qualitative band for interpreting a raw Synapse score.
///
/// Thresholds are heuristics intended for dashboards and UX copy, not a
/// formal standard. They apply best to Vortex and Axon; Radiance scales
/// differently with channel width.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ScoreBand {
    /// Very poor / unusable for interactive use.
    Critical,
    /// Noticeably degraded.
    Poor,
    /// Acceptable for general browsing.
    Fair,
    /// Comfortable for most workloads.
    Good,
    /// Excellent headroom.
    Excellent,
}

impl ScoreBand {
    /// Maps a raw score onto a [`ScoreBand`] using built-in heuristics.
    ///
    /// | Band       | Score range   |
    /// |------------|---------------|
    /// | Critical   | `< 50`        |
    /// | Poor       | `50` .. `150` |
    /// | Fair       | `150` .. `400`|
    /// | Good       | `400` .. `1000`|
    /// | Excellent  | `≥ 1000`      |
    pub fn from_score(score: f64) -> Self {
        if !score.is_finite() || score < 50.0 {
            Self::Critical
        } else if score < 150.0 {
            Self::Poor
        } else if score < 400.0 {
            Self::Fair
        } else if score < 1000.0 {
            Self::Good
        } else {
            Self::Excellent
        }
    }

    /// Short English label suitable for UI display.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Critical => "critical",
            Self::Poor => "poor",
            Self::Fair => "fair",
            Self::Good => "good",
            Self::Excellent => "excellent",
        }
    }
}

impl fmt::Display for ScoreBand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl NetworkData {
    /// Avoids division by zero when ping and jitter are both ~0.
    const EPSILON: f64 = 1e-7;

    /// Jitter is weighted more heavily than raw ping in friction.
    const JITTER_WEIGHT: f64 = 3.0;

    /// Packet-loss integrity is raised to this power (harsh near 100% loss).
    const INTEGRITY_EXPONENT: f64 = 10.0;

    /// Channel width is normalized against a 20 MHz baseline.
    const WIDTH_BASELINE_MHZ: f64 = 20.0;

    /// Creates an empty measurement (all fields `None`).
    pub const fn new() -> Self {
        Self {
            down_mbps: None,
            up_mbps: None,
            ping_ms: None,
            jitter_ms: None,
            packet_loss_percent: None,
            rssi_dbm: None,
            noise_dbm: None,
            channel_width_mhz: None,
        }
    }

    /// Builder: download speed in Mbps.
    pub fn with_down_mbps(mut self, v: f64) -> Self {
        self.down_mbps = Some(v);
        self
    }

    /// Builder: upload speed in Mbps.
    pub fn with_up_mbps(mut self, v: f64) -> Self {
        self.up_mbps = Some(v);
        self
    }

    /// Builder: ping in milliseconds.
    pub fn with_ping_ms(mut self, v: f64) -> Self {
        self.ping_ms = Some(v);
        self
    }

    /// Builder: jitter in milliseconds.
    pub fn with_jitter_ms(mut self, v: f64) -> Self {
        self.jitter_ms = Some(v);
        self
    }

    /// Builder: packet loss percentage.
    pub fn with_packet_loss_percent(mut self, v: f64) -> Self {
        self.packet_loss_percent = Some(v);
        self
    }

    /// Builder: RSSI in dBm.
    pub fn with_rssi_dbm(mut self, v: f64) -> Self {
        self.rssi_dbm = Some(v);
        self
    }

    /// Builder: noise floor in dBm.
    pub fn with_noise_dbm(mut self, v: f64) -> Self {
        self.noise_dbm = Some(v);
        self
    }

    /// Builder: channel width in MHz.
    pub fn with_channel_width_mhz(mut self, v: f64) -> Self {
        self.channel_width_mhz = Some(v);
        self
    }

    /// Returns `true` when enough fields are present to attempt a Vortex score.
    pub fn has_performance_data(&self) -> bool {
        self.down_mbps.is_some()
            && self.up_mbps.is_some()
            && self.ping_ms.is_some()
            && self.jitter_ms.is_some()
            && self.packet_loss_percent.is_some()
    }

    /// Returns `true` when enough fields are present to attempt a Radiance score.
    pub fn has_wireless_data(&self) -> bool {
        self.rssi_dbm.is_some() && self.noise_dbm.is_some() && self.channel_width_mhz.is_some()
    }

    /// Calculates the **Vortex** score (flow / performance).
    ///
    /// Combines logarithmic throughput volume with latency friction, then
    /// applies a packet-loss integrity factor:
    ///
    /// ```text
    /// volume    = log10(1 + down) * log10(1 + up)
    /// friction  = ping_s + 3 * jitter_s + ε
    /// integrity = clamp(1 - loss/100, 0, 1)^10
    /// vortex    = (volume / friction) * integrity
    /// ```
    ///
    /// # Returns
    ///
    /// * `Some(score)` when all performance fields are present and valid
    /// * `None` when data is missing or invalid (see [`Self::try_vortex`])
    pub fn calculate_vortex(&self) -> Option<f64> {
        self.try_vortex().ok()
    }

    /// Fallible Vortex calculation with structured errors.
    pub fn try_vortex(&self) -> Result<f64> {
        let down = require(self.down_mbps, "down_mbps")?;
        let up = require(self.up_mbps, "up_mbps")?;
        let ping = require(self.ping_ms, "ping_ms")?;
        let jitter = require(self.jitter_ms, "jitter_ms")?;
        let lost = require(self.packet_loss_percent, "packet_loss_percent")?;

        ensure_finite_non_negative(down, "down_mbps")?;
        ensure_finite_non_negative(up, "up_mbps")?;
        ensure_finite_non_negative(ping, "ping_ms")?;
        ensure_finite_non_negative(jitter, "jitter_ms")?;
        ensure_finite(lost, "packet_loss_percent")?;
        if !(0.0..=100.0).contains(&lost) {
            return Err(SynapseError::InvalidValue {
                field: "packet_loss_percent",
                reason: "must be between 0 and 100",
            });
        }

        let down_score = (1.0 + down).log10();
        let up_score = (1.0 + up).log10();
        let volume = down_score * up_score;

        let ping_seconds = ping / 1000.0;
        let jitter_seconds = jitter / 1000.0;
        let friction = ping_seconds + (Self::JITTER_WEIGHT * jitter_seconds) + Self::EPSILON;

        let integrity = (1.0 - (lost / 100.0))
            .clamp(0.0, 1.0)
            .powf(Self::INTEGRITY_EXPONENT);

        let score = (volume / friction) * integrity;
        if !score.is_finite() {
            return Err(SynapseError::InvalidValue {
                field: "vortex",
                reason: "calculation produced a non-finite result",
            });
        }
        Ok(score)
    }

    /// Calculates the **Radiance** score (wireless physical quality).
    ///
    /// ```text
    /// snr      = rssi_dbm - noise_dbm
    /// radiance = max(0, (channel_width_mhz / 20) * snr)
    /// ```
    ///
    /// # Returns
    ///
    /// * `Some(score)` when wireless fields are present and valid
    /// * `None` when wired / incomplete / invalid (see [`Self::try_radiance`])
    pub fn calculate_radiance(&self) -> Option<f64> {
        self.try_radiance().ok()
    }

    /// Fallible Radiance calculation with structured errors.
    pub fn try_radiance(&self) -> Result<f64> {
        let width = require(self.channel_width_mhz, "channel_width_mhz")?;
        let rssi = require(self.rssi_dbm, "rssi_dbm")?;
        let noise = require(self.noise_dbm, "noise_dbm")?;

        ensure_finite(width, "channel_width_mhz")?;
        ensure_finite(rssi, "rssi_dbm")?;
        ensure_finite(noise, "noise_dbm")?;

        if width <= 0.0 {
            return Err(SynapseError::InvalidValue {
                field: "channel_width_mhz",
                reason: "must be greater than 0",
            });
        }
        // RSSI should be at or above the noise floor in a sane measurement.
        if rssi < noise {
            return Err(SynapseError::InvalidValue {
                field: "rssi_dbm",
                reason: "RSSI is below the noise floor",
            });
        }

        let width_factor = width / Self::WIDTH_BASELINE_MHZ;
        let snr = rssi - noise;
        let score = (width_factor * snr).max(0.0);

        if !score.is_finite() {
            return Err(SynapseError::InvalidValue {
                field: "radiance",
                reason: "calculation produced a non-finite result",
            });
        }
        Ok(score)
    }

    /// Calculates the **Axon** unified health score.
    ///
    /// - **Wireless** (Vortex + Radiance available): geometric mean
    ///   `sqrt(vortex * radiance)`.
    /// - **Wired** (Vortex only): returns the Vortex score so Ethernet links
    ///   still get a health metric.
    ///
    /// # Returns
    ///
    /// * `Some(score)` when at least Vortex can be computed
    /// * `None` when performance data is missing or invalid
    pub fn calculate_axon(&self) -> Option<f64> {
        self.try_axon().ok()
    }

    /// Fallible Axon calculation with structured errors.
    pub fn try_axon(&self) -> Result<f64> {
        let vortex = self.try_vortex()?;

        match self.try_radiance() {
            Ok(radiance) => {
                let score = (vortex * radiance).sqrt();
                if !score.is_finite() {
                    return Err(SynapseError::InvalidValue {
                        field: "axon",
                        reason: "calculation produced a non-finite result",
                    });
                }
                Ok(score)
            }
            // Wired / no radio data: Axon degrades gracefully to Vortex.
            Err(SynapseError::MissingField(_)) => Ok(vortex),
            Err(err) => Err(err),
        }
    }
}

fn require(value: Option<f64>, field: &'static str) -> Result<f64> {
    value.ok_or(SynapseError::MissingField(field))
}

fn ensure_finite(value: f64, field: &'static str) -> Result<()> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(SynapseError::InvalidValue {
            field,
            reason: "must be a finite number",
        })
    }
}

fn ensure_finite_non_negative(value: f64, field: &'static str) -> Result<()> {
    ensure_finite(value, field)?;
    if value < 0.0 {
        return Err(SynapseError::InvalidValue {
            field,
            reason: "must be >= 0",
        });
    }
    Ok(())
}

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

    fn full_sample() -> NetworkData {
        NetworkData::new()
            .with_down_mbps(150.0)
            .with_up_mbps(40.0)
            .with_ping_ms(18.0)
            .with_jitter_ms(2.0)
            .with_packet_loss_percent(0.0)
            .with_rssi_dbm(-60.0)
            .with_noise_dbm(-90.0)
            .with_channel_width_mhz(40.0)
    }

    fn wired_sample() -> NetworkData {
        NetworkData::new()
            .with_down_mbps(45.0)
            .with_up_mbps(12.0)
            .with_ping_ms(35.0)
            .with_jitter_ms(4.0)
            .with_packet_loss_percent(0.1)
    }

    #[test]
    fn vortex_happy_path() {
        let v = full_sample().try_vortex().unwrap();
        assert!(v.is_finite() && v > 0.0);
    }

    #[test]
    fn radiance_happy_path() {
        // width_factor = 40/20 = 2, snr = 30 → radiance = 60
        let r = full_sample().try_radiance().unwrap();
        assert!((r - 60.0).abs() < 1e-9);
    }

    #[test]
    fn axon_is_geometric_mean_when_wireless() {
        let data = full_sample();
        let vx = data.try_vortex().unwrap();
        let rd = data.try_radiance().unwrap();
        let axon = data.try_axon().unwrap();
        assert!((axon - (vx * rd).sqrt()).abs() < 1e-9);
    }

    #[test]
    fn axon_falls_back_to_vortex_on_wired() {
        let data = wired_sample();
        let vx = data.try_vortex().unwrap();
        let axon = data.try_axon().unwrap();
        assert!((axon - vx).abs() < 1e-12);
        assert!(data.calculate_radiance().is_none());
    }

    #[test]
    fn missing_fields_return_none_and_error() {
        let data = NetworkData::new();
        assert!(data.calculate_vortex().is_none());
        assert!(matches!(
            data.try_vortex(),
            Err(SynapseError::MissingField("down_mbps"))
        ));
    }

    #[test]
    fn rejects_negative_speeds() {
        let data = wired_sample().with_down_mbps(-1.0);
        assert!(matches!(
            data.try_vortex(),
            Err(SynapseError::InvalidValue {
                field: "down_mbps",
                reason: "must be >= 0"
            })
        ));
        assert!(data.calculate_vortex().is_none());
    }

    #[test]
    fn rejects_nan_and_inf() {
        let data = wired_sample().with_ping_ms(f64::NAN);
        assert!(matches!(
            data.try_vortex(),
            Err(SynapseError::InvalidValue {
                field: "ping_ms",
                reason: "must be a finite number"
            })
        ));

        let data = wired_sample().with_up_mbps(f64::INFINITY);
        assert!(data.try_vortex().is_err());
    }

    #[test]
    fn rejects_packet_loss_out_of_range() {
        let data = wired_sample().with_packet_loss_percent(150.0);
        assert!(matches!(
            data.try_vortex(),
            Err(SynapseError::InvalidValue {
                field: "packet_loss_percent",
                ..
            })
        ));
    }

    #[test]
    fn total_packet_loss_zeroes_vortex() {
        let data = wired_sample().with_packet_loss_percent(100.0);
        let v = data.try_vortex().unwrap();
        assert!((v - 0.0).abs() < 1e-12);
    }

    #[test]
    fn rejects_rssi_below_noise() {
        let data = NetworkData::new()
            .with_rssi_dbm(-100.0)
            .with_noise_dbm(-90.0)
            .with_channel_width_mhz(20.0);
        assert!(matches!(
            data.try_radiance(),
            Err(SynapseError::InvalidValue {
                field: "rssi_dbm",
                reason: "RSSI is below the noise floor"
            })
        ));
    }

    #[test]
    fn rejects_zero_channel_width() {
        let data = NetworkData::new()
            .with_rssi_dbm(-60.0)
            .with_noise_dbm(-90.0)
            .with_channel_width_mhz(0.0);
        assert!(data.try_radiance().is_err());
    }

    #[test]
    fn zero_latency_still_finite_thanks_to_epsilon() {
        let data = wired_sample().with_ping_ms(0.0).with_jitter_ms(0.0);
        let v = data.try_vortex().unwrap();
        assert!(v.is_finite() && v > 0.0);
    }

    #[test]
    fn score_band_thresholds() {
        assert_eq!(ScoreBand::from_score(10.0), ScoreBand::Critical);
        assert_eq!(ScoreBand::from_score(80.0), ScoreBand::Poor);
        assert_eq!(ScoreBand::from_score(200.0), ScoreBand::Fair);
        assert_eq!(ScoreBand::from_score(500.0), ScoreBand::Good);
        assert_eq!(ScoreBand::from_score(1500.0), ScoreBand::Excellent);
        assert_eq!(ScoreBand::from_score(f64::NAN), ScoreBand::Critical);
    }

    #[test]
    fn has_data_helpers() {
        assert!(full_sample().has_performance_data());
        assert!(full_sample().has_wireless_data());
        assert!(wired_sample().has_performance_data());
        assert!(!wired_sample().has_wireless_data());
    }

    #[test]
    fn invalid_wireless_does_not_silently_fallback_axon() {
        // Vortex OK, but radiance present and invalid → Axon must error,
        // not pretend it is a wired link.
        let data = wired_sample()
            .with_rssi_dbm(-100.0)
            .with_noise_dbm(-90.0)
            .with_channel_width_mhz(20.0);
        assert!(data.try_axon().is_err());
        assert!(data.calculate_axon().is_none());
    }
}