liminal-server 0.25.4

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
//! Carrier selection and message-scoped recovery for configured links.
//!
//! A refused configured dial leaves the named link down while its server keeps serving and retries.
//! Crossings use `link_export` and `link_import` on the opened link resource and require a configured export prefix.

use crate::config::types::OutboundLinkConfig;
use crate::link_carrier::Carrier;
use std::time::{Duration, Instant};

pub mod carriers;
pub mod network;
pub use carriers::Stop;

/// Bounds and service addresses for opening a configured link.
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ChoiceConfig {
    /// Explicit security and discovery bounds for a person's device links.
    pub peers: Option<crate::config::peers::PeersConfig>,
    /// Twice the estate's 1000ms design RTT budget, including a durable flush.
    /// `docs/perf/participant-record-rtt.md` documents localhost record RTTs;
    /// it does not itself verify the estate-wide ceiling used by this default.
    pub crossing_deadline_ms: u64,
    /// The broker's admitted wire listener.
    pub broker_address: Option<String>,
    /// The broker's observed-address echo listener.
    pub broker_echo: Option<std::net::SocketAddr>,
    /// The local device's UDP listener.
    pub udp_listen: std::net::SocketAddr,
    /// The configured relaying machine's recorded holder.
    pub relay_holder: Option<String>,
    /// The relay's admitted wire listener.
    pub relay_address: Option<String>,
}

impl Default for ChoiceConfig {
    fn default() -> Self {
        Self {
            peers: None,
            crossing_deadline_ms: 2000,
            broker_address: None,
            broker_echo: None,
            udp_listen: std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
            relay_holder: None,
            relay_address: None,
        }
    }
}

/// A prepared crossing retains its exact sealed bytes and Noise counter.
#[derive(Clone)]
pub struct Packet {
    pub subject: String,
    pub counter: u64,
    pub bytes: Vec<u8>,
    pub deadline: Option<Deadline>,
}

impl std::fmt::Debug for Packet {
    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        out.debug_struct("Packet")
            .field("subject", &self.subject)
            .field("counter", &self.counter)
            .field("bytes", &self.bytes.len())
            .field("deadline", &self.deadline)
            .finish()
    }
}

/// One crossing's absolute deadline, armed before its datagram is sent.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Deadline {
    expires: Instant,
    budget: Duration,
}

impl Deadline {
    /// # Errors
    /// The configured crossing budget exceeds the clock's range.
    pub fn after(budget: Duration) -> Result<Self, OpenError> {
        let expires = Instant::now()
            .checked_add(budget)
            .ok_or_else(|| OpenError("crossing_deadline_out_of_range".to_owned()))?;
        Ok(Self { expires, budget })
    }
    #[must_use]
    pub const fn budget(self) -> Duration {
        self.budget
    }
    #[must_use]
    pub const fn expires(self) -> Instant {
        self.expires
    }
}

/// A keyed carrier answers one crossing or one message deadline.
pub trait Path: Send + std::fmt::Debug {
    fn carrier(&self) -> Carrier;
    fn interrupt_handle(&self) -> Option<Stop> {
        None
    }
    fn relay_device(&self) -> Option<String>;
    fn life(&self) -> Option<crate::link::LinkLife> {
        None
    }
    /// # Errors
    /// Unsolicited traffic or an observed carrier end.
    fn refuse_unsolicited(&self) -> Result<(), OpenError> {
        Ok(())
    }
    /// The device's local direct index; streams have none.
    fn direct_index(&self) -> Option<u32> {
        None
    }
    /// # Errors
    /// Invalid input, oversized message, or exhausted Noise nonce.
    fn prepare(&mut self, subject: &str, plain: &[u8]) -> Result<Packet, OpenError>;
    /// # Errors
    /// The transport could not move this prepared packet.
    fn transmit(&mut self, packet: &Packet) -> Result<(), OpenError>;
    /// The bound exists only while this crossing is in flight.
    /// # Errors
    /// The carrier ended or the importing endpoint refused the crossing.
    fn receipt(&mut self, counter: u64, bound: Option<Deadline>) -> Result<bool, OpenError>;
}

