lb-sparkplugb-rs 0.1.1

Eclipse Sparkplug B 3.0.0 protocol library — payload codec, topic namespace, sequence/bdSeq, and (phased) edge & host roles, in Rust.
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! Host Application tests, driven by an in-memory transport (no broker).

use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use bytes::Bytes;
use sparkplug_b::model::Metric;
use sparkplug_b::{
    BDSEQ_METRIC_NAME, ConnectOptions, EncodeOptions, HostApplication, HostConfig, HostEvent,
    IncomingMessage, MetricValue, MqttTransport, NODE_CONTROL_REBIRTH, OutboundMessage, Payload,
    Qos, Result, StatePayload, encode,
};

// ---- in-memory transport -------------------------------------------------

#[derive(Default)]
struct Recorder {
    published: Vec<OutboundMessage>,
    subscriptions: Vec<(String, Qos)>,
    will: Option<OutboundMessage>,
    connected: bool,
}

#[derive(Clone, Default)]
struct MockTransport {
    shared: Arc<Mutex<Recorder>>,
    incoming: Arc<Mutex<VecDeque<IncomingMessage>>>,
}

impl MqttTransport for MockTransport {
    async fn connect(&mut self, opts: &ConnectOptions) -> Result<()> {
        let mut s = self.shared.lock().unwrap();
        s.will = opts.will.clone();
        s.connected = true;
        Ok(())
    }
    async fn subscribe(&mut self, topic_filter: &str, qos: Qos) -> Result<()> {
        self.shared
            .lock()
            .unwrap()
            .subscriptions
            .push((topic_filter.to_owned(), qos));
        Ok(())
    }
    async fn publish(&mut self, message: &OutboundMessage) -> Result<()> {
        self.shared.lock().unwrap().published.push(message.clone());
        Ok(())
    }
    async fn disconnect(&mut self) -> Result<()> {
        self.shared.lock().unwrap().connected = false;
        Ok(())
    }
    async fn recv(&mut self) -> Result<Option<IncomingMessage>> {
        Ok(self.incoming.lock().unwrap().pop_front())
    }
}

// ---- message builders ----------------------------------------------------

fn host_config() -> HostConfig {
    let mut c = HostConfig::new("myhost");
    c.rebirth_debounce = Duration::ZERO;
    c
}

fn msg(topic: &str, payload: Bytes) -> IncomingMessage {
    IncomingMessage {
        topic: topic.to_owned(),
        payload,
    }
}

fn nbirth(bdseq: i64, aliased: bool) -> Bytes {
    let mut temperature = Metric::new("Temperature", MetricValue::Double(20.0));
    let mut pressure = Metric::new("Pressure", MetricValue::Int32(100));
    if aliased {
        temperature = temperature.with_alias(0);
        pressure = pressure.with_alias(1);
    }
    let payload = Payload::new()
        .with_seq(0)
        .with_metric(temperature)
        .with_metric(pressure)
        .with_metric(Metric::new(
            NODE_CONTROL_REBIRTH,
            MetricValue::Boolean(false),
        ))
        .with_metric(Metric::new(BDSEQ_METRIC_NAME, MetricValue::Int64(bdseq)));
    encode(&payload, EncodeOptions::birth())
}

fn ndata(seq: u8, aliased: bool, value: f64) -> Bytes {
    let metric = if aliased {
        Metric::aliased(0, MetricValue::Double(value))
    } else {
        Metric::new("Temperature", MetricValue::Double(value))
    };
    let payload = Payload::new().with_seq(seq).with_metric(metric);
    encode(&payload, EncodeOptions::data())
}

fn ndeath(bdseq: i64) -> Bytes {
    let payload = Payload {
        timestamp: Some(1),
        metrics: vec![Metric::new(BDSEQ_METRIC_NAME, MetricValue::Int64(bdseq))],
        seq: None,
        uuid: None,
        body: None,
    };
    encode(&payload, EncodeOptions::birth())
}

