astrs-node-api 0.1.0

The AstRS node API: handshake, typed pub/sub, zero-copy allocation and event streams.
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
//! The registration handshake (blueprint §7.3).
//!
//! ```text
//!   node                                       daemon
//!    ├──────── Hello / Welcome ─────────────────►│   (§7.2, astrs-transport)
//!    ├──────── Register(NodeHandshake) ─────────►│
//!    │◄─────── Registered { spec, session } ─────┤
//!    ├──────── Subscribe { inputs } ────────────►│
//!    │                                            │
//!    └──────── the pump starts here ─────────────┘
//! ```
//!
//! The handshake runs on the link *before* the reader task exists, because
//! everything after it depends on the specification `Registered` carries: a
//! `path: dynamic` node (§8.3) has no `ASTRS_NODE_CONFIG` at all and learns
//! its wiring here, and even a spawned one takes the daemon's word for its
//! generation over its own.
//!
//! # Events that arrive during the handshake
//!
//! A daemon may legitimately send an input the instant it accepts the
//! registration — it is under no obligation to wait for `Subscribe`. Those
//! frames are **buffered** here and replayed through the ordinary dispatcher
//! once the queues exist, so a message can be early but never lost.

use std::sync::Arc;
use std::time::Duration;

use astrs_wire::{
    DataId, DurationMs, NodeEvent, NodeHandshake, NodeRequest, NodeSpawnSpec, SessionId,
    WireMessage,
};
use tokio::sync::mpsc;

use crate::error::{NodeError, Result};
use crate::events::{EventSource, EventStream};
use crate::runtime::NodeRuntime;
use crate::session::connect::{LinkDuplex, NodeLink};
use crate::session::{OUTGOING_CAPACITY, SessionShared, pump};

/// How long the registration exchange waits for its answer.
pub const REGISTRATION_TIMEOUT: Duration = Duration::from_secs(10);

/// What the registration produced.
pub struct Registration {
    /// The shared session state.
    pub shared: Arc<SessionShared>,
    /// The node's event stream.
    pub events: EventStream,
    /// The running reader and writer tasks.
    pub tasks: pump::SessionTasks,
    /// The effective specification the daemon assigned.
    pub spec: Arc<NodeSpawnSpec>,
}

impl core::fmt::Debug for Registration {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Registration")
            .field("node", &self.spec.node)
            .field("generation", &self.spec.generation)
            .finish_non_exhaustive()
    }
}

/// Registers over an established link and starts the session.
///
/// # Errors
///
/// [`NodeError::Registration`] when the daemon refuses or answers with
/// something else, [`NodeError::Timeout`] when it does not answer at all, and
/// [`NodeError::Transport`] when the link fails mid-handshake.
pub async fn register(
    link: NodeLink,
    handshake: NodeHandshake,
    runtime: NodeRuntime,
    zero_copy_threshold: u64,
    subscribe_to: Vec<DataId>,
) -> Result<Registration> {
    register_with(
        link,
        handshake,
        runtime,
        zero_copy_threshold,
        subscribe_to,
        None,
    )
    .await
}

