nativeview_engine/wake.rs
1//! Coalesced wake bridge implementing `std::task::Wake` for async app tasks and background
2//! network/pairing workers, with synchronized callback teardown so hosts can safely free wake
3//! callback contexts immediately after `clear_sink()` / `set_wake_callback(NULL)` / `destroy()`.
4
5use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6use std::sync::{Arc, RwLock};
7use std::task::{Wake, Waker};
8
9/// Shared callback invoked when a surface needs the host event loop to schedule a tick.
10///
11/// # Re-entrancy Contract
12/// Installed callbacks MUST be lightweight and strictly non-re-entrant (e.g. post a message or
13/// signal a semaphore to the host event loop). They MUST NOT synchronously invoke `set_sink`,
14/// `clear_sink`, `SurfaceRuntime::destroy`, or mutating runtime methods on the same thread.
15pub type WakeCallback = Arc<dyn Fn() + Send + Sync>;
16
17/// Coalesced cross-thread wake notifier shared by in-process async frontends (`ReactiveRuntimeApp`),
18/// background workers, and the C ABI `set_wake_callback` hook.
19///
20/// Multiple `trigger()` / `Waker::wake()` calls before [`Self::take_pending`] coalesce into a
21/// single host callback invocation so worker bursts never flood the UI event loop.
22///
23/// [`Self::clear_sink`] and [`Self::set_sink`] acquire the internal write lock before mutating
24/// the callback slot, blocking until any in-flight callback invocation on another thread finishes
25/// so host `ctx` pointers are never accessed after clearing or surface destruction.
26pub struct WakeBridge {
27 pending: AtomicBool,
28 defer_depth: AtomicUsize,
29 deferred_wake: AtomicBool,
30 sink: RwLock<Option<WakeCallback>>,
31}
32
33/// RAII deferral guard that postpones synchronous [`WakeCallback`] invocations while a surface
34/// write lock is held, flushing one coalesced wake strictly after the outermost guard drops.
35pub struct WakeDeferGuard<'a> {
36 bridge: &'a WakeBridge,
37}
38
39impl Drop for WakeDeferGuard<'_> {
40 fn drop(&mut self) {
41 if self.bridge.defer_depth.fetch_sub(1, Ordering::SeqCst) == 1
42 && !std::thread::panicking()
43 && self.bridge.deferred_wake.swap(false, Ordering::SeqCst)
44 && self.bridge.pending.load(Ordering::Acquire)
45 {
46 self.bridge.fire_sink();
47 }
48 }
49}
50
51/// RAII lifetime token paired with a [`Waker`] created by [`WakeBridge::detachable_waker`].
52///
53/// Dropping this token immediately disables the paired waker so zombie background futures belonging
54/// to a replaced or dropped [`crate::RuntimeApp`] can never wake the surface.
55pub struct WakeToken {
56 alive: Arc<AtomicBool>,
57}
58
59impl Drop for WakeToken {
60 fn drop(&mut self) {
61 self.alive.store(false, Ordering::Release);
62 }
63}
64
65struct DetachableWake {
66 bridge: Arc<WakeBridge>,
67 alive: Arc<AtomicBool>,
68}
69
70impl Wake for DetachableWake {
71 fn wake(self: Arc<Self>) {
72 self.wake_by_ref();
73 }
74
75 fn wake_by_ref(self: &Arc<Self>) {
76 if self.alive.load(Ordering::Acquire) {
77 self.bridge.trigger();
78 }
79 }
80}
81
82impl Default for WakeBridge {
83 fn default() -> Self {
84 Self::new()
85 }
86}
87
88impl WakeBridge {
89 pub fn new() -> Self {
90 let sink = RwLock::new(None);
91 // Prime OS rwlock storage eagerly so steady-state wakes allocate 0 bytes.
92 drop(sink.read());
93 Self {
94 pending: AtomicBool::new(false),
95 defer_depth: AtomicUsize::new(0),
96 deferred_wake: AtomicBool::new(false),
97 sink,
98 }
99 }
100
101 #[inline]
102 fn fire_sink(&self) {
103 let guard = self.sink.read().unwrap_or_else(|e| e.into_inner());
104 if let Some(ref cb) = *guard {
105 cb();
106 }
107 }
108
109 /// Defers synchronous sink invocations until the returned [`WakeDeferGuard`] is dropped
110 /// (typically declared *outside* a surface write lock so wakes flush after unlock).
111 #[inline]
112 pub fn defer_guard(&self) -> WakeDeferGuard<'_> {
113 self.defer_depth.fetch_add(1, Ordering::SeqCst);
114 WakeDeferGuard { bridge: self }
115 }
116
117 /// Creates a `std::task::Waker` backed directly by this `WakeBridge`.
118 pub fn waker(self: &Arc<Self>) -> Waker {
119 Waker::from(Arc::clone(self))
120 }
121
122 /// Creates a `std::task::Waker` gated by an RAII [`WakeToken`]; dropping the token renders
123 /// all clones of that waker silent no-ops while still coalescing directly through this single
124 /// `WakeBridge` while alive.
125 pub fn detachable_waker(self: &Arc<Self>) -> (Waker, WakeToken) {
126 let alive = Arc::new(AtomicBool::new(true));
127 let waker = Waker::from(Arc::new(DetachableWake {
128 bridge: Arc::clone(self),
129 alive: Arc::clone(&alive),
130 }));
131 (waker, WakeToken { alive })
132 }
133
134 /// Installs or replaces the host wake sink, waiting for any in-flight invocation of a prior
135 /// sink to return before replacing it (dropping any replaced sink *after* releasing the lock).
136 /// If a wake was already pending, invokes the installed sink once under the shared read lock
137 /// (or defers until any active [`Self::defer_guard`] exits).
138 pub fn set_sink(&self, cb: WakeCallback) {
139 let (replaced, fire_now) = {
140 let mut guard = self.sink.write().unwrap_or_else(|e| e.into_inner());
141 let old = guard.replace(cb);
142 (old, self.pending.load(Ordering::Acquire))
143 };
144 drop(replaced);
145 if fire_now {
146 if self.defer_depth.load(Ordering::SeqCst) > 0 {
147 self.deferred_wake.store(true, Ordering::SeqCst);
148 if self.defer_depth.load(Ordering::SeqCst) == 0
149 && self.deferred_wake.swap(false, Ordering::SeqCst)
150 && self.pending.load(Ordering::Acquire)
151 {
152 self.fire_sink();
153 }
154 } else {
155 self.fire_sink();
156 }
157 }
158 }
159
160 /// Installs or clears the host wake sink from an `Option<WakeCallback>`.
161 pub fn set_sink_opt(&self, cb: Option<WakeCallback>) {
162 match cb {
163 Some(sink) => self.set_sink(sink),
164 None => self.clear_sink(),
165 }
166 }
167
168 /// Clears the installed host wake sink, waiting for any in-flight callback invocation on
169 /// another thread to finish before returning (dropping the removed sink *after* unlocking).
170 pub fn clear_sink(&self) {
171 let removed = {
172 let mut guard = self.sink.write().unwrap_or_else(|e| e.into_inner());
173 guard.take()
174 };
175 drop(removed);
176 }
177
178 /// Marks the bridge dirty and fires the installed sink on the `false -> true` transition while
179 /// holding the shared read lock so `clear_sink()`/`destroy()` cannot free host callback state
180 /// mid-call. Defers sink invocation while any [`WakeDeferGuard`] is active.
181 pub fn trigger(&self) {
182 if !self.pending.swap(true, Ordering::SeqCst) {
183 if self.defer_depth.load(Ordering::SeqCst) > 0 {
184 self.deferred_wake.store(true, Ordering::SeqCst);
185 if self.defer_depth.load(Ordering::SeqCst) == 0
186 && self.deferred_wake.swap(false, Ordering::SeqCst)
187 && self.pending.load(Ordering::Acquire)
188 {
189 self.fire_sink();
190 }
191 } else {
192 self.fire_sink();
193 }
194 }
195 }
196
197 /// Returns whether a wake is currently pending without clearing the latch.
198 #[inline]
199 pub fn is_pending(&self) -> bool {
200 self.pending.load(Ordering::Acquire)
201 }
202
203 /// Clears and returns the coalesced pending flag after acquiring the surface write lock.
204 #[inline]
205 pub fn take_pending(&self) -> bool {
206 self.deferred_wake.store(false, Ordering::SeqCst);
207 self.pending.swap(false, Ordering::SeqCst)
208 }
209}
210
211/// An app's async-task waker: a [`WakeBridge::detachable_waker`] plus its bridge, re-targetable
212/// to the runtime's single bridge via [`Self::install`]. Every in-process app frontend
213/// (`ReactiveRuntimeApp`, `NvAppAdapter`) polls its tasks with [`Self::waker`], so a task woken
214/// off-dispatch (a timer, a fetch) triggers the host's frame request.
215pub struct AppWake {
216 // Declared FIRST so dropping an `AppWake` silences zombie wakers before anything else drops.
217 _token: WakeToken,
218 waker: Waker,
219 bridge: Arc<WakeBridge>,
220}
221
222impl AppWake {
223 pub fn new() -> Self {
224 let bridge = Arc::new(WakeBridge::new());
225 let (waker, _token) = bridge.detachable_waker();
226 Self { _token, waker, bridge }
227 }
228
229 #[inline]
230 pub fn waker(&self) -> &Waker {
231 &self.waker
232 }
233
234 #[inline]
235 pub fn bridge(&self) -> &Arc<WakeBridge> {
236 &self.bridge
237 }
238
239 /// Re-targets the waker onto `bridge` (the previous waker clones go silent). Returns whether
240 /// a wake was pending on the previous bridge; callers trigger the new bridge for it after
241 /// releasing any surface write lock.
242 pub fn install(&mut self, bridge: Arc<WakeBridge>) -> bool {
243 let had_pending = self.bridge.take_pending();
244 let (waker, token) = bridge.detachable_waker();
245 self._token = token;
246 self.waker = waker;
247 self.bridge = bridge;
248 had_pending
249 }
250}
251
252impl Default for AppWake {
253 fn default() -> Self {
254 Self::new()
255 }
256}
257
258impl Wake for WakeBridge {
259 fn wake(self: Arc<Self>) {
260 self.trigger();
261 }
262
263 fn wake_by_ref(self: &Arc<Self>) {
264 self.trigger();
265 }
266}