/// The existing dial, broker, punch, and relay implementations meet here.
pub trait Backend: Send + std::fmt::Debug {
    /// Interrupts the backend's owned blocking operations during shutdown.
    fn interrupt_handle(&self) -> Option<Stop> {
        None
    }
    /// # Errors
    /// Carries the dialer's own named refusal.
    fn wire(
        &mut self,
        config: &OutboundLinkConfig,
        address: &str,
    ) -> Result<Box<dyn Path>, OpenError>;
    /// # Errors
    /// The broker could not return the peer's registered addresses.
    fn lookup(&mut self, config: &OutboundLinkConfig) -> Result<Vec<String>, OpenError>;
    /// # Errors
    /// The direct KK link could not open.
    fn punch(&mut self, config: &OutboundLinkConfig) -> Result<Box<dyn Path>, OpenError>;
    /// # Errors
    /// The relay or peer refused its endpoint-keyed link.
    fn relay(&mut self, config: &OutboundLinkConfig) -> Result<Box<dyn Path>, OpenError>;
    /// Refreshes the mapping while retaining this packet's transport and counter.
    /// # Errors
    /// The broker or peer could not refresh the direct endpoint.
    fn repunch(
        &mut self,
        config: &OutboundLinkConfig,
        path: &mut dyn Path,
    ) -> Result<(), OpenError>;
    /// # Errors
    /// The topology consumer could not record the observed fact.
    fn topology(
        &mut self,
        carrier: Option<Carrier>,
        relay: Option<String>,
        refusal: Option<&str>,
    ) -> Result<(), OpenError>;
}

/// A named refusal with no credential or message bytes.
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct OpenError(pub String);

/// One selected carrier and its on-demand recovery owner.
#[derive(Debug)]
pub struct Opened<B: Backend> {
    config: OutboundLinkConfig,
    choice: ChoiceConfig,
    backend: B,
    path: Option<Box<dyn Path>>,
    timers: usize,
    interrupt: carriers::StopSlot,
}

impl<B: Backend> Opened<B> {
    pub(crate) fn stopped(&self) -> bool {
        self.interrupt.stopped()
    }
    pub(crate) fn life(&self) -> Option<crate::link::LinkLife> {
        self.path.as_ref().and_then(|path| path.life())
    }
    pub(crate) fn refuse_unsolicited(&self) -> Result<(), OpenError> {
        self.path.as_ref().map_or_else(
            || Err(OpenError("link_has_no_carrier".to_owned())),
            |path| path.refuse_unsolicited(),
        )
    }
    pub(crate) const fn description(&self) -> &OutboundLinkConfig {
        &self.config
    }
    pub(crate) const fn backend(&self) -> &B {
        &self.backend
    }
    pub(crate) fn observed_carrier(&self) -> Option<crate::console::records::Carrier> {
        self.path.as_ref().and_then(|path| match path.carrier() {
            Carrier::Wire => Some(crate::console::records::Carrier::Wire),
            Carrier::Direct => Some(crate::console::records::Carrier::Direct),
            Carrier::Relay => path
                .relay_device()
                .map(crate::console::records::Carrier::Relay),
        })
    }
    /// # Errors
    /// This backend does not provide a shutdown interruption.
    pub fn interrupt_handle(&self) -> Result<Stop, OpenError> {
        self.interrupt.handle()
    }
    #[must_use]
    pub fn carrier(&self) -> Option<Carrier> {
        self.path.as_ref().map(|path| path.carrier())
    }
    #[must_use]
    pub const fn armed_timers(&self) -> usize {
        self.timers
    }
    /// Sends a crossing body already encoded by its exporting subscription.
    /// A production direct receipt is the importing publish response, never a transport ACK.
    /// # Errors
    /// Named open, carrier, crossing, or topology refusal.
    pub fn send(&mut self, subject: &str, plain: &[u8]) -> Result<(), OpenError> {
        if self.stopped() {
            return Err(OpenError("link_stopped".to_owned()));
        }
        crate::auth_lys::SubjectBinding::new(
            "wire".to_owned(),
            subject.to_owned(),
            subject.to_owned(),
        )
        .map_err(|error| OpenError(error.to_string()))?;
        if !self.config.exports.iter().any(|prefix| {
            subject == prefix
                || subject
                    .strip_prefix(prefix)
                    .is_some_and(|suffix| suffix.starts_with('.'))
        }) {
            return Err(OpenError("subject_not_exported_by_link".to_owned()));
        }
        if self.path.is_none() {
            let path = select(&self.config, &mut self.backend)?;
            self.interrupt.set(
                path.interrupt_handle()
                    .or_else(|| self.backend.interrupt_handle()),
            )?;
            self.path = Some(path);
        }
        let mut path = self
            .path
            .take()
            .ok_or_else(|| OpenError("link_has_no_carrier".to_owned()))?;
        let result = self.cross(path.as_mut(), subject, plain);
        self.timers = 0;
        match result {
            Ok(Crossing::Delivered) => {
                self.path = Some(path);
                Ok(())
            }
            Ok(Crossing::Relay) => self.cross_relay(subject, plain),
            Err(error) => {
                self.backend
                    .topology(Some(path.carrier()), path.relay_device(), Some(&error.0))?;
                if error.0.starts_with("crossing_refused:") {
                    self.path = Some(path);
                }
                Err(error)
            }
        }
    }