/// [`register`], told where the daemon's segment broker listens (§6.2).
///
/// The broker socket travels in [`astrs_wire::NodeConfig::shm_broker`], and it
/// is what turns a `RouteUpgrade` into a mapped segment on every platform —
/// see [`crate::session::routes::open_producer`]. Separate from [`register`]
/// so a caller that has no configuration blob (the in-process test harness)
/// keeps its shorter call.
///
/// # Errors
///
/// As [`register`].
pub async fn register_with(
    link: NodeLink,
    handshake: NodeHandshake,
    runtime: NodeRuntime,
    zero_copy_threshold: u64,
    subscribe_to: Vec<DataId>,
    shm_broker: Option<std::path::PathBuf>,
) -> Result<Registration> {
    let limits = link.session.frame_limits();
    let session_id = link.session.session_id;
    let mut duplex = link.duplex;

    duplex
        .send_message(&NodeRequest::Register(handshake))
        .await?;

    let (spec, session, deferred) = await_registered(&mut duplex, session_id).await?;
    let spec = Arc::new(spec);

    let source = Arc::new(EventSource::new());
    for input in &spec.inputs {
        source.register_input(input)?;
    }

    let (sender, receiver) = mpsc::channel(OUTGOING_CAPACITY);
    let shared = Arc::new(
        SessionShared::new(
            Arc::clone(&spec),
            session,
            sender,
            Arc::clone(&source),
            runtime.clone(),
            zero_copy_threshold,
            limits,
        )
        .with_shm_broker(shm_broker),
    );

    duplex
        .send_message(&NodeRequest::Subscribe {
            inputs: subscribe_to,
        })
        .await?;

    let (reader, writer) = duplex.into_halves();
    let tasks = pump::spawn(&shared, reader, writer, receiver);

    // A node that stops reading must stop the daemon queueing for it (§7.3),
    // and the only moment that is observable is when the stream is dropped.
    {
        let notify = Arc::clone(&shared);
        source.set_abandon_hook(Box::new(move || {
            let _ = notify.send_request(NodeRequest::EventStreamDropped);
        }));
    }

    // The other half of §11.3: a deadline violation `EventSource` measures
    // locally is always turned into a control-lane `Event::Error` (so the
    // node itself sees it even offline), but only a *connected* node can
    // relay it to the daemon for the `astrs/status` fan-out and the
    // registered metric — this is the one place a live session exists to
    // install that relay. `send_request` (not `_async`) matches
    // `EventStreamDropped` above: the hook itself has no `.await` point to
    // offer (its signature is a plain `Fn`, called synchronously from
    // inside `EventSource::finish_deadlines`, itself invoked from *both*
    // `SessionShared::send_request` and `send_request_async`'s publish
    // path), so the sync call is the only one it *can* make — safe from
    // either caller because `send_request` only ever blocks past
    // `NodeRuntime::block_on` when the outgoing channel is momentarily
    // full, and that call is what already makes blocking-from-async safe
    // throughout this crate: `tokio::task::block_in_place` on a
    // multi-threaded runtime, or a clean `NodeError::BlockingInAsync`
    // (never a panic) on a single-threaded one. And, exactly like a
    // dropped event stream, a relay that cannot be enqueued right now (the
    // daemon is gone, the outgoing channel is closed, or that
    // single-threaded-runtime error) is not a condition this node can act
    // on differently, so the error is intentionally discarded rather than
    // propagated out of a publish call that already succeeded on its own
    // terms.
    {
        let notify = Arc::clone(&shared);
        source.set_deadline_violation_hook(Box::new(move |input, budget, latency| {
            let _ = notify.send_request(NodeRequest::ReportDeadlineViolation {
                input,
                budget: DurationMs::from_duration(budget),
                latency: DurationMs::from_duration(latency),
            });
        }));
    }

    // Anything the daemon sent before the queues existed goes through the
    // ordinary dispatcher now, in arrival order.
    for event in deferred {
        pump::dispatch(&shared, event);
    }

    let events = EventStream::new(source, runtime);
    Ok(Registration {
        shared,
        events,
        tasks,
        spec,
    })
}

/// Reads frames until `Registered` arrives, buffering everything else.
async fn await_registered(
    duplex: &mut LinkDuplex,
    expected_session: SessionId,
) -> Result<(NodeSpawnSpec, SessionId, Vec<NodeEvent>)> {
    let mut deferred = Vec::new();
    let deadline = tokio::time::Instant::now() + REGISTRATION_TIMEOUT;
    loop {
        let frame = tokio::time::timeout_at(deadline, duplex.recv_frame())
            .await
            .map_err(|_| NodeError::Timeout {
                operation: "node registration",
                millis: as_millis(REGISTRATION_TIMEOUT),
            })??;
        let Some(frame) = frame else {
            return Err(NodeError::Registration(
                "the daemon closed the connection before answering the registration".to_owned(),
            ));
        };
        if frame.kind() != astrs_wire::FrameKind::NodeEvent {
            return Err(NodeError::Registration(format!(
                "the daemon answered a registration with a `{}` frame",
                frame.kind()
            )));
        }
        match NodeEvent::from_frame(&frame.as_view())? {
            NodeEvent::Registered { spec, session } => {
                if session != expected_session {
                    // Not fatal — the greeting's session and the
                    // registration's are allowed to differ if a daemon
                    // resumes — but worth carrying the daemon's answer, which
                    // is the authoritative one.
                }
                return Ok((*spec, session, deferred));
            }
            NodeEvent::Stop { cause, .. } => {
                return Err(NodeError::Registration(format!(
                    "the daemon stopped this node during registration: {cause}"
                )));
            }
            other => deferred.push(other),
        }
    }
}

