liminal-server 0.19.1

Standalone server for the liminal messaging bus
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
//! The held topology: one revision per real change, nothing for a repeat,
//! never a console line, and a document in the console's names.

use std::time::{Duration, Instant};

use super::error::ConsoleError;
use super::model::{FlowRole, ThisDevice, TopologyChange, TopologyModel};
use super::records::{LineLife, LineState, Mount, canonical_bytes};
use super::wall::WallBase;

type TestResult = Result<(), Box<dyn std::error::Error>>;

fn model(started: Instant) -> TopologyModel {
    TopologyModel::new(
        ThisDevice {
            id: "local".to_owned(),
            liminal: "1.2.3".to_owned(),
            started,
            depot: false,
        },
        ["orders.reply".to_owned()],
        [
            ("orders".to_owned(), LineLife::Kept, LineState::Live),
            (
                "console.topology".to_owned(),
                LineLife::Passing,
                LineState::Live,
            ),
            (
                "console.tap.orders".to_owned(),
                LineLife::Passing,
                LineState::Live,
            ),
        ],
        [(7, Mount::Websocket, Some("alice".to_owned()))],
        [],
    )
}

/// The wall clock the tests read: [`WALL_MS`] at the instant a document is
/// built.
const WALL_MS: u64 = 1_791_272_000_000;

fn document(
    model: &TopologyModel,
    built: Instant,
) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
    Ok(serde_json::from_slice(&canonical_bytes(
        &model.document(&WallBase::fixed(WALL_MS, built)).0,
        "topology",
    )?)?)
}

/// R7: with console.topology and two console.tap channels live, no line id
/// starts with console., at start or after a change names one.
#[test]
fn the_topology_has_no_console_line() -> TestResult {
    let started = Instant::now();
    let mut model = model(started);
    assert!(!model.apply(TopologyChange::Channel {
        name: "console.tap.audit".to_owned(),
        life: LineLife::Passing,
        state: LineState::Live,
    }));
    let value = document(&model, started)?;
    let lines = value["lines"].as_array().ok_or("lines is an array")?;
    assert_eq!(lines.len(), 1);
    assert!(lines.iter().all(|line| {
        !line["id"]
            .as_str()
            .is_some_and(|id| id.starts_with("console."))
    }));
    Ok(())
}

/// Each real change moves the revision on by exactly one; a repeat moves it
/// not at all, so it publishes nothing.
#[test]
fn one_revision_per_real_change() {
    let started = Instant::now();
    let mut model = model(started);
    assert_eq!(model.rev(), 1);
    let changes = [
        TopologyChange::Service {
            subject: "billing".to_owned(),
            present: true,
        },
        TopologyChange::Channel {
            name: "orders".to_owned(),
            life: LineLife::Kept,
            state: LineState::Quiesced,
        },
        TopologyChange::ConnectionOpened {
            id: 8,
            mount: Mount::Tcp,
            participant: None,
        },
        TopologyChange::Peer {
            name: "edge".to_owned(),
            present: true,
        },
    ];
    for change in changes.clone() {
        assert!(model.apply(change));
    }
    assert_eq!(model.rev(), 5);
    for change in changes {
        assert!(!model.apply(change), "a repeat is not a change");
    }
    assert_eq!(model.rev(), 5);
    assert!(model.apply(TopologyChange::ConnectionClosed { id: 8 }));
    assert!(!model.apply(TopologyChange::ConnectionClosed { id: 8 }));
    assert_eq!(model.rev(), 6);
}

