Skip to main content

nmbrs_tui/
display_sink.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! `DisplaySink` — uniform consumer interface for the run-state
5//! snapshot stream.
6//!
7//! ## Architecture
8//!
9//! The runtime publishes state through one canonical channel:
10//!
11//! ```text
12//!   RunObserver (lifecycle callbacks)
13//!         │
14//!         ▼ RunStateCmd
15//!   RunState actor (mpsc → ArcSwap<Arc<RunState>>)
16//!         │
17//!         ▼ snapshot() / mpsc::Receiver<MetricSet>
18//!   DisplaySink   ←──  the trait this module defines
19//! ```
20//!
21//! Every consumer that wants to render the live run — terminal
22//! TUI, line-mode "fake TUI" emulation, log-only stderr, future
23//! external dashboards, the inspector socket — implements this
24//! trait. The runtime stays oblivious to which sink is wired in;
25//! it only knows about the actor.
26//!
27//! Three impls are planned:
28//!
29//! | Impl                | Surface | Owns terminal? |
30//! |---------------------|---------|----------------|
31//! | `TuiSink` (Phase 2) | `app::App` raw-mode + alt-screen | **yes** |
32//! | `FakeTuiSink` (P2)  | line-mode emulation, stderr        | no |
33//! | `LogOnlySink`       | stderr line-stream (current `tui=off` shape) | no |
34//!
35//! Subsystems that *don't* consume the live stream (plotter,
36//! post-run summary reports — they read `metrics.db` after the
37//! run finishes) sit outside this trait. The trait is for
38//! live-stream consumers only.
39//!
40//! ## Lifecycle
41//!
42//! ```text
43//!   sink = SomeSink::new(inputs);
44//!   handle = sink.start();   // takes ownership; spawns thread(s)
45//!   // ... runtime fires events into the actor ...
46//!   handle.shutdown();        // graceful drain + teardown
47//! ```
48//!
49//! `shutdown` is the cooperative-stop signal; the sink thread
50//! flushes any pending buffered output, restores any terminal
51//! state it modified (raw mode, alt-screen), and exits. The
52//! returned thread join-handle on `start` lets the host wait for
53//! a clean teardown.
54//!
55//! ## Why a trait, not an enum
56//!
57//! - Each sink lives in its own file, with its own dependencies.
58//!   `TuiSink` needs `crossterm` + `ratatui`; `LogOnlySink`
59//!   doesn't.
60//! - Future external sinks (web dashboard, IPC bridge) can be
61//!   added without touching every existing impl.
62//! - The runner-side wiring code switches on `tui=` mode once at
63//!   startup and hands the trait object to a single executor —
64//!   one polymorphic dispatch on shutdown, none on the hot path.
65
66use std::sync::Arc;
67use std::sync::mpsc;
68
69use nmbrs_metrics::metrics_query::MetricsQuery;
70use nmbrs_metrics::snapshot::MetricSet;
71
72use crate::run_state_actor::RunStateHandle;
73
74/// Inputs every sink consumes. Cheap to construct: every field
75/// is either an `Arc` clone or an `mpsc::Receiver` (single-
76/// consumer, owned by the sink that takes it).
77///
78/// The two non-state fields are optional: a [`LogOnlySink`]
79/// that just renders log lines doesn't need either; the eventual
80/// [`crate::app::App`]-backed `TuiSink` and the future
81/// `FakeTuiSink` need both. `None` means "this sink doesn't
82/// consume frames / query the cadence store" — the runner-side
83/// wiring is responsible for not registering a reporter when no
84/// sink will drain it.
85///
86/// [`LogOnlySink`]: crate::log_only_sink::LogOnlySink
87pub struct DisplayInputs {
88    /// Read-only access to the actor's published `Arc<RunState>`.
89    /// Sinks load snapshots via `state.load()` on their own
90    /// schedule (TUI app polls at `tick_rate`; log-only sinks
91    /// poll on log-seq deltas).
92    pub state: RunStateHandle,
93    /// Base-cadence metrics frames from the cadence reporter.
94    /// `None` for sinks that don't render frames.
95    pub frame_rx: Option<mpsc::Receiver<MetricSet>>,
96    /// Cadence-windowed query handle. `None` for sinks that
97    /// don't render per-cadence views.
98    pub metrics_query: Option<Arc<MetricsQuery>>,
99}
100
101/// Sink for the run-state snapshot stream.
102///
103/// Implementors live on their own thread (or group of threads).
104/// The trait surface is intentionally tiny: construct, start,
105/// shut down. The runtime never reaches into the sink for
106/// per-event delivery — events flow through the actor; the sink
107/// drains.
108pub trait DisplaySink: Send {
109    /// Take ownership of the sink and spawn the rendering thread
110    /// (or threads). Returns the join handle so the runner can
111    /// wait on a clean teardown after `shutdown`. `inputs`
112    /// carries everything the sink needs to read state and
113    /// metrics — see [`DisplayInputs`].
114    fn start(self: Box<Self>, inputs: DisplayInputs) -> Box<dyn SinkHandle>;
115}
116
117/// Handle returned by [`DisplaySink::start`]. The runner uses it
118/// to signal shutdown and wait for the rendering thread to exit.
119/// Holding this handle alive keeps the thread running; dropping
120/// it without `shutdown` is a coding bug — the thread may leave
121/// the terminal in raw mode or fail to flush its output.
122pub trait SinkHandle: Send {
123    /// Cooperative stop. Returns when the sink's thread has
124    /// flushed its output and restored any terminal state it
125    /// modified. Idempotent: a second call after the thread has
126    /// already exited is a no-op.
127    fn shutdown(self: Box<Self>);
128
129    /// Whether this sink currently owns exclusive terminal access
130    /// (raw mode, alt-screen). Honest answer per impl:
131    /// `LogOnlySink` always returns `false`; `TuiSink` returns
132    /// `true` while the alt-screen is up. Used by the runner to
133    /// decide whether stdout reports (final summaries) should be
134    /// deferred until after the sink shuts down vs. printed live.
135    fn owns_terminal(&self) -> bool {
136        false
137    }
138}