    fn cross(
        &mut self,
        path: &mut dyn Path,
        subject: &str,
        plain: &[u8],
    ) -> Result<Crossing, OpenError> {
        let mut packet = match path.prepare(subject, plain) {
            Ok(packet) => packet,
            Err(error)
                if path.carrier() == Carrier::Direct && error.0 == "too_large_for_datagram" =>
            {
                self.backend
                    .topology(Some(Carrier::Direct), None, Some(&error.0))?;
                return Ok(Crossing::Relay);
            }
            Err(error) => return Err(error),
        };
        if path.carrier() != Carrier::Direct {
            path.transmit(&packet)?;
            return if path.receipt(packet.counter, None)? {
                Ok(Crossing::Delivered)
            } else {
                Err(OpenError("stream_crossing_has_no_receipt".to_owned()))
            };
        }
        let bound = Duration::from_millis(self.choice.crossing_deadline_ms);
        packet.deadline = Some(Deadline::after(bound)?);
        self.timers = 1;
        path.transmit(&packet)?;
        if path.receipt(packet.counter, packet.deadline)? {
            return Ok(Crossing::Delivered);
        }
        self.backend
            .topology(Some(Carrier::Direct), None, Some("crossing_deadline"))?;
        if let Err(error) = self.backend.repunch(&self.config, path) {
            self.backend
                .topology(Some(Carrier::Direct), None, Some(&error.0))?;
            return Ok(Crossing::Relay);
        }
        // Reusing ciphertext is essential: sealing again would consume a second nonce.
        packet.deadline = Some(Deadline::after(bound)?);
        path.transmit(&packet)?;
        if path.receipt(packet.counter, packet.deadline)? {
            return Ok(Crossing::Delivered);
        }
        self.backend.topology(
            Some(Carrier::Direct),
            None,
            Some("second_crossing_deadline"),
        )?;
        Ok(Crossing::Relay)
    }

    fn cross_relay(&mut self, subject: &str, plain: &[u8]) -> Result<(), OpenError> {
        let mut relay = match self.backend.relay(&self.config) {
            Ok(relay) => relay,
            Err(error) => {
                self.backend
                    .topology(Some(Carrier::Relay), None, Some(&error.0))?;
                return Err(error);
            }
        };
        self.interrupt.set(
            relay
                .interrupt_handle()
                .or_else(|| self.backend.interrupt_handle()),
        )?;
        self.backend
            .topology(Some(relay.carrier()), relay.relay_device(), None)?;
        let crossing = (|| {
            let packet = relay.prepare(subject, plain)?;
            relay.transmit(&packet)?;
            if !relay.receipt(packet.counter, None)? {
                return Err(OpenError("relay_crossing_has_no_receipt".to_owned()));
            }
            Ok(())
        })();
        if let Err(error) = crossing {
            self.backend
                .topology(Some(Carrier::Relay), relay.relay_device(), Some(&error.0))?;
            return Err(error);
        }
        self.path = Some(relay);
        Ok(())
    }
}