fn dbirth(seq: u8) -> Bytes {
    let payload = Payload::new()
        .with_seq(seq)
        .with_metric(Metric::new("Flow", MetricValue::Double(1.0)));
    encode(&payload, EncodeOptions::birth())
}

fn ddata(seq: u8, value: f64) -> Bytes {
    let payload = Payload::new()
        .with_seq(seq)
        .with_metric(Metric::new("Flow", MetricValue::Double(value)));
    encode(&payload, EncodeOptions::data())
}

fn ddeath(seq: u8) -> Bytes {
    let payload = Payload {
        timestamp: Some(1),
        metrics: Vec::new(),
        seq: Some(seq),
        uuid: None,
        body: None,
    };
    encode(&payload, EncodeOptions::birth())
}

async fn started() -> (HostApplication<MockTransport>, Arc<Mutex<Recorder>>) {
    let mock = MockTransport::default();
    let shared = mock.shared.clone();
    let mut host = HostApplication::new(host_config(), mock);
    host.start().await.unwrap();
    (host, shared)
}

// ---- tests ---------------------------------------------------------------

#[tokio::test]
async fn start_publishes_retained_state_birth_and_will_sharing_one_timestamp() {
    let (_host, shared) = started().await;
    let s = shared.lock().unwrap();
    assert!(s.connected);

    let birth = &s.published[0];
    assert_eq!(birth.topic, "spBv1.0/STATE/myhost");
    assert_eq!(birth.qos, Qos::AtLeastOnce, "STATE QoS MUST be 1");
    assert!(birth.retain, "STATE birth retain MUST be true");
    let birth_state = StatePayload::parse(std::str::from_utf8(&birth.payload).unwrap()).unwrap();
    assert!(birth_state.online);

    let will = s.will.as_ref().expect("will registered");
    let will_state = StatePayload::parse(std::str::from_utf8(&will.payload).unwrap()).unwrap();
    assert!(!will_state.online);
    assert_eq!(
        birth_state.timestamp, will_state.timestamp,
        "birth reuses the will's timestamp"
    );

    let state_sub = s
        .subscriptions
        .iter()
        .find(|(t, _)| t == "spBv1.0/STATE/myhost")
        .unwrap();
    assert_eq!(state_sub.1, Qos::AtLeastOnce);
    assert!(s.subscriptions.iter().any(|(t, _)| t == "spBv1.0/#"));
}

#[tokio::test]
async fn node_birth_then_data_by_name() {
    let (mut host, _shared) = started().await;
    let event = host
        .handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap();
    assert!(matches!(event, HostEvent::NodeBirth { .. }));

    match host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(1, false, 21.0)))
        .await
        .unwrap()
    {
        HostEvent::NodeData {
            group,
            edge,
            metrics,
        } => {
            assert_eq!((group.as_str(), edge.as_str()), ("G", "E"));
            assert_eq!(metrics[0].name.as_deref(), Some("Temperature"));
            assert_eq!(metrics[0].value, MetricValue::Double(21.0));
        }
        other => panic!("expected NodeData, got {other:?}"),
    }
}

#[tokio::test]
async fn node_data_with_aliases_resolves_back_to_names() {
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, true)))
        .await
        .unwrap();

    match host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(1, true, 21.0)))
        .await
        .unwrap()
    {
        HostEvent::NodeData { metrics, .. } => {
            assert_eq!(metrics[0].alias, Some(0));
            assert_eq!(
                metrics[0].name.as_deref(),
                Some("Temperature"),
                "alias resolved to name"
            );
            assert_eq!(metrics[0].value, MetricValue::Double(21.0));
        }
        other => panic!("expected NodeData, got {other:?}"),
    }
}

