Skip to main content

dekopon_process/
threads.rs

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