Skip to main content

dekopon_process/
threads.rs

1use std::{
2    io,
3    sync::Arc,
4    thread::{self, Scope, ScopedJoinHandle},
5};
6
7use dekopon_core::offload;
8use tokio::{
9    runtime::Handle,
10    sync::{OwnedSemaphorePermit, Semaphore, oneshot},
11};
12
13use crate::LimitExceeded;
14
15#[derive(Clone, Debug)]
16pub struct ShellThreads {
17    permits: Arc<Semaphore>,
18    maximum: u32,
19    runtime: Handle,
20}
21
22impl ShellThreads {
23    pub const STACK_BYTES: usize = 2 * 1024 * 1024;
24
25    #[must_use]
26    pub fn new(maximum: u32, runtime: Handle) -> Self {
27        Self {
28            permits: Arc::new(Semaphore::new(maximum as usize)),
29            maximum,
30            runtime,
31        }
32    }
33
34    pub fn reserve<const N: usize>(&self) -> Result<[ThreadPermit; N], LimitExceeded> {
35        self.reserve_many(N)?
36            .try_into()
37            .map_err(|_unsplit: Vec<ThreadPermit>| self.exhausted())
38    }
39
40    pub fn reserve_many(&self, count: usize) -> Result<Vec<ThreadPermit>, LimitExceeded> {
41        let mut permits = Vec::with_capacity(count);
42        let Some(last) = count.checked_sub(1) else {
43            return Ok(permits);
44        };
45        let requested = u32::try_from(count).map_err(|_oversized| self.exhausted())?;
46        let mut group = Arc::clone(&self.permits)
47            .try_acquire_many_owned(requested)
48            .map_err(|_busy| self.exhausted())?;
49        for _ in 0..last {
50            let one = group.split(1).ok_or_else(|| self.exhausted())?;
51            permits.push(self.permit(one));
52        }
53        permits.push(self.permit(group));
54        Ok(permits)
55    }
56
57    fn permit(&self, permit: OwnedSemaphorePermit) -> ThreadPermit {
58        ThreadPermit {
59            permit,
60            runtime: self.runtime.clone(),
61        }
62    }
63
64    const fn exhausted(&self) -> LimitExceeded {
65        LimitExceeded::ShellThreads {
66            maximum: self.maximum,
67        }
68    }
69}
70
71#[derive(Clone, Copy, Debug, Eq, PartialEq)]
72pub struct ThreadName(&'static str);
73
74impl ThreadName {
75    #[must_use]
76    pub const fn new(name: &'static str) -> Self {
77        assert!(name.len() <= 15, "a thread name is at most 15 bytes");
78        Self(name)
79    }
80}
81
82#[derive(Debug)]
83#[must_use]
84pub struct ThreadPermit {
85    permit: OwnedSemaphorePermit,
86    runtime: Handle,
87}
88
89struct Completed(Option<oneshot::Sender<()>>);
90
91impl Drop for Completed {
92    fn drop(&mut self) {
93        if let Some(done) = self.0.take() {
94            done.send(()).unwrap_or(());
95        }
96    }
97}
98
99impl ThreadPermit {
100    pub fn spawn_owned<T: Send + 'static>(
101        self,
102        name: ThreadName,
103        run: impl FnOnce() -> T + Send + 'static,
104    ) -> io::Result<impl Future<Output = Result<thread::Result<T>, tokio::task::JoinError>> + Send>
105    {
106        let Self { permit, runtime } = self;
107        let (done, completed) = oneshot::channel();
108        #[expect(
109            clippy::disallowed_methods,
110            reason = "owner: the returned join operation, retained by the gateway; bound: the ShellThreads permit moved into the thread"
111        )]
112        let thread = thread::Builder::new()
113            .name(name.0.to_owned())
114            .stack_size(ShellThreads::STACK_BYTES)
115            .spawn(move || {
116                let _completed = Completed(Some(done));
117                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
118                    let _runtime = runtime.enter();
119                    run()
120                }));
121                (permit, result)
122            })?;
123        Ok(async move {
124            drop(completed.await);
125            // Closure completion precedes TLS destruction, so even the final join stays off workers.
126            offload(move || match thread.join() {
127                Ok((_permit, result)) => result,
128                Err(payload) => Err(payload),
129            })
130            .await
131            .map_err(Into::into)
132        })
133    }
134
135    pub fn spawn<'scope, T: Send + 'scope>(
136        self,
137        scope: &'scope Scope<'scope, '_>,
138        name: ThreadName,
139        run: impl FnOnce() -> T + Send + 'scope,
140    ) -> io::Result<ScopedJoinHandle<'scope, T>> {
141        let Self { permit, runtime } = self;
142        #[expect(
143            clippy::disallowed_methods,
144            reason = "owner: the caller's thread::scope joins it; bound: the ShellThreads permit moved into the thread"
145        )]
146        thread::Builder::new()
147            .name(name.0.to_owned())
148            .stack_size(ShellThreads::STACK_BYTES)
149            .spawn_scoped(scope, move || {
150                let _permit = permit;
151                let _runtime = runtime.enter();
152                run()
153            })
154    }
155}