Skip to main content

serialplugin_core/hub/
stream.rs

1//! Delivery of the old watches (the plugin's Tauri `Channel`s, [`EventSink`] closures).
2//!
3//! Each watch is an [`EventStream`]: its sink and the events it has not got yet. Events are
4//! queued under the lock of the watch that produced them and delivered with no hub, manager
5//! or session lock held, one thread at a time per stream: the hub thread after it routed a
6//! chunk, or the caller of `unwatch` / `close` for the tail. A thread that finds a delivery
7//! in progress leaves its events to it; [`EventStream::settle`] then waits for them.
8//!
9//! [`watch_core`](crate::SerialManager::watch_core) streams do not come through here: their
10//! sink only pushes into a queue ([`crate::hub::delivery`]).
11
12// False positive on Android targets, whose `thread_local!` hides the `const` block.
13#![allow(clippy::missing_const_for_thread_local)]
14
15use crate::events::{EventSink, SerialEvent};
16use crate::sync_util::lock_or_recover;
17use std::cell::Cell;
18use std::collections::VecDeque;
19use std::panic::{catch_unwind, AssertUnwindSafe};
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::{Arc, Condvar, Mutex};
22
23thread_local! {
24    /// Sink calls on this thread's stack (any port, hub or CMUX session).
25    static SINK_DEPTH: Cell<usize> = const { Cell::new(0) };
26}
27
28/// This thread is inside a sink. It must not wait for another thread's delivery: that one
29/// may be waiting for this one (two sinks that unwatch or close each other).
30pub(crate) fn in_sink() -> bool {
31    SINK_DEPTH.with(Cell::get) > 0
32}
33
34/// Call `sink`; `None` when it panicked (caught: the thread it runs on is not its own).
35pub(crate) fn call_sink(sink: &EventSink, event: SerialEvent) -> Option<bool> {
36    SINK_DEPTH.with(|d| d.set(d.get() + 1));
37    let result = catch_unwind(AssertUnwindSafe(|| sink(event)));
38    SINK_DEPTH.with(|d| d.set(d.get() - 1));
39    if result.is_err() {
40        crate::log_warn!("serial event sink panicked; its stream ends");
41    }
42    result.ok()
43}
44
45/// One old watch: its sink and the events it has not got yet.
46pub(crate) struct EventStream {
47    sink: EventSink,
48    state: Mutex<StreamState>,
49    /// An event was delivered, or a delivery ended.
50    progress: Condvar,
51    /// The sink panicked.
52    gone: AtomicBool,
53}
54
55#[derive(Default)]
56struct StreamState {
57    queue: VecDeque<SerialEvent>,
58    delivering: bool,
59    queued: u64,
60    delivered: u64,
61    /// Nothing more is queued.
62    ended: bool,
63}
64
65impl StreamState {
66    fn push(&mut self, events: &mut Vec<SerialEvent>) {
67        if !self.ended {
68            self.queued += events.len() as u64;
69            self.queue.extend(events.drain(..));
70        }
71        events.clear();
72    }
73}
74
75impl EventStream {
76    pub(crate) fn gone(&self) -> bool {
77        self.gone.load(Ordering::SeqCst)
78    }
79
80    fn push(&self, events: &mut Vec<SerialEvent>) {
81        if !events.is_empty() {
82            lock_or_recover(&self.state).push(events);
83        }
84    }
85
86    /// Queue the last events.
87    fn end(&self, events: &mut Vec<SerialEvent>) {
88        let mut s = lock_or_recover(&self.state);
89        s.push(events);
90        s.ended = true;
91    }
92
93    /// Nothing left to deliver, now or later.
94    fn is_done(&self) -> bool {
95        let s = lock_or_recover(&self.state);
96        s.ended && s.queue.is_empty() && !s.delivering
97    }
98
99    /// Deliver what is queued now; all of it once the stream ended (a live stream's hub
100    /// may queue faster than the sink takes: its next pass delivers the rest).
101    fn deliver(&self) {
102        let mut s = lock_or_recover(&self.state);
103        if s.delivering {
104            return;
105        }
106        s.delivering = true;
107        let target = s.queued;
108        while s.ended || s.delivered < target {
109            let Some(event) = s.queue.pop_front() else {
110                break;
111            };
112            drop(s);
113            let result = call_sink(&self.sink, event);
114            if result == Some(false) {
115                crate::log_warn!("Failed to send serial event: receiver is gone");
116            }
117            s = lock_or_recover(&self.state);
118            s.delivered += 1;
119            if result.is_none() {
120                self.gone.store(true, Ordering::SeqCst);
121                s.ended = true;
122                s.delivered = s.queued;
123                s.queue.clear();
124            }
125            self.progress.notify_all();
126        }
127        s.delivering = false;
128        self.progress.notify_all();
129    }
130
131    /// What was queued before this call is delivered when it returns, by this thread or by
132    /// the one delivering now. Inside a sink it does not wait for another delivery.
133    pub(crate) fn settle(&self) {
134        let target = lock_or_recover(&self.state).queued;
135        loop {
136            self.deliver();
137            let s = lock_or_recover(&self.state);
138            if s.delivered >= target {
139                return;
140            }
141            if s.delivering {
142                if in_sink() {
143                    return;
144                }
145                drop(self.progress.wait(s));
146            }
147        }
148    }
149}
150
151/// The old watches of one hub (or one CMUX session) that may still have events to deliver.
152#[derive(Default)]
153pub struct Outbox {
154    streams: Mutex<Vec<Arc<EventStream>>>,
155}
156
157impl Outbox {
158    /// A stream for `sink`, delivered from here until it ended.
159    pub(crate) fn stream(&self, sink: EventSink) -> Arc<EventStream> {
160        let stream = Arc::new(EventStream {
161            sink,
162            state: Mutex::default(),
163            progress: Condvar::new(),
164            gone: AtomicBool::new(false),
165        });
166        lock_or_recover(&self.streams).push(stream.clone());
167        stream
168    }
169
170    /// Deliver queued events. Call with no lock held.
171    pub(crate) fn deliver(&self) {
172        let streams = lock_or_recover(&self.streams).clone();
173        for stream in &streams {
174            stream.deliver();
175        }
176        self.forget_done(&streams);
177    }
178
179    /// [`EventStream::settle`] of one stream. Call with no lock held.
180    pub(crate) fn settle(&self, stream: &Arc<EventStream>) {
181        stream.settle();
182        self.forget_done(std::slice::from_ref(stream));
183    }
184
185    /// [`EventStream::settle`] of every stream. Call with no lock held.
186    pub(crate) fn settle_all(&self) {
187        let streams = lock_or_recover(&self.streams).clone();
188        streams.iter().for_each(|s| s.settle());
189        self.forget_done(&streams);
190    }
191
192    fn forget_done(&self, streams: &[Arc<EventStream>]) {
193        for done in streams.iter().filter(|s| s.is_done()) {
194            lock_or_recover(&self.streams).retain(|s| !Arc::ptr_eq(s, done));
195        }
196    }
197}
198
199/// What owns an attached old watch: a hub, or a CMUX channel.
200pub(crate) trait WatchOwner: Send + Sync {
201    /// Detach `stream` (if still attached) with its tail queued, and settle it.
202    fn stop(&self, stream: &Arc<EventStream>);
203}
204
205/// Where the events of a watch go.
206pub(crate) enum Target {
207    Old(Arc<EventStream>),
208    /// `watch_core`: the sink only queues, so it is called at once.
209    Core {
210        sink: EventSink,
211        /// Cleared once the subscriber is gone.
212        alive: Arc<AtomicBool>,
213    },
214}
215
216impl Target {
217    pub(crate) fn is(&self, stream: &Arc<EventStream>) -> bool {
218        matches!(self, Target::Old(s) if Arc::ptr_eq(s, stream))
219    }
220
221    pub(crate) fn gone(&self) -> bool {
222        match self {
223            Target::Old(stream) => stream.gone(),
224            Target::Core { alive, .. } => !alive.load(Ordering::SeqCst),
225        }
226    }
227
228    /// Send `events` (emptied). Call under the watch's lock, so they go in production
229    /// order and none after its last.
230    pub(crate) fn send(&self, events: &mut Vec<SerialEvent>) {
231        match self {
232            Target::Old(stream) => stream.push(events),
233            Target::Core { sink, .. } => events.drain(..).for_each(|e| {
234                sink(e);
235            }),
236        }
237    }
238
239    /// [`Self::send`] the last events.
240    pub(crate) fn end(&self, events: &mut Vec<SerialEvent>) {
241        match self {
242            Target::Old(stream) => stream.end(events),
243            Target::Core { .. } => self.send(events),
244        }
245    }
246}