#[tokio::test]
async fn data_before_birth_requests_rebirth() {
    let (mut host, shared) = started().await;
    let event = host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(1, false, 1.0)))
        .await
        .unwrap();
    assert!(matches!(event, HostEvent::RebirthRequested { .. }));
    let s = shared.lock().unwrap();
    assert!(
        s.published.iter().any(|m| m.topic == "spBv1.0/G/NCMD/E"),
        "a rebirth NCMD was published"
    );
}

#[tokio::test]
async fn sequence_gap_requests_rebirth() {
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap();
    // Expected seq is 1; sending 5 is a gap.
    let event = host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(5, false, 1.0)))
        .await
        .unwrap();
    assert!(matches!(event, HostEvent::RebirthRequested { .. }));
}

#[tokio::test]
async fn ndeath_honored_only_on_matching_bdseq() {
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap();

    // Mismatched bdSeq -> stale death, ignored.
    let stale = host
        .handle_incoming(&msg("spBv1.0/G/NDEATH/E", ndeath(9)))
        .await
        .unwrap();
    assert!(matches!(stale, HostEvent::Ignored));

    // Matching bdSeq -> NodeDeath.
    let death = host
        .handle_incoming(&msg("spBv1.0/G/NDEATH/E", ndeath(5)))
        .await
        .unwrap();
    assert!(matches!(death, HostEvent::NodeDeath { .. }));
}

#[tokio::test]
async fn device_birth_data_and_death_share_the_node_sequence() {
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap(); // expected -> 1

    let birth = host
        .handle_incoming(&msg("spBv1.0/G/DBIRTH/E/dev1", dbirth(1)))
        .await
        .unwrap();
    assert!(matches!(birth, HostEvent::DeviceBirth { .. })); // expected -> 2
    let data = host
        .handle_incoming(&msg("spBv1.0/G/DDATA/E/dev1", ddata(2, 9.0)))
        .await
        .unwrap();
    match data {
        HostEvent::DeviceData {
            device, metrics, ..
        } => {
            assert_eq!(device, "dev1");
            assert_eq!(metrics[0].name.as_deref(), Some("Flow"));
        }
        other => panic!("expected DeviceData, got {other:?}"),
    }
    let death = host
        .handle_incoming(&msg("spBv1.0/G/DDEATH/E/dev1", ddeath(3)))
        .await
        .unwrap();
    assert!(matches!(death, HostEvent::DeviceDeath { .. }));
}

#[tokio::test]
async fn self_state_offline_triggers_online_republish() {
    let (mut host, shared) = started().await;
    let before = shared.lock().unwrap().published.len();

    let event = host
        .handle_incoming(&msg(
            "spBv1.0/STATE/myhost",
            Bytes::from(StatePayload::new(false, 1).to_json()),
        ))
        .await
        .unwrap();
    assert!(matches!(event, HostEvent::Ignored));

    let s = shared.lock().unwrap();
    assert_eq!(s.published.len(), before + 1, "republished an online STATE");
    let last =
        StatePayload::parse(std::str::from_utf8(&s.published.last().unwrap().payload).unwrap())
            .unwrap();
    assert!(last.online);
}

#[tokio::test]
async fn own_command_echo_is_ignored() {
    let (mut host, shared) = started().await;
    let before = shared.lock().unwrap().published.len();
    let payload = Payload::new().with_metric(Metric::new("x", MetricValue::Int32(1)));
    let event = host
        .handle_incoming(&msg(
            "spBv1.0/G/NCMD/E",
            encode(&payload, EncodeOptions::birth()),
        ))
        .await
        .unwrap();
    assert!(matches!(event, HostEvent::Ignored));
    assert_eq!(
        shared.lock().unwrap().published.len(),
        before,
        "no side effects"
    );
}

#[tokio::test]
async fn shutdown_publishes_offline_state_and_disconnects() {
    let (mut host, shared) = started().await;
    host.shutdown().await.unwrap();
    let s = shared.lock().unwrap();
    assert!(!s.connected);
    let last = s.published.last().unwrap();
    assert_eq!(last.topic, "spBv1.0/STATE/myhost");
    let state = StatePayload::parse(std::str::from_utf8(&last.payload).unwrap()).unwrap();
    assert!(!state.online);
}