enum Crossing {
    Delivered,
    Relay,
}

fn record<B: Backend>(
    backend: &mut B,
    carrier: Carrier,
    result: Result<Box<dyn Path>, OpenError>,
    refusals: &mut Vec<String>,
) -> Result<Option<Box<dyn Path>>, OpenError> {
    match result {
        Ok(path) => {
            backend.topology(Some(path.carrier()), path.relay_device(), None)?;
            Ok(Some(path))
        }
        Err(error) => {
            let name = match carrier {
                Carrier::Wire => "wire",
                Carrier::Direct => "direct",
                Carrier::Relay => "relay",
            };
            refusals.push(format!("{name}={}", error.0));
            backend.topology(Some(carrier), None, Some(&error.0))?;
            if error.0.starts_with("link_held:")
                || error.0.starts_with("link_refused:")
                || error.0 == "network_stopped"
            {
                return Err(error);
            }
            Ok(None)
        }
    }
}

fn select<B: Backend>(
    config: &OutboundLinkConfig,
    backend: &mut B,
) -> Result<Box<dyn Path>, OpenError> {
    let mut refusals = Vec::new();
    if let Some(address) = &config.peer_address {
        let result = backend.wire(config, address);
        if let Some(path) = record(backend, Carrier::Wire, result, &mut refusals)? {
            return Ok(path);
        }
    } else {
        let addresses = match backend.lookup(config) {
            Ok(addresses) => addresses,
            Err(error) => {
                refusals.push(format!("lookup={}", error.0));
                backend.topology(None, None, Some(&error.0))?;
                Vec::new()
            }
        };
        let mut tried = std::collections::BTreeSet::new();
        for address in addresses {
            if !tried.insert(address.clone()) {
                continue;
            }
            let result = backend.wire(config, &address);
            if let Some(path) = record(backend, Carrier::Wire, result, &mut refusals)? {
                return Ok(path);
            }
        }
    }
    let result = backend.punch(config);
    if let Some(path) = record(backend, Carrier::Direct, result, &mut refusals)? {
        return Ok(path);
    }
    let result = backend.relay(config);
    if let Some(path) = record(backend, Carrier::Relay, result, &mut refusals)? {
        return Ok(path);
    }
    let reason = format!("all_link_carriers_refused: {}", refusals.join("; "));
    backend.topology(None, None, Some(&reason))?;
    Err(OpenError(reason))
}

/// Opens each carrier once, in wire, direct, relay order.
/// # Errors
/// Every attempted carrier refused, or the configuration was invalid.
pub fn open<B: Backend>(
    config: OutboundLinkConfig,
    choice: ChoiceConfig,
    mut backend: B,
) -> Result<Opened<B>, OpenError> {
    if choice.crossing_deadline_ms == 0 {
        return Err(OpenError(
            "crossing_deadline_ms_must_be_positive".to_owned(),
        ));
    }
    if config.link_id.is_empty()
        || config
            .link_id
            .chars()
            .any(|character| character.is_whitespace() || character.is_control())
    {
        return Err(OpenError("invalid_link_id".to_owned()));
    }
    for subject in &config.exports {
        crate::auth_lys::SubjectBinding::new("wire".to_owned(), subject.clone(), subject.clone())
            .map_err(|error| OpenError(error.to_string()))?;
    }
    let path = select(&config, &mut backend)?;
    let interrupt = carriers::StopSlot::new(
        path.interrupt_handle()
            .or_else(|| backend.interrupt_handle()),
    );
    Ok(Opened {
        config,
        choice,
        backend,
        path: Some(path),
        timers: 0,
        interrupt,
    })
}