/// A peer appears as a device and an up link whose ends are both listed
/// devices, sorted; when it leaves, both are gone. This device carries its
/// version and its start in wall milliseconds; a peer carries neither.
#[test]
fn a_peer_joins_and_leaves_the_document() -> TestResult {
    let started = Instant::now();
    let mut model = model(started);
    model.apply(TopologyChange::Peer {
        name: "edge".to_owned(),
        present: true,
    });
    let joined = document(&model, started + Duration::from_secs(3_600))?;
    assert_eq!(joined["rev"], 2);
    assert_eq!(joined["devices"][0]["started"], WALL_MS - 3_600_000);
    assert_eq!(joined["devices"][0]["liminal"], "1.2.3");
    assert_eq!(joined["devices"][1]["id"], "edge");
    assert!(joined["devices"][1].get("liminal").is_none());
    assert_eq!(
        joined["links"][0]["ends"],
        serde_json::json!(["edge", "local"])
    );
    assert_eq!(joined["links"][0]["state"], "up");
    assert_eq!(joined["connections"][0]["id"], "7");
    assert_eq!(joined["stations"][0]["device"], "local");

    model.apply(TopologyChange::Peer {
        name: "edge".to_owned(),
        present: false,
    });
    let left = document(&model, started)?;
    assert_eq!(left["rev"], 3);
    assert_eq!(left["devices"].as_array().map(Vec::len), Some(1));
    assert_eq!(left["links"].as_array().map(Vec::len), Some(0));
    Ok(())
}

/// R7: a registered worker is a station, and a line's stops are its
/// registered publishers then its registered subscribers, each once; an
/// unregistered connection is no stop, and a closed one leaves the line.
#[test]
fn a_line_runs_from_its_publisher_to_its_subscriber() -> TestResult {
    let started = Instant::now();
    let mut model = model(started);
    let flow = |connection, role| TopologyChange::Flow {
        connection,
        line: "orders".to_owned(),
        role,
        present: true,
    };
    for (connection, identity) in [(11, "ping"), (12, "pong")] {
        assert!(model.apply(TopologyChange::Worker {
            connection,
            identity: identity.to_owned(),
        }));
    }
    assert!(model.apply(flow(12, FlowRole::Subscribes)));
    assert!(model.apply(flow(11, FlowRole::Publishes)));
    assert!(
        !model.apply(flow(11, FlowRole::Publishes)),
        "a repeat is no change"
    );
    assert!(
        !model.apply(flow(7, FlowRole::Subscribes)),
        "an unregistered connection"
    );
    let value = document(&model, started)?;
    assert_eq!(value["lines"][0]["id"], "orders");
    assert_eq!(
        value["lines"][0]["stops"],
        serde_json::json!(["ping", "local", "pong"])
    );
    let stations: Vec<&str> = value["stations"]
        .as_array()
        .ok_or("stations")?
        .iter()
        .filter_map(|station| station["id"].as_str())
        .collect();
    assert_eq!(stations, ["local", "orders.reply", "ping", "pong"]);
    let kinds: Vec<&str> = value["stations"]
        .as_array()
        .ok_or("stations")?
        .iter()
        .filter_map(|station| station["kind"].as_str())
        .collect();
    assert_eq!(kinds, ["exchange", "service", "worker", "worker"]);
    assert_eq!(
        value["devices"][0]["box"],
        serde_json::json!({"x": -140, "y": 60, "w": 1340, "h": 520})
    );

    assert!(model.apply(TopologyChange::ConnectionClosed { id: 12 }));
    let value = document(&model, started)?;
    assert_eq!(
        value["lines"][0]["stops"],
        serde_json::json!(["ping", "local"])
    );
    Ok(())
}

/// A worker that stops subscribing leaves the line's stops at once, without
/// waiting for its connection to close.
#[test]
fn a_flow_withdrawn_leaves_the_stops() -> TestResult {
    let started = Instant::now();
    let mut model = model(started);
    let flow = |present| TopologyChange::Flow {
        connection: 12,
        line: "orders".to_owned(),
        role: FlowRole::Subscribes,
        present,
    };
    assert!(model.apply(TopologyChange::Worker {
        connection: 12,
        identity: "pong".to_owned(),
    }));
    assert!(model.apply(flow(true)));
    assert!(model.apply(flow(false)));
    assert!(!model.apply(flow(false)), "a repeat is no change");
    let value = document(&model, started)?;
    assert_eq!(value["lines"][0]["stops"], serde_json::json!(["local"]));
    Ok(())
}