#[tokio::test]
async fn rebirth_requests_are_debounced() {
    let mut cfg = host_config();
    cfg.rebirth_debounce = Duration::from_secs(60);
    let mock = MockTransport::default();
    let shared = mock.shared.clone();
    let mut host = HostApplication::new(cfg, mock);
    host.start().await.unwrap();
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap();

    let first = host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(9, false, 1.0)))
        .await
        .unwrap();
    assert!(matches!(first, HostEvent::RebirthRequested { .. }));
    let second = host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(9, false, 1.0)))
        .await
        .unwrap();
    assert!(
        matches!(second, HostEvent::Ignored),
        "second rebirth within the window is debounced"
    );

    let ncmds = shared
        .lock()
        .unwrap()
        .published
        .iter()
        .filter(|m| m.topic == "spBv1.0/G/NCMD/E")
        .count();
    assert_eq!(ncmds, 1, "only one rebirth NCMD published");
}

// ---- review-driven additions --------------------------------------------

#[tokio::test]
async fn node_death_surfaces_affected_devices_and_timestamp() {
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap();
    host.handle_incoming(&msg("spBv1.0/G/DBIRTH/E/dev1", dbirth(1)))
        .await
        .unwrap();

    match host
        .handle_incoming(&msg("spBv1.0/G/NDEATH/E", ndeath(5)))
        .await
        .unwrap()
    {
        HostEvent::NodeDeath {
            devices, timestamp, ..
        } => {
            assert_eq!(
                devices,
                vec!["dev1".to_owned()],
                "the online device is surfaced as stale"
            );
            assert_eq!(timestamp, 1, "the NDEATH payload timestamp is surfaced");
        }
        other => panic!("expected NodeDeath, got {other:?}"),
    }
}

#[tokio::test]
async fn device_death_surfaces_timestamp() {
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap();
    host.handle_incoming(&msg("spBv1.0/G/DBIRTH/E/dev1", dbirth(1)))
        .await
        .unwrap();

    match host
        .handle_incoming(&msg("spBv1.0/G/DDEATH/E/dev1", ddeath(2)))
        .await
        .unwrap()
    {
        HostEvent::DeviceDeath { timestamp, .. } => assert_eq!(timestamp, 1),
        other => panic!("expected DeviceDeath, got {other:?}"),
    }
}

#[tokio::test]
async fn ndeath_without_bdseq_is_ignored() {
    let nbirth_no_bdseq = {
        let p = Payload::new()
            .with_seq(0)
            .with_metric(Metric::new("Temperature", MetricValue::Double(20.0)))
            .with_metric(Metric::new(
                NODE_CONTROL_REBIRTH,
                MetricValue::Boolean(false),
            ));
        encode(&p, EncodeOptions::birth())
    };
    let ndeath_no_bdseq = {
        let p = Payload {
            timestamp: Some(1),
            metrics: Vec::new(),
            seq: None,
            uuid: None,
            body: None,
        };
        encode(&p, EncodeOptions::birth())
    };
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth_no_bdseq))
        .await
        .unwrap();
    // Both sides omit bdSeq -> the None==None match must NOT honor the death.
    let event = host
        .handle_incoming(&msg("spBv1.0/G/NDEATH/E", ndeath_no_bdseq))
        .await
        .unwrap();
    assert!(matches!(event, HostEvent::Ignored));
}