/// Milliseconds, saturating rather than wrapping.
fn as_millis(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    use super::*;
    use crate::session::connect::wrap_stream;
    use astrs_wire::{
        DataflowId, FrameKind, FrameLimits, InputSpec, Metadata, NodeId, NodeSource, OutputPayload,
        PortRef, StopCause,
    };

    fn spec() -> NodeSpawnSpec {
        NodeSpawnSpec::new(
            DataflowId::from_u128(4),
            NodeId::new("detect").unwrap(),
            1,
            NodeSource::Dynamic,
        )
        .with_input(InputSpec::new(
            DataId::new("frames").unwrap(),
            PortRef::from_parts("camera", "image").unwrap(),
        ))
    }

    /// As [`spec`], but `frames` carries a 1ms deadline (§11.3) — short
    /// enough that an ordinary test-thread scheduling delay between the
    /// input arriving and the node's next publish reliably runs it over
    /// budget, without a test-visible sleep longer than a couple of
    /// milliseconds.
    fn spec_with_deadline() -> NodeSpawnSpec {
        NodeSpawnSpec::new(
            DataflowId::from_u128(4),
            NodeId::new("detect").unwrap(),
            1,
            NodeSource::Dynamic,
        )
        .with_input(InputSpec {
            deadline: Some(DurationMs::new(1)),
            ..InputSpec::new(
                DataId::new("frames").unwrap(),
                PortRef::from_parts("camera", "image").unwrap(),
            )
        })
    }

    fn link(io: tokio::io::DuplexStream) -> NodeLink {
        NodeLink {
            duplex: wrap_stream(io, FrameLimits::uds()),
            session: astrs_wire::NegotiatedSession {
                protocol: astrs_wire::PROTOCOL_VERSION,
                session_id: SessionId::from_u128(11),
                features: astrs_wire::FeatureFlags::EMPTY,
                limits: astrs_wire::NegotiatedLimits::uds(),
                role: astrs_wire::Role::Node,
                peer_version: astrs_wire::AstrsVersion::current(),
                resumed: false,
            },
            endpoint: "duplex".to_owned(),
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn the_registration_exchange_completes_and_starts_the_pump() {
        let (node_io, daemon_io) = tokio::io::duplex(64 * 1024);
        let mut daemon = wrap_stream(daemon_io, FrameLimits::uds());

        let daemon_task = tokio::spawn(async move {
            let request = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            assert!(matches!(request, NodeRequest::Register(_)));
            daemon
                .send_message(&NodeEvent::Registered {
                    spec: Box::new(spec()),
                    session: SessionId::from_u128(11),
                })
                .await
                .unwrap();
            let request = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            assert!(matches!(request, NodeRequest::Subscribe { .. }));
            daemon
                .send_message(&NodeEvent::Input {
                    id: DataId::new("frames").unwrap(),
                    source: PortRef::from_parts("camera", "image").unwrap(),
                    metadata: Metadata::default(),
                    payload: vec![1, 2],
                })
                .await
                .unwrap();
            daemon
        });

        let handshake =
            NodeHandshake::dynamic(DataflowId::from_u128(4), NodeId::new("detect").unwrap());
        let registration = register(
            link(node_io),
            handshake,
            NodeRuntime::acquire().unwrap(),
            4096,
            Vec::new(),
        )
        .await
        .unwrap();

        assert_eq!(registration.spec.generation, 1);
        assert_eq!(registration.spec.inputs.len(), 1);
        assert!(format!("{registration:?}").contains("detect"));

        let mut events = registration.events;
        let event = events
            .recv_async_timeout(Duration::from_secs(5))
            .await
            .unwrap();
        assert!(event.is_input());

        registration.shared.close();
        registration.tasks.abort();
        let _daemon = daemon_task.await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn events_that_arrive_before_registered_are_replayed_not_lost() {
        let (node_io, daemon_io) = tokio::io::duplex(64 * 1024);
        let mut daemon = wrap_stream(daemon_io, FrameLimits::uds());

        let daemon_task = tokio::spawn(async move {
            let _ = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            // An input *before* the registration answer.
            daemon
                .send_message(&NodeEvent::Input {
                    id: DataId::new("frames").unwrap(),
                    source: PortRef::from_parts("camera", "image").unwrap(),
                    metadata: Metadata::default(),
                    payload: vec![9],
                })
                .await
                .unwrap();
            daemon
                .send_message(&NodeEvent::Registered {
                    spec: Box::new(spec()),
                    session: SessionId::from_u128(11),
                })
                .await
                .unwrap();
            let _ = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            daemon
        });

        let registration = register(
            link(node_io),
            NodeHandshake::dynamic(DataflowId::from_u128(4), NodeId::new("detect").unwrap()),
            NodeRuntime::acquire().unwrap(),
            4096,
            Vec::new(),
        )
        .await
        .unwrap();

        let mut events = registration.events;
        let event = events
            .recv_async_timeout(Duration::from_secs(5))
            .await
            .unwrap();
        let Some((id, _, data)) = event.into_input() else {
            panic!("expected the replayed input");
        };
        assert_eq!(id.as_str(), "frames");
        assert_eq!(data.to_vec(), vec![9]);

        registration.shared.close();
        registration.tasks.abort();
        let _daemon = daemon_task.await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_stop_during_registration_is_reported() {
        let (node_io, daemon_io) = tokio::io::duplex(64 * 1024);
        let mut daemon = wrap_stream(daemon_io, FrameLimits::uds());
        let daemon_task = tokio::spawn(async move {
            let _ = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            daemon
                .send_message(&NodeEvent::Stop {
                    cause: StopCause::Destroyed,
                    grace: None,
                })
                .await
                .unwrap();
            daemon
        });

        let error = register(
            link(node_io),
            NodeHandshake::dynamic(DataflowId::from_u128(4), NodeId::new("detect").unwrap()),
            NodeRuntime::acquire().unwrap(),
            4096,
            Vec::new(),
        )
        .await
        .unwrap_err();
        assert!(matches!(error, NodeError::Registration(_)), "{error}");
        let _daemon = daemon_task.await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_daemon_that_hangs_up_is_reported() {
        let (node_io, daemon_io) = tokio::io::duplex(64 * 1024);
        drop(daemon_io);
        let error = register(
            link(node_io),
            NodeHandshake::dynamic(DataflowId::from_u128(4), NodeId::new("detect").unwrap()),
            NodeRuntime::acquire().unwrap(),
            4096,
            Vec::new(),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(error, NodeError::Registration(_) | NodeError::Transport(_)),
            "{error}"
        );
    }

    /// The production wiring this module's own `register_with` adds beside
    /// its abandon-hook install: a deadline violation `EventSource` measures
    /// locally must reach the daemon as [`NodeRequest::ReportDeadlineViolation`],
    /// not only the node's own control-lane `Event::Error` — see
    /// `EventSource`'s `DeadlineViolationHook` docs for the half this test
    /// does *not* cover (that local event is asserted directly in
    /// `astrs_node_api::events::source`'s own tests).
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_deadline_violation_is_relayed_to_the_daemon() {
        let (node_io, daemon_io) = tokio::io::duplex(64 * 1024);
        let mut daemon = wrap_stream(daemon_io, FrameLimits::uds());

        let daemon_task = tokio::spawn(async move {
            let request = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            assert!(matches!(request, NodeRequest::Register(_)));
            daemon
                .send_message(&NodeEvent::Registered {
                    spec: Box::new(spec_with_deadline()),
                    session: SessionId::from_u128(11),
                })
                .await
                .unwrap();
            let request = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            assert!(matches!(request, NodeRequest::Subscribe { .. }));
            daemon
                .send_message(&NodeEvent::Input {
                    id: DataId::new("frames").unwrap(),
                    source: PortRef::from_parts("camera", "image").unwrap(),
                    metadata: Metadata::default(),
                    payload: vec![1, 2],
                })
                .await
                .unwrap();

            // The node's simulated publish, which closes the open deadline
            // measurement — always sent first (`finish_deadlines` runs
            // synchronously *after* this request is already enqueued; see
            // `SessionShared::send_request`'s own docs).
            let request = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            assert!(matches!(request, NodeRequest::SendMessage { .. }));

            // The relay this test exists to prove: queued from inside the
            // `DeadlineViolationHook` this module's `register_with` installs,
            // strictly after the publish above on the same outgoing channel.
            let request = daemon
                .expect_message::<NodeRequest>(FrameKind::NodeRequest)
                .await
                .unwrap();
            match request {
                NodeRequest::ReportDeadlineViolation {
                    input,
                    budget,
                    latency,
                } => {
                    assert_eq!(input.as_str(), "frames");
                    assert_eq!(budget, DurationMs::new(1));
                    assert!(latency >= budget, "{latency:?} >= {budget:?}");
                }
                other => panic!("expected ReportDeadlineViolation, got {other:?}"),
            }
            daemon
        });

        let registration = register(
            link(node_io),
            NodeHandshake::dynamic(DataflowId::from_u128(4), NodeId::new("detect").unwrap()),
            NodeRuntime::acquire().unwrap(),
            4096,
            Vec::new(),
        )
        .await
        .unwrap();

        let mut events = registration.events;
        let event = events
            .recv_async_timeout(Duration::from_secs(5))
            .await
            .unwrap();
        assert!(event.is_input(), "opens the deadline measurement");

        // Comfortably past the 1ms budget, so the publish below is judged
        // late regardless of test-runner scheduling jitter.
        tokio::time::sleep(Duration::from_millis(20)).await;

        registration
            .shared
            .send_request(NodeRequest::SendMessage {
                output: DataId::new("boxes").unwrap(),
                metadata: Metadata::default(),
                payload: OutputPayload::inline(vec![0]),
            })
            .unwrap();

        // `send_request` only enqueues onto the outgoing channel — the
        // writer task still has to flush both the publish above and the
        // relay it triggers onto the duplex. Awaiting the daemon side (whose
        // own `expect_message` calls simply wait for those bytes to arrive)
        // before tearing the session down avoids racing `tasks.abort()`
        // against that still-in-flight write.
        let _daemon = daemon_task.await.unwrap();

        registration.shared.close();
        registration.tasks.abort();
    }
}