/// This device's start is its incarnation's, in wall milliseconds, and the
/// same whenever the document is built: one built at T+0 and read at T+30 s
/// lets the reader show 30 s more than at T+0, where an uptime stamped at
/// T+0 would still read T+0 (Hermes 7 Oct 01:49).
#[test]
fn the_start_is_the_incarnations_whenever_the_document_is_built() -> TestResult {
    let built = Instant::now();
    let mut model = model(built);
    let incarnation = built.checked_sub(Duration::from_secs(5)).ok_or("clock")?;
    assert!(model.incarnation_started(incarnation));

    let (at_zero, fault) = model.document(&WallBase::fixed(WALL_MS, built));
    assert!(fault.is_none(), "{fault:?}");
    // The same wall clock, read 30 s later.
    let later = built + Duration::from_secs(30);
    let (at_thirty, _) = model.document(&WallBase::fixed(WALL_MS + 30_000, later));
    let started = at_zero.devices[0]
        .started
        .ok_or("no start on this device")?;
    assert_eq!(started, WALL_MS - 5_000);
    assert_eq!(at_thirty.devices[0].started, Some(started));
    let read_at_thirty = WALL_MS + 30_000;
    assert_eq!(
        read_at_thirty - started,
        35_000,
        "the uptime read at T+30 s"
    );
    let value = document(&model, built)?;
    assert!(
        value["devices"][0].get("uptime").is_none(),
        "no stale uptime field"
    );
    Ok(())
}

/// Buttercup's finding 3 (Hermes 03:05): this device carries its start or
/// the fault that kept it, never both and never neither. A start the wall
/// clock can give is `started` alone; one before the epoch is
/// `started_fault` alone, naming the clock, and the fault comes back beside
/// the document for the hub to count.
#[test]
fn a_device_has_its_start_or_its_fault_never_both() -> TestResult {
    let built = Instant::now();
    let model = model(built);
    let (good, none) = model.document(&WallBase::fixed(WALL_MS, built));
    assert!(none.is_none(), "{none:?}");
    assert_eq!(
        (
            good.devices[0].started.is_some(),
            good.devices[0].started_fault.is_none()
        ),
        (true, true)
    );
    // A wall base one second after the epoch, read with a start two seconds
    // before it.
    let mut early = model;
    let incarnation = built.checked_sub(Duration::from_secs(2)).ok_or("clock")?;
    early.incarnation_started(incarnation);
    let (faulted, fault) = early.document(&WallBase::fixed(1_000, built));
    assert!(
        matches!(fault, Some(ConsoleError::Clock { .. })),
        "{fault:?}"
    );
    assert_eq!(faulted.devices[0].started, None);
    assert_eq!(
        faulted.devices[0].started_fault.as_deref(),
        Some("console clock: a time is outside u64 milliseconds since the epoch")
    );
    for peer in &faulted.devices[1..] {
        assert_eq!((peer.started, peer.started_fault.as_deref()), (None, None));
    }
    Ok(())
}

/// Lane brief ruling 1 (Hermes 7 Oct 03:51): the document names this device
/// once, at the top level, as one of its devices' ids, whatever peers it
/// holds and however they sort.
#[test]
fn the_document_names_this_device_once() -> TestResult {
    let started = Instant::now();
    let mut model = model(started);
    model.apply(TopologyChange::Peer {
        name: "alpha".to_owned(),
        present: true,
    });
    let value = document(&model, started)?;
    assert_eq!(value["this_device"], "local");
    let devices = value["devices"]
        .as_array()
        .ok_or("the document has no devices")?;
    let named = devices
        .iter()
        .filter(|device| device["id"] == value["this_device"])
        .count();
    assert_eq!(named, 1, "this_device names exactly one device: {value}");
    Ok(())
}

