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        }
775    });
776
777    handler
778}
779
780// ---------------------------------------------------------------------------
781// Tests
782// ---------------------------------------------------------------------------
783
784#[cfg(test)]
785mod tests {
786    use super::*;
787    use std::sync::Mutex;
788    use std::time::Duration;
789
790    /// Drive the reactor with a gated task so all messages get enqueued
791    /// before the scheduler sees any.
792    fn run_with_gate<S>(channels: Vec<(u8, Capacity, Vec<u32>)>, scheduler: S) -> Vec<u32>
793    where
794        S: Scheduler<u32>,
795    {
796        use tokio::sync::Notify;
797
798        let log = Arc::new(Mutex::new(Vec::<u32>::new()));
799
800        struct Gated {
801            log: Arc<Mutex<Vec<u32>>>,
802            gate: Arc<Notify>,
803            gate_passed: bool,
804        }
805
806        impl Task<u32> for Gated {
807            async fn handle(&mut self, ctx: u32) {
808                if !self.gate_passed {
809                    self.gate.notified().await;
810                    self.gate_passed = true;
811                }
812                self.log.lock().unwrap().push(ctx);
813            }
814        }
815
816        let gate = Arc::new(Notify::new());
817        let task = Gated {
818            log: log.clone(),
819            gate: gate.clone(),
820            gate_passed: false,
821        };
822
823        let reactor = Reactor::<u32, Gated>::new_current().unwrap();
824
825        let mut builder = TaskBuilder::<u32>::new();
826        let tokens: Vec<Channel<u32>> = channels
827            .iter()
828            .map(|(prio, cap, _)| builder.add_channel(*prio, *cap))
829            .collect();
830
831        let handler = reactor.spawn_with(task, builder, scheduler).unwrap();
832
833        // Dummy sentinel on first channel to force scheduler into the gate.
834        handler.send(tokens[0], u32::MAX).unwrap();
835        std::thread::sleep(Duration::from_millis(50));
836
837        for (i, (_prio, _cap, msgs)) in channels.iter().enumerate() {
838            for m in msgs {
839                handler.send(tokens[i], *m).unwrap();
840            }
841        }
842
843        gate.notify_one();
844
845        let expected: usize = 1 + channels.iter().map(|(_, _, m)| m.len()).sum::<usize>();
846        let deadline = std::time::Instant::now() + Duration::from_secs(5);
847        loop {
848            if log.lock().unwrap().len() >= expected {
849                break;
850            }
851            if std::time::Instant::now() >= deadline {
852                panic!(
853                    "timeout: got {} / {} items",
854                    log.lock().unwrap().len(),
855                    expected
856                );
857            }
858            std::thread::sleep(Duration::from_millis(10));
859        }
860
861        drop(handler);
862        reactor.shutdown().unwrap();
863
864        let mut recorded = log.lock().unwrap().clone();
865        assert_eq!(recorded.remove(0), u32::MAX);
866        recorded
867    }
868
869    #[test]
870    fn fair_priority_order_default() {
871        let result = run_with_gate(
872            vec![
873                (0, Capacity::Unbounded, vec![10, 11, 12]),
874                (1, Capacity::Unbounded, vec![20, 21, 22]),
875                (2, Capacity::Unbounded, vec![30, 31, 32]),
876            ],
877            FairPriority::default(),
878        );
879        assert_eq!(result, vec![10, 11, 12, 20, 21, 22, 30, 31, 32]);
880    }
881
882    #[test]
883    fn strict_priority_scheduler() {
884        let result = run_with_gate(
885            vec![
886                (0, Capacity::Unbounded, (0..50).collect()),
887                (2, Capacity::Unbounded, vec![999]),
888            ],
889            StrictPriority,
890        );
891
892        // StrictPriority: all 50 high-prio items come out before the low one.
893        let pos = result.iter().position(|&v| v == 999).unwrap();
894        assert_eq!(pos, 50, "low-prio must come last under StrictPriority");
895    }
896
897    #[test]
898    fn fair_priority_anti_starvation() {
899        let high: Vec<u32> = (0..40).map(|i| 1000 + i).collect();
900        let low = vec![9999_u32];
901
902        let result = run_with_gate(
903            vec![
904                (0, Capacity::Unbounded, high.clone()),
905                (2, Capacity::Unbounded, low),
906            ],
907            FairPriority::new(16),
908        );
909
910        let pos = result.iter().position(|&v| v == 9999).unwrap();
911        assert!(
912            pos <= 16,
913            "FairPriority must relieve starvation within budget: pos={pos}"
914        );
915
916        let highs: Vec<u32> = result.iter().copied().filter(|&v| v != 9999).collect();
917        let mut sorted = highs.clone();
918        sorted.sort();
919        assert_eq!(sorted, high);
920    }
921
922    #[test]
923    fn bounded_channel_applies_backpressure() {
924        // Bounded(1) channel. The consumer blocks on the *first* item only;
925        // that leaves the pipeline with:
926        //   - 1 item in-flight (held by the handler, awaiting release)
927        //   - 1 item buffered (capacity = 1)
928        // A further `try_send` must then return `Full`.
929        use tokio::sync::Notify;
930
931        struct Slow {
932            release: Arc<Notify>,
933            blocked_once: bool,
934        }
935        impl Task<u32> for Slow {
936            async fn handle(&mut self, _ctx: u32) {
937                if !self.blocked_once {
938                    self.blocked_once = true;
939                    self.release.notified().await;
940                }
941            }
942        }
943
944        let release = Arc::new(Notify::new());
945        let reactor = Reactor::<u32, Slow>::new_current().unwrap();
946        let mut builder = TaskBuilder::<u32>::new();
947        let ch = builder.add_bounded(0, 1);
948        let handler = reactor
949            .spawn(
950                Slow {
951                    release: release.clone(),
952                    blocked_once: false,
953                },
954                builder,
955            )
956            .unwrap();
957
958        // Consumer picks up item 1 and blocks on `notified`.
959        handler.try_send(ch, 1).expect("send 1");
960        std::thread::sleep(Duration::from_millis(100));
961
962        // Fill the 1-slot buffer.
963        handler.try_send(ch, 2).expect("send 2 fills buffer");
964        // Now Full.
965        match handler.try_send(ch, 3) {
966            Err(TrySendError::Full(3)) => { /* expected */ }
967            other => panic!("expected Full(3), got {:?}", other.map(|_| ())),
968        }
969
970        // Release the consumer; subsequent items process instantly.
971        release.notify_one();
972        drop(handler);
973        reactor.shutdown().expect("shutdown");
974    }
975
976    #[tokio::test(flavor = "current_thread")]
977    async fn send_async_awaits_capacity() {
978        // Reactor on its own thread, task that processes each item after a
979        // small sleep. A bounded(1) channel; producer uses send_async to
980        // push 5 items, which should all land eventually.
981        struct Trickle {
982            log: Arc<Mutex<Vec<u32>>>,
983        }
984        impl Task<u32> for Trickle {
985            async fn handle(&mut self, ctx: u32) {
986                tokio::time::sleep(Duration::from_millis(20)).await;
987                self.log.lock().unwrap().push(ctx);
988            }
989        }
990
991        let log = Arc::new(Mutex::new(Vec::<u32>::new()));
992        let reactor = Reactor::<u32, Trickle>::new_current().unwrap();
993        let mut builder = TaskBuilder::<u32>::new();
994        let ch = builder.add_bounded(0, 1);
995        // Use the async spawn variant since we're inside a tokio runtime.
996        let handler = reactor
997            .spawn_async(Trickle { log: log.clone() }, builder)
998            .await
999            .unwrap();
1000
1001        for i in 0..5u32 {
1002            handler.send_async(ch, i).await.unwrap();
1003        }
1004
1005        // Wait for the task to drain.
1006        let deadline = std::time::Instant::now() + Duration::from_secs(2);
1007        loop {
1008            if log.lock().unwrap().len() == 5 {
1009                break;
1010            }
1011            if std::time::Instant::now() >= deadline {
1012                panic!("didn't drain in time");
1013            }
1014            tokio::time::sleep(Duration::from_millis(10)).await;
1015        }
1016
1017        assert_eq!(*log.lock().unwrap(), vec![0, 1, 2, 3, 4]);
1018        drop(handler);
1019        // Move the blocking shutdown to a blocking thread to avoid
1020        // stalling the current-thread runtime.
1021        tokio::task::spawn_blocking(move || reactor.shutdown().unwrap())
1022            .await
1023            .unwrap();
1024    }
1025
1026    #[test]
1027    fn shutdown_is_clean() {
1028        struct Noop;
1029        impl Task<()> for Noop {
1030            async fn handle(&mut self, _ctx: ()) {}
1031        }
1032
1033        let reactor = Reactor::<(), Noop>::new_current().unwrap();
1034        let mut builder = TaskBuilder::<()>::new();
1035        let ch = builder.add_unbounded(0);
1036        let handler = reactor.spawn(Noop, builder).unwrap();
1037
1038        for _ in 0..10 {
1039            handler.send(ch, ()).unwrap();
1040        }
1041
1042        drop(handler);
1043        reactor.shutdown().expect("shutdown clean");
1044    }
1045}