Skip to main content

hyperfile_reactor/
lib.rs

1//! A lightweight task execution framework built on top of Tokio's `LocalSet`.
2//!
3//! # Overview
4//!
5//! A [`Reactor`] owns a dedicated OS thread running a tokio `current_thread`
6//! runtime plus a [`LocalSet`]. Users register their own **typed tasks** on
7//! the reactor; each task listens on one or more **user-defined channels**,
8//! each with its own **priority** and **capacity**, and processes incoming
9//! contexts through a user-supplied handler. The dispatch policy is
10//! pluggable via the [`Scheduler`] trait; [`FairPriority`] (the default) and
11//! [`StrictPriority`] are provided.
12//!
13//! ```no_run
14//! use hyperfile_reactor::{Capacity, Reactor, Task, TaskBuilder};
15//!
16//! struct MyTask;
17//! impl Task<u64> for MyTask {
18//!     async fn handle(&mut self, ctx: u64) {
19//!         println!("got {ctx}");
20//!     }
21//! }
22//!
23//! let reactor = Reactor::<u64, MyTask>::new_current().unwrap();
24//!
25//! let mut builder = TaskBuilder::<u64>::new();
26//! let high = builder.add_channel(0, Capacity::Bounded(64));  // backpressured
27//! let low  = builder.add_channel(9, Capacity::Unbounded);
28//!
29//! let handler = reactor.spawn(MyTask, builder).expect("spawn");
30//! handler.send(high, 1).unwrap();
31//! handler.send(low,  2).unwrap();
32//! ```
33#![warn(missing_docs)]
34
35use std::marker::PhantomData;
36use std::sync::Arc;
37use std::thread::JoinHandle;
38
39use tokio::runtime::{Builder, Runtime};
40use tokio::sync::{mpsc, oneshot};
41use tokio::task::LocalSet;
42
43// ---------------------------------------------------------------------------
44// Errors
45// ---------------------------------------------------------------------------
46
47/// Returned when a send fails because the task has stopped.
48///
49/// The wrapped value is the context that could not be delivered, so the
50/// caller can recover ownership and retry, log, or discard it.
51#[derive(Debug)]
52pub struct SendError<T>(pub T);
53
54impl<T> SendError<T> {
55    /// Recover the context that could not be sent.
56    pub fn into_inner(self) -> T {
57        self.0
58    }
59}
60
61impl<T> std::fmt::Display for SendError<T> {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.write_str("task receiver closed")
64    }
65}
66
67impl<T: std::fmt::Debug> std::error::Error for SendError<T> {}
68
69/// Returned from non-blocking send paths: either the bounded channel is full
70/// or the task has stopped.
71///
72/// This enum is `#[non_exhaustive]`; callers must include a wildcard arm
73/// when matching to remain forward-compatible.
74#[derive(Debug)]
75#[non_exhaustive]
76pub enum TrySendError<T> {
77    /// Bounded channel currently full. The item is returned to the caller.
78    Full(T),
79    /// Receiver has been dropped / task has stopped.
80    Closed(T),
81}
82
83impl<T> TrySendError<T> {
84    /// Recover the context that could not be sent.
85    pub fn into_inner(self) -> T {
86        match self {
87            Self::Full(t) | Self::Closed(t) => t,
88        }
89    }
90}
91
92impl<T> std::fmt::Display for TrySendError<T> {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        match self {
95            Self::Full(_) => f.write_str("channel full"),
96            Self::Closed(_) => f.write_str("task receiver closed"),
97        }
98    }
99}
100
101impl<T: std::fmt::Debug> std::error::Error for TrySendError<T> {}
102
103/// Returned when spawning a task fails because the reactor thread is gone.
104#[derive(Debug)]
105pub struct SpawnError;
106
107impl std::fmt::Display for SpawnError {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.write_str("reactor background thread has shut down")
110    }
111}
112
113impl std::error::Error for SpawnError {}
114
115// ---------------------------------------------------------------------------
116// Task trait (business logic only)
117// ---------------------------------------------------------------------------
118
119/// Business-logic trait. Implemented by users for each task type.
120///
121/// The handler runs inside a single-threaded runtime. **Never block it.**
122/// Offload blocking or long-running IO via `tokio::task::spawn`,
123/// `spawn_blocking`, or similar.
124pub trait Task<Ctx>: 'static {
125    /// Process one context delivered through one of the task's channels.
126    ///
127    /// This is invoked sequentially by the scheduler loop on the reactor
128    /// thread; while it is `await`ing, no other context for this task is
129    /// processed. Keep the synchronous portion short, and detach
130    /// long-running async work via `tokio::task::spawn` rather than
131    /// awaiting it inline.
132    fn handle(&mut self, ctx: Ctx) -> impl std::future::Future<Output = ()>;
133}
134
135// ---------------------------------------------------------------------------
136// Capacity + DynSender / DynReceiver
137// ---------------------------------------------------------------------------
138
139/// Channel capacity policy.
140///
141/// `#[non_exhaustive]` so that adding new policies (e.g. bounded with an
142/// overflow strategy) in a future release is not a breaking change.
143#[derive(Clone, Copy, Debug)]
144#[non_exhaustive]
145pub enum Capacity {
146    /// Bounded channel; producers apply backpressure when full.
147    Bounded(usize),
148    /// Unbounded channel; producers never block, but producers can OOM the
149    /// consumer if they vastly outpace it.
150    Unbounded,
151}
152
153/// Internal unified sender.
154pub(crate) enum DynSender<T> {
155    Bounded(mpsc::Sender<T>),
156    Unbounded(mpsc::UnboundedSender<T>),
157}
158
159impl<T> Clone for DynSender<T> {
160    fn clone(&self) -> Self {
161        match self {
162            Self::Bounded(s) => Self::Bounded(s.clone()),
163            Self::Unbounded(s) => Self::Unbounded(s.clone()),
164        }
165    }
166}
167
168impl<T> DynSender<T> {
169    /// Non-blocking send. For bounded channels, returns `Full` if the queue
170    /// is full.
171    fn try_send(&self, value: T) -> Result<(), TrySendError<T>> {
172        match self {
173            Self::Bounded(s) => s.try_send(value).map_err(|e| match e {
174                mpsc::error::TrySendError::Full(v) => TrySendError::Full(v),
175                mpsc::error::TrySendError::Closed(v) => TrySendError::Closed(v),
176            }),
177            Self::Unbounded(s) => s.send(value).map_err(|e| TrySendError::Closed(e.0)),
178        }
179    }
180
181    /// Async send. Unbounded channels resolve immediately; bounded channels
182    /// await capacity.
183    async fn send_async(&self, value: T) -> Result<(), SendError<T>> {
184        match self {
185            Self::Bounded(s) => s.send(value).await.map_err(|e| SendError(e.0)),
186            Self::Unbounded(s) => s.send(value).map_err(|e| SendError(e.0)),
187        }
188    }
189}
190
191/// Internal unified receiver used by [`Scheduler`] implementations.
192///
193/// User code should treat this as opaque: only call [`try_recv`](Self::try_recv)
194/// or [`poll_recv`](Self::poll_recv). Both the enum and its variants are
195/// `#[non_exhaustive]`; new representations may be added without a major
196/// version bump, and external code may not construct or destructure them.
197#[non_exhaustive]
198pub enum DynReceiver<T> {
199    /// Wraps a bounded `tokio::sync::mpsc::Receiver`.
200    #[non_exhaustive]
201    Bounded(mpsc::Receiver<T>),
202    /// Wraps a `tokio::sync::mpsc::UnboundedReceiver`.
203    #[non_exhaustive]
204    Unbounded(mpsc::UnboundedReceiver<T>),
205}
206
207impl<T> DynReceiver<T> {
208    /// Non-blocking receive. Returns `Err(TryRecvError::Empty)` if no value
209    /// is ready; `Err(TryRecvError::Disconnected)` if all senders are gone.
210    pub fn try_recv(&mut self) -> Result<T, mpsc::error::TryRecvError> {
211        match self {
212            Self::Bounded(r) => r.try_recv(),
213            Self::Unbounded(r) => r.try_recv(),
214        }
215    }
216
217    /// Poll-based receive; mirrors `Receiver::poll_recv`.
218    pub fn poll_recv(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<T>> {
219        match self {
220            Self::Bounded(r) => r.poll_recv(cx),
221            Self::Unbounded(r) => r.poll_recv(cx),
222        }
223    }
224}
225
226fn make_channel<T>(cap: Capacity) -> (DynSender<T>, DynReceiver<T>) {
227    match cap {
228        Capacity::Bounded(n) => {
229            let (tx, rx) = mpsc::channel(n.max(1));
230            (DynSender::Bounded(tx), DynReceiver::Bounded(rx))
231        }
232        Capacity::Unbounded => {
233            let (tx, rx) = mpsc::unbounded_channel();
234            (DynSender::Unbounded(tx), DynReceiver::Unbounded(rx))
235        }
236    }
237}
238
239// ---------------------------------------------------------------------------
240// Channel token + TaskBuilder
241// ---------------------------------------------------------------------------
242
243/// An opaque token identifying one channel registered on a task.
244///
245/// Obtained from [`TaskBuilder::add_channel`] (or the `add_bounded` /
246/// `add_unbounded` convenience methods) and passed to
247/// [`TaskHandler::send`] / [`try_send`](TaskHandler::try_send) /
248/// [`send_async`](TaskHandler::send_async) to select which channel to
249/// produce on. Cheap to copy.
250pub struct Channel<Ctx> {
251    idx: usize,
252    _marker: PhantomData<fn(Ctx)>,
253}
254
255impl<Ctx> Clone for Channel<Ctx> {
256    fn clone(&self) -> Self {
257        *self
258    }
259}
260
261impl<Ctx> Copy for Channel<Ctx> {}
262
263impl<Ctx> std::fmt::Debug for Channel<Ctx> {
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        f.debug_struct("Channel").field("idx", &self.idx).finish()
266    }
267}
268
269#[derive(Clone, Copy, Debug)]
270struct ChannelSpec {
271    /// Lower value = higher priority. 0 is the highest.
272    priority: u8,
273    capacity: Capacity,
274}
275
276/// Declares the set of channels a task will receive on.
277///
278/// Build it up with [`add_channel`](Self::add_channel),
279/// [`add_unbounded`](Self::add_unbounded), or
280/// [`add_bounded`](Self::add_bounded), each of which returns a
281/// [`Channel`] token to hold onto. Then pass the builder to
282/// [`Reactor::spawn`](crate::Reactor::spawn) to start the task.
283pub struct TaskBuilder<Ctx> {
284    channels: Vec<ChannelSpec>,
285    _marker: PhantomData<fn(Ctx)>,
286}
287
288impl<Ctx> Default for TaskBuilder<Ctx> {
289    fn default() -> Self {
290        Self::new()
291    }
292}
293
294impl<Ctx> TaskBuilder<Ctx> {
295    /// Create an empty builder.
296    pub fn new() -> Self {
297        Self {
298            channels: Vec::new(),
299            _marker: PhantomData,
300        }
301    }
302
303    /// Register a channel with the given priority (0 = highest) and capacity.
304    ///
305    /// Multiple channels may share the same priority; among equals the
306    /// default scheduler visits them in registration order.
307    pub fn add_channel(&mut self, priority: u8, capacity: Capacity) -> Channel<Ctx> {
308        let idx = self.channels.len();
309        self.channels.push(ChannelSpec { priority, capacity });
310        Channel {
311            idx,
312            _marker: PhantomData,
313        }
314    }
315
316    /// Convenience: register an unbounded channel.
317    pub fn add_unbounded(&mut self, priority: u8) -> Channel<Ctx> {
318        self.add_channel(priority, Capacity::Unbounded)
319    }
320
321    /// Convenience: register a bounded channel with the given capacity.
322    pub fn add_bounded(&mut self, priority: u8, capacity: usize) -> Channel<Ctx> {
323        self.add_channel(priority, Capacity::Bounded(capacity))
324    }
325
326    /// Number of channels registered so far.
327    pub fn channel_count(&self) -> usize {
328        self.channels.len()
329    }
330}
331
332// ---------------------------------------------------------------------------
333// TaskHandler (producer side)
334// ---------------------------------------------------------------------------
335
336/// Producer-side handle. Cheap to clone; can be shared across threads.
337pub struct TaskHandler<Ctx> {
338    senders: Arc<[DynSender<Ctx>]>,
339}
340
341impl<Ctx> Clone for TaskHandler<Ctx> {
342    fn clone(&self) -> Self {
343        Self {
344            senders: self.senders.clone(),
345        }
346    }
347}
348
349impl<Ctx> TaskHandler<Ctx> {
350    /// Non-blocking send. On a bounded channel this returns `Full` when the
351    /// queue is at capacity; on an unbounded channel it is effectively
352    /// infallible except when the task has already stopped.
353    pub fn try_send(&self, ch: Channel<Ctx>, ctx: Ctx) -> Result<(), TrySendError<Ctx>> {
354        self.senders[ch.idx].try_send(ctx)
355    }
356
357    /// Convenience wrapper over [`try_send`](Self::try_send) that flattens
358    /// `Full` back into `Closed`-style errors. Use [`send_async`](Self::send_async)
359    /// when you want proper backpressure on bounded channels.
360    ///
361    /// For unbounded channels this is equivalent to `try_send`.
362    pub fn send(&self, ch: Channel<Ctx>, ctx: Ctx) -> Result<(), TrySendError<Ctx>> {
363        self.try_send(ch, ctx)
364    }
365
366    /// Async send with backpressure. On bounded channels this awaits free
367    /// capacity; on unbounded channels it resolves immediately.
368    pub async fn send_async(&self, ch: Channel<Ctx>, ctx: Ctx) -> Result<(), SendError<Ctx>> {
369        self.senders[ch.idx].send_async(ctx).await
370    }
371
372    /// Number of channels registered on this task.
373    pub fn channel_count(&self) -> usize {
374        self.senders.len()
375    }
376}
377
378// ---------------------------------------------------------------------------
379// Scheduler trait + built-in implementations
380// ---------------------------------------------------------------------------
381
382/// Pluggable dispatch policy.
383///
384/// Given the task's receivers and their priorities (parallel arrays, aligned
385/// by channel index), a scheduler decides which context to process next.
386/// Return `None` only when every receiver is closed and the task should
387/// terminate.
388pub trait Scheduler<Ctx>: Send + 'static {
389    /// Pick the next context to process.
390    ///
391    /// `rxs` and `priorities` are parallel arrays aligned by channel index
392    /// (registration order on the [`TaskBuilder`]). Implementations should
393    /// not assume any ordering between the two; the priorities slice is
394    /// read-only metadata.
395    ///
396    /// Returning `None` signals that every receiver is permanently closed
397    /// and the task's scheduler loop should exit.
398    fn next_ctx<'a>(
399        &'a mut self,
400        rxs: &'a mut [DynReceiver<Ctx>],
401        priorities: &'a [u8],
402    ) -> impl std::future::Future<Output = Option<Ctx>> + 'a;
403}
404
405/// Strict priority: always serve the highest-priority non-empty channel.
406/// Lower-priority channels may starve if higher ones never drain.
407#[derive(Clone, Copy, Debug, Default)]
408pub struct StrictPriority;
409
410impl<Ctx> Scheduler<Ctx> for StrictPriority {
411    async fn next_ctx<'a>(
412        &'a mut self,
413        rxs: &'a mut [DynReceiver<Ctx>],
414        priorities: &'a [u8],
415    ) -> Option<Ctx> {
416        let order = sort_order(priorities);
417
418        // Non-blocking scan.
419        if let Some(v) = try_recv_in_order(rxs, &order) {
420            return Some(v);
421        }
422        // Block until something arrives.
423        await_any(rxs, &order).await.map(|(v, _)| v)
424    }
425}
426
427/// Strict priority with anti-starvation: after `budget` consecutive items
428/// from the top-priority band, serve one item from the lowest non-empty
429/// band if any is waiting.
430///
431/// The default ([`FairPriority::default`]) uses `budget = 16`, which is a
432/// reasonable middle ground for most workloads. Lower the budget if your
433/// low-priority work is latency-sensitive; raise it if high-priority
434/// throughput dominates.
435#[derive(Clone, Copy, Debug)]
436pub struct FairPriority {
437    budget: u32,
438    top_streak: u32,
439}
440
441impl FairPriority {
442    /// Build a fair-priority scheduler with the given anti-starvation
443    /// budget. After `budget` consecutive top-priority items, one
444    /// lower-priority item is served (if any is waiting).
445    pub fn new(budget: u32) -> Self {
446        Self {
447            budget,
448            top_streak: 0,
449        }
450    }
451
452    /// Read back the configured budget.
453    pub fn budget(&self) -> u32 {
454        self.budget
455    }
456}
457
458impl Default for FairPriority {
459    fn default() -> Self {
460        Self::new(16)
461    }
462}
463
464impl<Ctx> Scheduler<Ctx> for FairPriority {
465    async fn next_ctx<'a>(
466        &'a mut self,
467        rxs: &'a mut [DynReceiver<Ctx>],
468        priorities: &'a [u8],
469    ) -> Option<Ctx> {
470        let order = sort_order(priorities);
471        if order.is_empty() {
472            return None;
473        }
474        let top_idx = order[0];
475
476        // 1) Starvation relief.
477        if self.top_streak >= self.budget {
478            self.top_streak = 0;
479            if let Some(v) = try_recv_lowest_nonempty(rxs, &order) {
480                return Some(v);
481            }
482            // nothing below waiting; fall through
483        }
484
485        // 2) Non-blocking priority scan.
486        if let Some((v, idx)) = try_recv_in_order_tagged(rxs, &order) {
487            self.top_streak = if idx == top_idx {
488                self.top_streak.saturating_add(1)
489            } else {
490                0
491            };
492            return Some(v);
493        }
494
495        // 3) Await any; track top-streak.
496        match await_any(rxs, &order).await {
497            Some((v, is_top)) => {
498                self.top_streak = if is_top {
499                    self.top_streak.saturating_add(1)
500                } else {
501                    0
502                };
503                Some(v)
504            }
505            None => None,
506        }
507    }
508}
509
510// --- shared scheduler helpers ---
511
512/// Return indices 0..N sorted by ascending priority value (stable).
513fn sort_order(priorities: &[u8]) -> Vec<usize> {
514    let mut order: Vec<usize> = (0..priorities.len()).collect();
515    order.sort_by_key(|&i| priorities[i]);
516    order
517}
518
519fn try_recv_in_order<Ctx>(rxs: &mut [DynReceiver<Ctx>], order: &[usize]) -> Option<Ctx> {
520    for &idx in order {
521        if let Ok(v) = rxs[idx].try_recv() {
522            return Some(v);
523        }
524    }
525    None
526}
527
528fn try_recv_in_order_tagged<Ctx>(
529    rxs: &mut [DynReceiver<Ctx>],
530    order: &[usize],
531) -> Option<(Ctx, usize)> {
532    for &idx in order {
533        if let Ok(v) = rxs[idx].try_recv() {
534            return Some((v, idx));
535        }
536    }
537    None
538}
539
540fn try_recv_lowest_nonempty<Ctx>(rxs: &mut [DynReceiver<Ctx>], order: &[usize]) -> Option<Ctx> {
541    for &idx in order.iter().rev() {
542        if let Ok(v) = rxs[idx].try_recv() {
543            return Some(v);
544        }
545    }
546    None
547}
548
549async fn await_any<Ctx>(rxs: &mut [DynReceiver<Ctx>], order: &[usize]) -> Option<(Ctx, bool)> {
550    use std::future::poll_fn;
551    use std::task::Poll;
552
553    if order.is_empty() {
554        return None;
555    }
556    let top = order[0];
557
558    poll_fn(|cx| {
559        let mut all_closed = true;
560        for &idx in order {
561            match rxs[idx].poll_recv(cx) {
562                Poll::Ready(Some(v)) => return Poll::Ready(Some((v, idx == top))),
563                Poll::Ready(None) => { /* closed; keep scanning */ }
564                Poll::Pending => all_closed = false,
565            }
566        }
567        if all_closed {
568            Poll::Ready(None)
569        } else {
570            Poll::Pending
571        }
572    })
573    .await
574}
575
576// ---------------------------------------------------------------------------
577// Reactor (owns the background thread)
578// ---------------------------------------------------------------------------
579
580type SpawnRequest = Box<dyn FnOnce() + Send>;
581
582/// Owns the background thread running the tokio runtime + `LocalSet`.
583///
584/// # Shutdown
585///
586/// Dropping the reactor (or calling [`shutdown`](Self::shutdown)) closes the
587/// spawn control channel and joins the background thread. **The background
588/// thread only exits once every [`TaskHandler`] clone has been dropped.**
589/// If producers are still alive, `Drop`/`shutdown` will block.
590pub struct Reactor<Ctx, T> {
591    ctrl: Option<mpsc::UnboundedSender<SpawnRequest>>,
592    thread: Option<JoinHandle<()>>,
593    _marker: PhantomData<fn(Ctx, T)>,
594}
595
596impl<Ctx, T> Reactor<Ctx, T>
597where
598    Ctx: Send + 'static,
599    T: Task<Ctx> + Send + 'static,
600{
601    /// Build a reactor on a freshly created `current_thread` runtime.
602    pub fn new_current() -> std::io::Result<Self> {
603        Self::new(None)
604    }
605
606    /// Build a reactor. Supply `Some(rt)` to reuse an existing runtime.
607    pub fn new(runtime: Option<Arc<Runtime>>) -> std::io::Result<Self> {
608        let (ctrl_tx, mut ctrl_rx) = mpsc::unbounded_channel::<SpawnRequest>();
609
610        let rt = match runtime {
611            Some(r) => r,
612            None => Arc::new(Builder::new_current_thread().enable_all().build()?),
613        };
614
615        let thread = std::thread::Builder::new()
616            .name("hyperfile-reactor".into())
617            .spawn(move || {
618                let local = LocalSet::new();
619
620                local.spawn_local(async move {
621                    while let Some(req) = ctrl_rx.recv().await {
622                        req();
623                    }
624                });
625
626                rt.block_on(local);
627            })?;
628
629        Ok(Self {
630            ctrl: Some(ctrl_tx),
631            thread: Some(thread),
632            _marker: PhantomData,
633        })
634    }
635
636    /// Spawn a task using the default scheduler ([`FairPriority`] with
637    /// budget 16).
638    ///
639    /// Blocks the current thread until the task has been started. **Do not
640    /// call this from inside a tokio runtime**; use [`spawn_async`](Self::spawn_async)
641    /// instead.
642    pub fn spawn(
643        &self,
644        task: T,
645        builder: TaskBuilder<Ctx>,
646    ) -> Result<TaskHandler<Ctx>, SpawnError> {
647        self.spawn_with(task, builder, FairPriority::default())
648    }
649
650    /// Spawn a task with a user-supplied scheduler (blocking).
651    pub fn spawn_with<S>(
652        &self,
653        task: T,
654        builder: TaskBuilder<Ctx>,
655        scheduler: S,
656    ) -> Result<TaskHandler<Ctx>, SpawnError>
657    where
658        S: Scheduler<Ctx>,
659    {
660        let rx = self.submit(task, builder, scheduler)?;
661        rx.blocking_recv().map_err(|_| SpawnError)
662    }
663
664    /// Async version of [`spawn`](Self::spawn). Use this from inside a
665    /// tokio runtime.
666    pub async fn spawn_async(
667        &self,
668        task: T,
669        builder: TaskBuilder<Ctx>,
670    ) -> Result<TaskHandler<Ctx>, SpawnError> {
671        self.spawn_with_async(task, builder, FairPriority::default())
672            .await
673    }
674
675    /// Async version of [`spawn_with`](Self::spawn_with).
676    pub async fn spawn_with_async<S>(
677        &self,
678        task: T,
679        builder: TaskBuilder<Ctx>,
680        scheduler: S,
681    ) -> Result<TaskHandler<Ctx>, SpawnError>
682    where
683        S: Scheduler<Ctx>,
684    {
685        let rx = self.submit(task, builder, scheduler)?;
686        rx.await.map_err(|_| SpawnError)
687    }
688
689    /// Shared internals: build the spawn request, push it onto the reactor
690    /// control channel, return the oneshot receiver.
691    fn submit<S>(
692        &self,
693        task: T,
694        builder: TaskBuilder<Ctx>,
695        scheduler: S,
696    ) -> Result<oneshot::Receiver<TaskHandler<Ctx>>, SpawnError>
697    where
698        S: Scheduler<Ctx>,
699    {
700        let ctrl = self.ctrl.as_ref().ok_or(SpawnError)?;
701        let (tx, rx) = oneshot::channel::<TaskHandler<Ctx>>();
702
703        let req: SpawnRequest = Box::new(move || {
704            let handler = start_task(task, builder, scheduler);
705            let _ = tx.send(handler);
706        });
707
708        ctrl.send(req).map_err(|_| SpawnError)?;
709        Ok(rx)
710    }
711
712    /// Close the control channel and join the background thread.
713    pub fn shutdown(mut self) -> std::thread::Result<()> {
714        drop(self.ctrl.take());
715        if let Some(h) = self.thread.take() {
716            h.join()
717        } else {
718            Ok(())
719        }
720    }
721}
722
723impl<Ctx, T> Drop for Reactor<Ctx, T> {
724    fn drop(&mut self) {
725        drop(self.ctrl.take());
726        if let Some(h) = self.thread.take() {
727            let _ = h.join();
728        }
729    }
730}
731
732// ---------------------------------------------------------------------------
733// start_task: create channels + spawn scheduler loop
734// ---------------------------------------------------------------------------
735
736fn start_task<Ctx, T, S>(
737    mut task: T,
738    builder: TaskBuilder<Ctx>,
739    mut scheduler: S,
740) -> TaskHandler<Ctx>
741where
742    Ctx: Send + 'static,
743    T: Task<Ctx> + 'static,
744    S: Scheduler<Ctx>,
745{
746    let cap_hint = builder.channels.len().max(1);
747    let mut senders: Vec<DynSender<Ctx>> = Vec::with_capacity(cap_hint);
748    let mut receivers: Vec<DynReceiver<Ctx>> = Vec::with_capacity(cap_hint);
749    let mut priorities: Vec<u8> = Vec::with_capacity(cap_hint);
750
751    if builder.channels.is_empty() {
752        // Degenerate case: create a single unbounded channel so the handler
753        // is usable.
754        let (tx, rx) = make_channel::<Ctx>(Capacity::Unbounded);
755        senders.push(tx);
756        receivers.push(rx);
757        priorities.push(0);
758    } else {
759        for spec in &builder.channels {
760            let (tx, rx) = make_channel::<Ctx>(spec.capacity);
761            senders.push(tx);
762            receivers.push(rx);
763            priorities.push(spec.priority);
764        }
765    }
766
767    let handler = TaskHandler {
768        senders: senders.into(),
769    };
770
771    tokio::task::spawn_local(async move {
772        while let Some(ctx) = scheduler.next_ctx(&mut receivers, &priorities).await {
773            task.handle(ctx).await;
774            // Cooperatively yield to the runtime after each item.
775            //
776            // The scheduler's non-blocking `try_recv` fast path bypasses
777            // tokio's coop budget; so does an `async fn handle` whose body
778            // never reaches an `.await` point. Without this nudge, a
779            // handler that synchronously re-queues onto a channel
780            // (e.g. `ResourceBusy => send_cb(ctx); return;`) would drive
781            // the scheduler in a tight loop and starve the runtime's I/O
782            // and timer drivers, including any `tokio::task::spawn`'d
783            // futures that the handler itself launched.
784            //
785            // `consume_budget().await` decrements the task-local coop
786            // budget; when exhausted (after ~128 iterations by default)
787            // it returns Pending, returning control to the runtime so it
788            // can drive timers / I/O before re-polling.
789            tokio::task::consume_budget().await;
790        }
791    });
792
793    handler
794}
795
796// ---------------------------------------------------------------------------
797// Tests
798// ---------------------------------------------------------------------------
799
800#[cfg(test)]
801mod tests {
802    use super::*;
803    use std::sync::Mutex;
804    use std::time::Duration;
805
806    /// Drive the reactor with a gated task so all messages get enqueued
807    /// before the scheduler sees any.
808    fn run_with_gate<S>(channels: Vec<(u8, Capacity, Vec<u32>)>, scheduler: S) -> Vec<u32>
809    where
810        S: Scheduler<u32>,
811    {
812        use tokio::sync::Notify;
813
814        let log = Arc::new(Mutex::new(Vec::<u32>::new()));
815
816        struct Gated {
817            log: Arc<Mutex<Vec<u32>>>,
818            gate: Arc<Notify>,
819            gate_passed: bool,
820        }
821
822        impl Task<u32> for Gated {
823            async fn handle(&mut self, ctx: u32) {
824                if !self.gate_passed {
825                    self.gate.notified().await;
826                    self.gate_passed = true;
827                }
828                self.log.lock().unwrap().push(ctx);
829            }
830        }
831
832        let gate = Arc::new(Notify::new());
833        let task = Gated {
834            log: log.clone(),
835            gate: gate.clone(),
836            gate_passed: false,
837        };
838
839        let reactor = Reactor::<u32, Gated>::new_current().unwrap();
840
841        let mut builder = TaskBuilder::<u32>::new();
842        let tokens: Vec<Channel<u32>> = channels
843            .iter()
844            .map(|(prio, cap, _)| builder.add_channel(*prio, *cap))
845            .collect();
846
847        let handler = reactor.spawn_with(task, builder, scheduler).unwrap();
848
849        // Dummy sentinel on first channel to force scheduler into the gate.
850        handler.send(tokens[0], u32::MAX).unwrap();
851        std::thread::sleep(Duration::from_millis(50));
852
853        for (i, (_prio, _cap, msgs)) in channels.iter().enumerate() {
854            for m in msgs {
855                handler.send(tokens[i], *m).unwrap();
856            }
857        }
858
859        gate.notify_one();
860
861        let expected: usize = 1 + channels.iter().map(|(_, _, m)| m.len()).sum::<usize>();
862        let deadline = std::time::Instant::now() + Duration::from_secs(5);
863        loop {
864            if log.lock().unwrap().len() >= expected {
865                break;
866            }
867            if std::time::Instant::now() >= deadline {
868                panic!(
869                    "timeout: got {} / {} items",
870                    log.lock().unwrap().len(),
871                    expected
872                );
873            }
874            std::thread::sleep(Duration::from_millis(10));
875        }
876
877        drop(handler);
878        reactor.shutdown().unwrap();
879
880        let mut recorded = log.lock().unwrap().clone();
881        assert_eq!(recorded.remove(0), u32::MAX);
882        recorded
883    }
884
885    #[test]
886    fn fair_priority_order_default() {
887        let result = run_with_gate(
888            vec![
889                (0, Capacity::Unbounded, vec![10, 11, 12]),
890                (1, Capacity::Unbounded, vec![20, 21, 22]),
891                (2, Capacity::Unbounded, vec![30, 31, 32]),
892            ],
893            FairPriority::default(),
894        );
895        assert_eq!(result, vec![10, 11, 12, 20, 21, 22, 30, 31, 32]);
896    }
897
898    #[test]
899    fn strict_priority_scheduler() {
900        let result = run_with_gate(
901            vec![
902                (0, Capacity::Unbounded, (0..50).collect()),
903                (2, Capacity::Unbounded, vec![999]),
904            ],
905            StrictPriority,
906        );
907
908        // StrictPriority: all 50 high-prio items come out before the low one.
909        let pos = result.iter().position(|&v| v == 999).unwrap();
910        assert_eq!(pos, 50, "low-prio must come last under StrictPriority");
911    }
912
913    #[test]
914    fn fair_priority_anti_starvation() {
915        let high: Vec<u32> = (0..40).map(|i| 1000 + i).collect();
916        let low = vec![9999_u32];
917
918        let result = run_with_gate(
919            vec![
920                (0, Capacity::Unbounded, high.clone()),
921                (2, Capacity::Unbounded, low),
922            ],
923            FairPriority::new(16),
924        );
925
926        let pos = result.iter().position(|&v| v == 9999).unwrap();
927        assert!(
928            pos <= 16,
929            "FairPriority must relieve starvation within budget: pos={pos}"
930        );
931
932        let highs: Vec<u32> = result.iter().copied().filter(|&v| v != 9999).collect();
933        let mut sorted = highs.clone();
934        sorted.sort();
935        assert_eq!(sorted, high);
936    }
937
938    #[test]
939    fn bounded_channel_applies_backpressure() {
940        // Bounded(1) channel. The consumer blocks on the *first* item only;
941        // that leaves the pipeline with:
942        //   - 1 item in-flight (held by the handler, awaiting release)
943        //   - 1 item buffered (capacity = 1)
944        // A further `try_send` must then return `Full`.
945        use tokio::sync::Notify;
946
947        struct Slow {
948            release: Arc<Notify>,
949            blocked_once: bool,
950        }
951        impl Task<u32> for Slow {
952            async fn handle(&mut self, _ctx: u32) {
953                if !self.blocked_once {
954                    self.blocked_once = true;
955                    self.release.notified().await;
956                }
957            }
958        }
959
960        let release = Arc::new(Notify::new());
961        let reactor = Reactor::<u32, Slow>::new_current().unwrap();
962        let mut builder = TaskBuilder::<u32>::new();
963        let ch = builder.add_bounded(0, 1);
964        let handler = reactor
965            .spawn(
966                Slow {
967                    release: release.clone(),
968                    blocked_once: false,
969                },
970                builder,
971            )
972            .unwrap();
973
974        // Consumer picks up item 1 and blocks on `notified`.
975        handler.try_send(ch, 1).expect("send 1");
976        std::thread::sleep(Duration::from_millis(100));
977
978        // Fill the 1-slot buffer.
979        handler.try_send(ch, 2).expect("send 2 fills buffer");
980        // Now Full.
981        match handler.try_send(ch, 3) {
982            Err(TrySendError::Full(3)) => { /* expected */ }
983            other => panic!("expected Full(3), got {:?}", other.map(|_| ())),
984        }
985
986        // Release the consumer; subsequent items process instantly.
987        release.notify_one();
988        drop(handler);
989        reactor.shutdown().expect("shutdown");
990    }
991
992    #[tokio::test(flavor = "current_thread")]
993    async fn send_async_awaits_capacity() {
994        // Reactor on its own thread, task that processes each item after a
995        // small sleep. A bounded(1) channel; producer uses send_async to
996        // push 5 items, which should all land eventually.
997        struct Trickle {
998            log: Arc<Mutex<Vec<u32>>>,
999        }
1000        impl Task<u32> for Trickle {
1001            async fn handle(&mut self, ctx: u32) {
1002                tokio::time::sleep(Duration::from_millis(20)).await;
1003                self.log.lock().unwrap().push(ctx);
1004            }
1005        }
1006
1007        let log = Arc::new(Mutex::new(Vec::<u32>::new()));
1008        let reactor = Reactor::<u32, Trickle>::new_current().unwrap();
1009        let mut builder = TaskBuilder::<u32>::new();
1010        let ch = builder.add_bounded(0, 1);
1011        // Use the async spawn variant since we're inside a tokio runtime.
1012        let handler = reactor
1013            .spawn_async(Trickle { log: log.clone() }, builder)
1014            .await
1015            .unwrap();
1016
1017        for i in 0..5u32 {
1018            handler.send_async(ch, i).await.unwrap();
1019        }
1020
1021        // Wait for the task to drain.
1022        let deadline = std::time::Instant::now() + Duration::from_secs(2);
1023        loop {
1024            if log.lock().unwrap().len() == 5 {
1025                break;
1026            }
1027            if std::time::Instant::now() >= deadline {
1028                panic!("didn't drain in time");
1029            }
1030            tokio::time::sleep(Duration::from_millis(10)).await;
1031        }
1032
1033        assert_eq!(*log.lock().unwrap(), vec![0, 1, 2, 3, 4]);
1034        drop(handler);
1035        // Move the blocking shutdown to a blocking thread to avoid
1036        // stalling the current-thread runtime.
1037        tokio::task::spawn_blocking(move || reactor.shutdown().unwrap())
1038            .await
1039            .unwrap();
1040    }
1041
1042    #[test]
1043    fn shutdown_is_clean() {
1044        struct Noop;
1045        impl Task<()> for Noop {
1046            async fn handle(&mut self, _ctx: ()) {}
1047        }
1048
1049        let reactor = Reactor::<(), Noop>::new_current().unwrap();
1050        let mut builder = TaskBuilder::<()>::new();
1051        let ch = builder.add_unbounded(0);
1052        let handler = reactor.spawn(Noop, builder).unwrap();
1053
1054        for _ in 0..10 {
1055            handler.send(ch, ()).unwrap();
1056        }
1057
1058        drop(handler);
1059        reactor.shutdown().expect("shutdown clean");
1060    }
1061
1062    /// Regression test for the I/O/timer-starvation bug fixed by adding
1063    /// `consume_budget` to the scheduler loop.
1064    ///
1065    /// A handler that synchronously re-queues onto the same channel used
1066    /// to drive the scheduler in a tight loop, preventing the reactor
1067    /// thread's tokio runtime from polling sibling tasks (e.g. timers
1068    /// spawned via `tokio::task::spawn`). Here we ensure a 100 ms
1069    /// `tokio::time::sleep` spawned from within `handle` actually fires
1070    /// even while the scheduler is otherwise looping on a re-queued
1071    /// context.
1072    #[test]
1073    fn handler_resubmit_does_not_starve_spawned_timer() {
1074        use tokio::sync::Notify;
1075
1076        enum Msg {
1077            /// Hand the worker its own producer + channel token.
1078            Init {
1079                handler: TaskHandler<Msg>,
1080                ch: Channel<Msg>,
1081            },
1082            /// Kicks the loop and arms the timer once.
1083            Start,
1084            /// Re-queued by the handler on every iteration.
1085            Retry,
1086            /// Sent by the spawned timer; releases the watchdog.
1087            Done,
1088        }
1089
1090        struct Worker {
1091            handler: Option<TaskHandler<Msg>>,
1092            ch: Option<Channel<Msg>>,
1093            armed: bool,
1094            done: Arc<Notify>,
1095        }
1096
1097        impl Task<Msg> for Worker {
1098            async fn handle(&mut self, msg: Msg) {
1099                match msg {
1100                    Msg::Init { handler, ch } => {
1101                        self.handler = Some(handler);
1102                        self.ch = Some(ch);
1103                    }
1104                    Msg::Start => {
1105                        let h = self.handler.clone().unwrap();
1106                        let ch = self.ch.unwrap();
1107                        if !self.armed {
1108                            self.armed = true;
1109                            let h_for_timer = h.clone();
1110                            tokio::task::spawn(async move {
1111                                tokio::time::sleep(Duration::from_millis(100)).await;
1112                                let _ = h_for_timer.send(ch, Msg::Done);
1113                            });
1114                        }
1115                        let _ = h.send(ch, Msg::Retry);
1116                    }
1117                    Msg::Retry => {
1118                        let h = self.handler.as_ref().unwrap();
1119                        let ch = self.ch.unwrap();
1120                        let _ = h.send(ch, Msg::Retry);
1121                    }
1122                    Msg::Done => {
1123                        self.done.notify_one();
1124                    }
1125                }
1126            }
1127        }
1128
1129        let done = Arc::new(Notify::new());
1130        let reactor = Reactor::<Msg, Worker>::new_current().unwrap();
1131
1132        let mut builder = TaskBuilder::<Msg>::new();
1133        let cb = builder.add_channel(0, Capacity::Unbounded);
1134        let ext = builder.add_channel(1, Capacity::Unbounded);
1135
1136        let handler = reactor
1137            .spawn(
1138                Worker {
1139                    handler: None,
1140                    ch: None,
1141                    armed: false,
1142                    done: done.clone(),
1143                },
1144                builder,
1145            )
1146            .unwrap();
1147
1148        handler
1149            .send(
1150                ext,
1151                Msg::Init {
1152                    handler: handler.clone(),
1153                    ch: cb,
1154                },
1155            )
1156            .ok()
1157            .expect("init send");
1158        handler.send(ext, Msg::Start).ok().expect("start send");
1159
1160        // Wait up to 2 s for the spawned timer to fire. With the bug,
1161        // it never fires. With the fix, it fires in ~100 ms.
1162        let waited = std::thread::scope(|s| {
1163            let done = done.clone();
1164            let h = s.spawn(move || {
1165                let rt = tokio::runtime::Builder::new_current_thread()
1166                    .enable_all()
1167                    .build()
1168                    .unwrap();
1169                rt.block_on(async {
1170                    tokio::time::timeout(Duration::from_secs(2), done.notified())
1171                        .await
1172                        .is_ok()
1173                })
1174            });
1175            h.join().unwrap()
1176        });
1177
1178        assert!(
1179            waited,
1180            "spawned timer did not fire within 2 s: scheduler is starving the runtime"
1181        );
1182
1183        // The handler keeps re-queueing forever, so we can't `shutdown`
1184        // cleanly here — the receivers will never close. Drop the
1185        // reactor and let the OS reap the thread on process exit.
1186        std::mem::forget(handler);
1187        std::mem::forget(reactor);
1188    }
1189}