sfo_pool/
worker_pool.rs

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
use std::collections::VecDeque;
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, Mutex};
use std::thread::sleep;
use std::time::Duration;
use notify_future::NotifyFuture;
use tokio::runtime::Runtime;

#[async_trait::async_trait]
pub trait Worker {
    fn is_work(&self) -> bool;
}

pub struct WorkerGuard<W: Worker, F: WorkerFactory<W>> {
    pool_ref: WorkerPoolRef<W, F>,
    worker: Option<W>
}

impl<W: Worker, F: WorkerFactory<W>> WorkerGuard<W, F> {
    fn new(worker: W, pool_ref: WorkerPoolRef<W, F>) -> Self {
        WorkerGuard {
            pool_ref,
            worker: Some(worker)
        }
    }
}

impl<W: Worker, F: WorkerFactory<W>> Deref for WorkerGuard<W, F> {
    type Target = W;

    fn deref(&self) -> &Self::Target {
        self.worker.as_ref().unwrap()
    }
}

impl<W: Worker, F: WorkerFactory<W>> DerefMut for WorkerGuard<W, F> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.worker.as_mut().unwrap()
    }
}

impl<W: Worker, F: WorkerFactory<W>> Drop for WorkerGuard<W, F> {
    fn drop(&mut self) {
        if let Some(worker) = self.worker.take() {
            self.pool_ref.release(worker);
        }
    }
}

#[async_trait::async_trait]
pub trait WorkerFactory<W: Worker> {
    async fn create(&self) -> W;
}

struct WorkerPoolState<W: Worker, F: WorkerFactory<W>> {
    current_count: u16,
    worker_list: VecDeque<W>,
    waiting_list: VecDeque<NotifyFuture<WorkerGuard<W, F>>>,
}
pub struct WorkerPool<W: Worker, F: WorkerFactory<W>> {
    factory: F,
    max_count: u16,
    state: Mutex<WorkerPoolState<W, F>>,
}
pub type WorkerPoolRef<W, F> = Arc<WorkerPool<W, F>>;

impl<W: Worker, F: WorkerFactory<W>> WorkerPool<W, F> {
    pub fn new(max_count: u16, factory: F) -> WorkerPoolRef<W, F> {
        Arc::new(WorkerPool {
            factory,
            max_count,
            state: Mutex::new(WorkerPoolState {
                current_count: 0,
                worker_list: VecDeque::with_capacity(max_count as usize),
                waiting_list: VecDeque::new(),
            }),
        })
    }

    pub async fn get_worker(self: &WorkerPoolRef<W, F>) -> WorkerGuard<W, F> {
        let wait = {
            let mut state = self.state.lock().unwrap();

            while state.worker_list.len() > 0 {
                let worker = state.worker_list.pop_front().unwrap();
                if !worker.is_work() {
                    state.current_count -= 1;
                    continue;
                }
                return WorkerGuard::new(worker, self.clone());
            }

            if state.current_count < self.max_count {
                state.current_count += 1;
                None
            } else {
                let future = NotifyFuture::new();
                state.waiting_list.push_back(future.clone());
                Some(future)
            }
        };

        if let Some(wait) = wait {
            wait.await
        } else {
            let worker = self.factory.create().await;
            WorkerGuard::new(worker, self.clone())
        }
    }

    fn release(self: &WorkerPoolRef<W, F>, work: W) {
        if work.is_work() {
            let mut state = self.state.lock().unwrap();
            let future = state.waiting_list.pop_front();
            if let Some(future) = future {
                future.set_complete(WorkerGuard::new(work, self.clone()));
            } else {
                state.worker_list.push_back(work);
            }
        } else {
            let mut state = self.state.lock().unwrap();
            let future = state.waiting_list.pop_front();
            if let Some(future) = future {
                let rt = Runtime::new().unwrap();
                let work = rt.block_on(self.factory.create());
                future.set_complete(WorkerGuard::new(work, self.clone()));
            } else {
                state.current_count -= 1;
            }
        }
    }
}

#[test]
fn test_pool() {
    struct TestWorker {
        work: bool,
    }

    #[async_trait::async_trait]
    impl Worker for TestWorker {
        fn is_work(&self) -> bool {
            self.work
        }
    }

    struct TestWorkerFactory;

    #[async_trait::async_trait]
    impl WorkerFactory<TestWorker> for TestWorkerFactory {
        async fn create(&self) -> TestWorker {
            TestWorker { work: true }
        }
    }

    let pool = WorkerPool::new(2, TestWorkerFactory);
    let rt = Runtime::new().unwrap();
    let pool_ref = pool.clone();
    rt.spawn(async move {
        let _worker = pool_ref.get_worker().await;
        tokio::time::sleep(Duration::from_secs(5)).await;
    });
    let pool_ref = pool.clone();
    rt.spawn(async move {
        let _worker = pool_ref.get_worker().await;
        tokio::time::sleep(Duration::from_secs(10)).await;
    });

    let pool_ref = pool.clone();
    rt.spawn(async move {
        tokio::time::sleep(Duration::from_secs(2)).await;

        let start = std::time::Instant::now();
        let _worker3 = pool_ref.get_worker().await;
        let end = std::time::Instant::now();
        let duration = end.duration_since(start);
        println!("duration {}", duration.as_millis());
        assert!(duration.as_millis() > 2000);
    });

    sleep(Duration::from_secs(10));
}