/// Lane brief ruling 5 (Hermes 7 Oct 03:51): a server with a persistent
/// store has a depot, `<device>.depot`, and a durable line passes it after
/// its publishers and before its subscribers, because the append comes
/// before the fan-out. A passing line never stops there, and a server with
/// no persistent store lists no depot.
#[test]
fn a_durable_line_passes_the_depot_before_its_subscribers() -> TestResult {
    let started = Instant::now();
    let with_depot = |depot| {
        let mut model = TopologyModel::new(
            ThisDevice {
                id: "local".to_owned(),
                liminal: "1.2.3".to_owned(),
                started,
                depot,
            },
            [],
            [
                ("orders".to_owned(), LineLife::Kept, LineState::Live),
                ("audit".to_owned(), LineLife::Passing, LineState::Live),
            ],
            [],
            [],
        );
        for (connection, identity) in [(11, "ping"), (12, "pong")] {
            model.apply(TopologyChange::Worker {
                connection,
                identity: identity.to_owned(),
            });
        }
        for line in ["orders", "audit"] {
            for (connection, role) in [(11, FlowRole::Publishes), (12, FlowRole::Subscribes)] {
                model.apply(TopologyChange::Flow {
                    connection,
                    line: line.to_owned(),
                    role,
                    present: true,
                });
            }
        }
        model
    };
    let stops = |value: &serde_json::Value, line: &str| {
        value["lines"]
            .as_array()
            .and_then(|lines| lines.iter().find(|entry| entry["id"] == line))
            .map(|entry| entry["stops"].clone())
    };
    let kept = document(&with_depot(true), started)?;
    assert_eq!(
        stops(&kept, "orders"),
        Some(serde_json::json!(["ping", "local.depot", "local", "pong"]))
    );
    assert_eq!(
        stops(&kept, "audit"),
        Some(serde_json::json!(["ping", "local", "pong"]))
    );
    let depot = kept["stations"]
        .as_array()
        .and_then(|stations| {
            stations
                .iter()
                .find(|station| station["id"] == "local.depot")
        })
        .ok_or_else(|| format!("no depot station: {kept}"))?;
    assert_eq!(
        (&depot["kind"], &depot["device"]),
        (&serde_json::json!("depot"), &serde_json::json!("local"))
    );

    let memory = document(&with_depot(false), started)?;
    assert_eq!(
        stops(&memory, "orders"),
        Some(serde_json::json!(["ping", "local", "pong"]))
    );
    assert!(
        !memory.to_string().contains("local.depot"),
        "no persistent store, no depot: {memory}"
    );
    Ok(())
}

/// Lane brief ruling 2 (Hermes 7 Oct 03:51): this server's exchange is a
/// station whose id is the device's own, of kind `exchange`, and a stop on
/// every line exactly once: after the publishers and the depot, before the
/// subscribers, and alone on a line with no flows.
#[test]
fn every_line_passes_the_exchange_once() -> TestResult {
    let started = Instant::now();
    let mut model = TopologyModel::new(
        ThisDevice {
            id: "local".to_owned(),
            liminal: "1.2.3".to_owned(),
            started,
            depot: true,
        },
        [],
        [
            ("orders".to_owned(), LineLife::Kept, LineState::Live),
            ("audit".to_owned(), LineLife::Passing, LineState::Live),
            ("idle".to_owned(), LineLife::Passing, LineState::Live),
        ],
        [],
        [],
    );
    for (connection, identity) in [(11, "ping"), (12, "pong")] {
        model.apply(TopologyChange::Worker {
            connection,
            identity: identity.to_owned(),
        });
    }
    for line in ["orders", "audit"] {
        for (connection, role) in [(11, FlowRole::Publishes), (12, FlowRole::Subscribes)] {
            model.apply(TopologyChange::Flow {
                connection,
                line: line.to_owned(),
                role,
                present: true,
            });
        }
    }
    let value = document(&model, started)?;
    let stops = |line: &str| {
        value["lines"]
            .as_array()
            .and_then(|lines| lines.iter().find(|entry| entry["id"] == line))
            .map(|entry| entry["stops"].clone())
    };
    assert_eq!(
        stops("orders"),
        Some(serde_json::json!(["ping", "local.depot", "local", "pong"]))
    );
    assert_eq!(
        stops("audit"),
        Some(serde_json::json!(["ping", "local", "pong"]))
    );
    assert_eq!(stops("idle"), Some(serde_json::json!(["local"])));
    let exchange = value["stations"]
        .as_array()
        .and_then(|stations| stations.iter().find(|station| station["id"] == "local"))
        .ok_or_else(|| format!("no exchange station: {value}"))?;
    assert_eq!(
        (&exchange["kind"], &exchange["device"]),
        (&serde_json::json!("exchange"), &serde_json::json!("local"))
    );
    Ok(())
}