1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#![ doc = include_str!( concat!( env!( "CARGO_MANIFEST_DIR" ), "/", "README.md" ) ) ]
use log::error;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Semaphore;
use tokio::task::JoinHandle;

pub type SpawnResult<T> = Result<JoinHandle<Result<<T as Future>::Output, Error>>, Error>;

/// Task ID, can be created from &'static str or String
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TaskId {
    Static(&'static str),
    Owned(String),
}

impl From<&'static str> for TaskId {
    #[inline]
    fn from(s: &'static str) -> Self {
        Self::Static(s)
    }
}

impl From<String> for TaskId {
    #[inline]
    fn from(s: String) -> Self {
        Self::Owned(s)
    }
}

impl TaskId {
    #[inline]
    fn as_str(&self) -> &str {
        match self {
            TaskId::Static(v) => v,
            TaskId::Owned(s) => s.as_str(),
        }
    }
}

/// Task
///
/// Contains Future, can contain custom ID and timeout
pub struct Task<T>
where
    T: Future + Send + 'static,
    T::Output: Send + 'static,
{
    id: Option<TaskId>,
    timeout: Option<Duration>,
    future: T,
}

impl<T> Task<T>
where
    T: Future + Send + 'static,
    T::Output: Send + 'static,
{
    #[inline]
    pub fn new(future: T) -> Self {
        Self {
            id: None,
            timeout: None,
            future,
        }
    }
    #[inline]
    pub fn with_id<I: Into<TaskId>>(mut self, id: I) -> Self {
        self.id = Some(id.into());
        self
    }
    #[inline]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Error {
    SpawnTimeout,
    RunTimeout(Option<TaskId>),
    SpawnSemaphoneAcquireError,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::SpawnTimeout => write!(f, "task spawn timeout"),
            Error::RunTimeout(id) => {
                if let Some(i) = id {
                    write!(f, "task {} run timeout", i.as_str())
                } else {
                    write!(f, "task run timeout")
                }
            }
            Error::SpawnSemaphoneAcquireError => write!(f, "task spawn semaphore error"),
        }
    }
}

impl std::error::Error for Error {}

impl From<tokio::sync::AcquireError> for Error {
    fn from(_: tokio::sync::AcquireError) -> Self {
        Self::SpawnSemaphoneAcquireError
    }
}

/// Task pool
pub struct Pool {
    id: Option<Arc<String>>,
    spawn_timeout: Option<Duration>,
    run_timeout: Option<Duration>,
    limiter: Option<Arc<Semaphore>>,
    capacity: Option<usize>,
    logging_enabled: bool,
}

impl Default for Pool {
    fn default() -> Self {
        Self::unbounded()
    }
}