#[tokio::test]
async fn duplicate_alias_birth_invalidates_session_until_rebirth() {
    let dup = {
        let p = Payload::new()
            .with_seq(0)
            .with_metric(Metric::new("A", MetricValue::Int32(1)).with_alias(0))
            .with_metric(Metric::new("B", MetricValue::Int32(2)).with_alias(0))
            .with_metric(Metric::new(BDSEQ_METRIC_NAME, MetricValue::Int64(5)));
        encode(&p, EncodeOptions::birth())
    };
    let (mut host, _shared) = started().await;
    let birth = host
        .handle_incoming(&msg("spBv1.0/G/NBIRTH/E", dup))
        .await
        .unwrap();
    assert!(matches!(birth, HostEvent::RebirthRequested { .. }));

    let data = host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(1, false, 1.0)))
        .await
        .unwrap();
    assert!(
        matches!(
            data,
            HostEvent::RebirthRequested { .. } | HostEvent::Ignored
        ),
        "NDATA against an invalidated session must not be emitted as NodeData"
    );
}

#[tokio::test]
async fn malformed_in_session_data_routes_to_rebirth_not_err() {
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap();
    let result = host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", Bytes::from_static(&[0x12, 0x05])))
        .await;
    assert!(matches!(result, Ok(HostEvent::RebirthRequested { .. })));
}

#[tokio::test]
async fn re_nbirth_resets_an_already_online_session() {
    let (mut host, _shared) = started().await;
    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(5, false)))
        .await
        .unwrap();
    host.handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(1, false, 1.0)))
        .await
        .unwrap();

    host.handle_incoming(&msg("spBv1.0/G/NBIRTH/E", nbirth(6, false)))
        .await
        .unwrap();
    let event = host
        .handle_incoming(&msg("spBv1.0/G/NDATA/E", ndata(1, false, 2.0)))
        .await
        .unwrap();
    assert!(
        matches!(event, HostEvent::NodeData { .. }),
        "session reset by the re-NBIRTH"
    );
}

#[tokio::test]
async fn device_birth_before_node_birth_requests_rebirth() {
    let (mut host, _shared) = started().await;
    let event = host
        .handle_incoming(&msg("spBv1.0/G/DBIRTH/E/dev1", dbirth(1)))
        .await
        .unwrap();
    assert!(matches!(event, HostEvent::RebirthRequested { .. }));
}

#[tokio::test]
async fn publish_node_and_device_commands() {
    let (mut host, shared) = started().await;
    host.publish_node_command(
        "G",
        "E",
        vec![Metric::new("Output", MetricValue::Boolean(true))],
    )
    .await
    .unwrap();
    host.publish_device_command(
        "G",
        "E",
        "dev1",
        vec![Metric::new("SP", MetricValue::Double(5.0))],
    )
    .await
    .unwrap();

    let s = shared.lock().unwrap();
    let ncmd = s
        .published
        .iter()
        .find(|m| m.topic == "spBv1.0/G/NCMD/E")
        .expect("NCMD published");
    assert_eq!(ncmd.qos, Qos::AtMostOnce);
    assert!(!ncmd.retain);
    let decoded = sparkplug_b::decode(&ncmd.payload, None).unwrap();
    assert_eq!(decoded.metrics[0].name.as_deref(), Some("Output"));
    assert_eq!(decoded.metrics[0].value, MetricValue::Boolean(true));

    let dcmd = s
        .published
        .iter()
        .find(|m| m.topic == "spBv1.0/G/DCMD/E/dev1")
        .expect("DCMD published");
    assert_eq!(dcmd.qos, Qos::AtMostOnce);
    assert!(!dcmd.retain);
}

#[tokio::test]
async fn malformed_birth_and_non_utf8_state_return_err_not_panic() {
    let (mut host, _shared) = started().await;
    assert!(
        host.handle_incoming(&msg(
            "spBv1.0/G/NBIRTH/E",
            Bytes::from_static(&[0x12, 0x05])
        ))
        .await
        .is_err()
    );
    assert!(
        host.handle_incoming(&msg(
            "spBv1.0/STATE/myhost",
            Bytes::from_static(&[0xFF, 0xFE])
        ))
        .await
        .is_err()
    );
}