impl Pool {
    /// Creates a bounded pool (recommended)
    pub fn bounded(capacity: usize) -> Self {
        Self {
            id: None,
            spawn_timeout: None,
            run_timeout: None,
            limiter: Some(Arc::new(Semaphore::new(capacity))),
            capacity: Some(capacity),
            logging_enabled: true,
        }
    }
    /// Creates an unbounded pool
    pub fn unbounded() -> Self {
        Self {
            id: None,
            spawn_timeout: None,
            run_timeout: None,
            limiter: None,
            capacity: None,
            logging_enabled: true,
        }
    }
    pub fn with_id<I: Into<String>>(mut self, id: I) -> Self {
        self.id.replace(Arc::new(id.into()));
        self
    }
    pub fn id(&self) -> Option<&str> {
        self.id.as_deref().map(String::as_str)
    }
    /// Sets spawn timeout
    ///
    /// (ignored for unbounded)
    #[inline]
    pub fn with_spawn_timeout(mut self, timeout: Duration) -> Self {
        self.spawn_timeout = Some(timeout);
        self
    }
    /// Sets the default task run timeout
    #[inline]
    pub fn with_run_timeout(mut self, timeout: Duration) -> Self {
        self.run_timeout = Some(timeout);
        self
    }
    /// Sets both spawn and run timeouts
    #[inline]
    pub fn with_timeout(self, timeout: Duration) -> Self {
        self.with_spawn_timeout(timeout).with_run_timeout(timeout)
    }
    /// Disables internal error logging_enabled
    #[inline]
    pub fn with_no_logging_enabled(mut self) -> Self {
        self.logging_enabled = false;
        self
    }
    /// Returns pool capacity
    #[inline]
    pub fn capacity(&self) -> Option<usize> {
        self.capacity
    }
    /// Returns pool available task permits
    #[inline]
    pub fn available_permits(&self) -> Option<usize> {
        self.limiter.as_ref().map(|v| v.available_permits())
    }
    /// Returns pool busy task permits
    #[inline]
    pub fn busy_permits(&self) -> Option<usize> {
        self.limiter
            .as_ref()
            .map(|v| self.capacity.unwrap_or_default() - v.available_permits())
    }
    /// Spawns a future
    #[inline]
    pub fn spawn<T>(&self, future: T) -> impl Future<Output = SpawnResult<T>> + '_
    where
        T: Future + Send + 'static,
        T::Output: Send + 'static,
    {
        self.spawn_task(Task::new(future))
    }
    /// Spawns a future with a custom timeout
    #[inline]
    pub fn spawn_with_timeout<T>(
        &self,
        future: T,
        timeout: Duration,
    ) -> impl Future<Output = SpawnResult<T>> + '_
    where
        T: Future + Send + 'static,
        T::Output: Send + 'static,
    {
        self.spawn_task(Task::new(future).with_timeout(timeout))
    }
    /// Spawns a task (a future which can have a custom ID and timeout)
    pub async fn spawn_task<T>(&self, task: Task<T>) -> SpawnResult<T>
    where
        T: Future + Send + 'static,
        T::Output: Send + 'static,
    {
        let id = self.id.as_ref().cloned();
        let perm = if let Some(ref limiter) = self.limiter {
            if let Some(spawn_timeout) = self.spawn_timeout {
                Some(
                    tokio::time::timeout(spawn_timeout, limiter.clone().acquire_owned())
                        .await
                        .map_err(|_| Error::SpawnTimeout)??,
                )
            } else {
                Some(limiter.clone().acquire_owned().await?)
            }
        } else {
            None
        };
        if let Some(rtimeout) = task.timeout.or(self.run_timeout) {
            let logging_enabled = self.logging_enabled;
            Ok(tokio::spawn(async move {
                let _p = perm;
                if let Ok(v) = tokio::time::timeout(rtimeout, task.future).await {
                    Ok(v)
                } else {
                    let e = Error::RunTimeout(task.id);
                    if logging_enabled {
                        error!("{}: {}", id.as_deref().map_or("", |v| v.as_str()), e);
                    }
                    Err(e)
                }
            }))
        } else {
            Ok(tokio::spawn(async move {
                let _p = perm;
                Ok(task.future.await)
            }))
        }
    }
}

#[cfg(test)]
mod test {
    use super::Pool;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::sync::mpsc::channel;
    use tokio::time::sleep;

    #[tokio::test]
    async fn test_spawn() {
        let pool = Pool::bounded(5);
        let counter = Arc::new(AtomicUsize::new(0));
        for _ in 1..=5 {
            let counter_c = counter.clone();
            pool.spawn(async move {
                sleep(Duration::from_secs(2)).await;
                counter_c.fetch_add(1, Ordering::SeqCst);
            })
            .await
            .unwrap();
        }
        sleep(Duration::from_secs(3)).await;
        assert_eq!(counter.load(Ordering::SeqCst), 5);
    }

    #[tokio::test]
    async fn test_spawn_timeout() {
        let pool = Pool::bounded(5).with_spawn_timeout(Duration::from_secs(1));
        for _ in 1..=5 {
            let (tx, mut rx) = channel(1);
            pool.spawn(async move {
                tx.send(()).await.unwrap();
                sleep(Duration::from_secs(2)).await;
            })
            .await
            .unwrap();
            rx.recv().await;
        }
        dbg!(pool.available_permits(), pool.busy_permits());
        assert!(pool
            .spawn(async move {
                sleep(Duration::from_secs(2)).await;
            })
            .await
            .is_err());
    }

    #[tokio::test]
    async fn test_run_timeout() {
        let pool = Pool::bounded(5).with_run_timeout(Duration::from_secs(2));
        let counter = Arc::new(AtomicUsize::new(0));
        for i in 1..=5 {
            let counter_c = counter.clone();
            pool.spawn(async move {
                sleep(Duration::from_secs(if i == 5 { 3 } else { 1 })).await;
                counter_c.fetch_add(1, Ordering::SeqCst);
            })
            .await
            .unwrap();
        }
        sleep(Duration::from_secs(5)).await;
        assert_eq!(counter.load(Ordering::SeqCst), 4);
    }
}