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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use std::collections::{BTreeMap, HashSet, VecDeque};
use std::fmt::{self, Debug, Formatter};
use std::future::Future;
use std::pin::Pin;
use std::sync::{
    atomic::{AtomicU8, Ordering},
    Arc,
};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

use concurrent_queue::ConcurrentQueue;

use futures_util::FutureExt;

use super::resource::{ResourceGuard, ResourceInfo, ResourceLock};
use super::shared::{DisposeFn, ReleaseFn, Shared, SharedEvent};
use super::util::{sentinel::Sentinel, thread_waker};

mod acquire;
pub use acquire::Acquire;

mod config;
pub use config::PoolConfig;

mod error;
pub use error::AcquireError;

mod executor;
pub use executor::{default_executor, Executor};

mod operation;
use operation::{
    resource_create, resource_verify, ResourceFuture, ResourceOperation, ResourceResolve,
};

mod wait;
use wait::{waiter_pair, WaitResponder, Waiter};

const ACTIVE: u8 = 0;
const DRAIN: u8 = 1;
const SHUTDOWN: u8 = 2;
const STOPPED: u8 = 3;

type BoxedOperation<T, E> = Box<dyn ResourceOperation<T, E> + Send + Sync>;

type ErrorFn<E> = Box<dyn Fn(E) + Send + Sync>;

type WaitResource<T, E> = WaitResponder<ResourceResolve<T, E>>;

pub(crate) struct PoolManageState<T: Send + 'static, E: 'static> {
    acquire_timeout: Option<Duration>,
    create: BoxedOperation<T, E>,
    executor: Box<dyn Executor>,
    handle_error: Option<ErrorFn<E>>,
    max_waiters: Option<usize>,
    shared_waiter: thread_waker::Waiter,
    register_inject: ConcurrentQueue<Register<T, E>>,
    state: AtomicU8,
    verify: Option<BoxedOperation<T, E>>,
}

pub struct PoolInternal<T: Send + 'static, E: 'static> {
    manage: PoolManageState<T, E>,
    shared: Arc<Shared<T>>,
}

impl<T: Send, E> PoolInternal<T, E> {
    pub fn new(
        acquire_timeout: Option<Duration>,
        create: Box<dyn ResourceOperation<T, E> + Send + Sync>,
        executor: Box<dyn Executor>,
        handle_error: Option<Box<dyn Fn(E) + Send + Sync>>,
        idle_timeout: Option<Duration>,
        min_count: usize,
        max_count: usize,
        max_waiters: Option<usize>,
        on_dispose: Option<DisposeFn<T>>,
        on_release: Option<ReleaseFn<T>>,
        verify: Option<Box<dyn ResourceOperation<T, E> + Send + Sync>>,
    ) -> Self {
        let (shared, shared_waiter) =
            Shared::new(on_release, on_dispose, min_count, max_count, idle_timeout);
        let manage = PoolManageState {
            acquire_timeout,
            create,
            executor,
            handle_error,
            max_waiters,
            register_inject: ConcurrentQueue::unbounded(),
            shared_waiter,
            state: AtomicU8::new(ACTIVE),
            verify,
        };
        Self {
            manage,
            shared: Arc::new(shared),
        }
    }

    pub fn create(self: &Arc<Self>) -> ResourceResolve<T, E> {
        let mut info = ResourceInfo::default();
        info.reusable = self.shared.can_reuse();
        let lock = ResourceLock::new(info, None);
        let guard = lock.try_lock().unwrap();

        // Send the resource lock into the repo, for collection later
        // Not concerned with failure here
        self.shared
            .push_event(SharedEvent::Created(guard.as_lock()));

        self.manage.create.apply(guard, self)
    }

    pub fn create_from_count(&self) -> Option<usize> {
        let count = self.shared.count();
        let max = self.shared.max_count();
        if max == 0 || max > count {
            Some(count)
        } else {
            None
        }
    }

    pub fn handle_error(&self, err: E) {
        if let Some(handler) = self.manage.handle_error.as_ref() {
            (handler)(err)
        }
    }

    fn manage(self: Arc<Self>) {
        let mut drain_count: usize = 0;
        let inner = Sentinel::new(self, |inner, _| {
            // Set the state to Stopped when this thread exits, whether normally
            // or due to a panic.
            inner.manage.state.store(STOPPED, Ordering::Release);
        });
        let mut last_dispose_count = 0;
        let mut next_check = None;
        let mut repo = HashSet::<ResourceLock<T>>::new();
        let mut timer_id_source: usize = 0;
        let mut timers = BTreeMap::<(Instant, usize), Timer<T, E>>::new();
        let mut waiters = VecDeque::<WaitResource<T, E>>::new();

        loop {
            let remain_timers = timers.split_off(&(Instant::now(), 0));
            for ((inst, _), timer) in timers {
                match timer {
                    Timer::Drain(_) => {
                        // Cancel drain (waiter is notified by dropping it)
                        drain_count -= 1;
                        if drain_count == 0 {
                            inner.stop_drain();
                        }
                    }
                    Timer::Verify(res) => {
                        if let Some(mut guard) = res.try_lock() {
                            // Any clone of the resource lock in the idle queue can't be
                            // acquired at the moment, so forget that lock and create a
                            // new one
                            repo.remove(&guard.as_lock());
                            guard = guard.detach();

                            if guard.is_some() && guard.info().verify_at == Some(inst) {
                                // Act upon the verify timer
                                inner.verify(guard);
                            } else {
                                // The resource was reacquired and released after the
                                // verify timer was set, put it back into the idle queue.
                                // FIXME attach timer to the resource lock so it can be
                                // checked without acquiring it
                                repo.insert(guard.as_lock());
                                // FIXME this can trigger another verify!
                                inner.shared.release(guard);
                            }
                        } else {
                            // If the resource is locked, then a consumer thread
                            // has acquired it or is in the process of doing so,
                            // nothing to do here
                        }
                    }
                    Timer::Waiter(waiter) => {
                        // Try to cancel the waiter. This will only succeed if the
                        // waiter hasn't been fulfilled already, or cancelled by the
                        // other side.
                        waiter.cancel();
                    }
                }
            }
            // remain_timers.drain_filter(|_, timer| timer.is_canceled());
            timers = remain_timers;

            if let Some(fst) = timers.keys().next() {
                next_check = Some(next_check.map_or(fst.0, |t| std::cmp::min(t, fst.0)))
            }

            // Set the waiter state to Idle.
            // If anything is subsequently added to the queues, it will move to Busy.
            inner.manage.shared_waiter.prepare_wait();

            while let Some(event) = inner.shared.pop_event() {
                match event {
                    SharedEvent::Created(res) => {
                        repo.insert(res);
                    }
                    SharedEvent::Verify(expire, res) => {
                        timer_id_source += 1;
                        timers.insert((expire, timer_id_source), Timer::Verify(res));
                    }
                }
            }

            while let Ok(register) = inner.manage.register_inject.pop() {
                match register {
                    Register::Drain(expire, notify) => {
                        inner.start_drain(false);
                        timer_id_source += 1;
                        timers.insert((expire, timer_id_source), Timer::Drain(notify));
                        drain_count += 1;
                    }
                    Register::Waiter(start, waiter) => {
                        if let Some(expire) =
                            inner.manage.acquire_timeout.clone().map(|dur| start + dur)
                        {
                            timer_id_source += 1;
                            timers.insert((expire, timer_id_source), Timer::Waiter(waiter.clone()));
                        }
                        waiters.push_back(waiter);
                    }
                }
            }

            if waiters.is_empty() {
                // FIXME dispose idle resources over min_count
                // because 'busy' allows them to return to the idle queue
                inner.shared.set_busy(false);
            } else {
                // This triggers released resources to go to the idle queue even when
                // there is no idle timeout, and prevents subsequent acquires from stealing
                // directly from the idle queue so that the waiters are completed first
                inner.shared.set_busy(true);

                if inner.shared.have_idle() || inner.create_from_count().is_some() {
                    let mut res = None;
                    while let Some(waiter) = waiters.pop_front() {
                        if waiter.is_canceled() {
                            continue;
                        }
                        // Bypasses busy check because we are satisfying waiters
                        if let Some(idle) = res.take().or_else(|| inner.shared.try_acquire_idle()) {
                            if let Err(mut failed) =
                                waiter.send((idle, inner.shared.clone()).into())
                            {
                                res = failed.take_resource()
                            }
                        } else {
                            // Return waiter, no resources available
                            waiters.push_front(waiter);
                            break;
                        }
                    }
                    // No active waiters were found, return the resource to the queue
                    if let Some(res) = res {
                        inner.shared.release(res);
                    }
                }
            }

            let state = inner.manage.state.load(Ordering::Acquire);
            if state == DRAIN {
                for res in repo.iter() {
                    if let Some(guard) = res.try_lock() {
                        inner.shared.dispose(guard);
                    }
                }
                repo.retain(|res| !res.is_none());
                if repo.is_empty() {
                    break;
                }
            } else {
                let dispose_count = inner.shared.dispose_count();
                if last_dispose_count != dispose_count {
                    repo.retain(|res| !res.is_none());
                    last_dispose_count = dispose_count;
                }
            }

            if let Some(next_check) = next_check {
                inner.manage.shared_waiter.wait_until(next_check);
            } else {
                inner.manage.shared_waiter.wait();
            }
            next_check = None;
        }

        // FIXME wait for executor to complete

        for (_, timer) in timers {
            match timer {
                Timer::Drain(waiter) => {
                    // Send true to indicate that the shutdown succeeded.
                    // Not bothered if the send fails.
                    waiter.send(true).unwrap_or(());
                }
                // Drop any other waiters, leading them to be cancelled
                _ => (),
            }
        }
    }

    pub fn complete_resolve(self: &Arc<Self>, res: ResourceResolve<T, E>) {
        if res.is_pending() {
            let inner = self.clone();
            self.manage.executor.spawn_ok(
                res.map(move |res| match res {
                    Some(Ok(res)) => {
                        inner.shared.release(res);
                    }
                    Some(Err(err)) => {
                        inner.handle_error(err);
                    }
                    None => (),
                })
                .boxed(),
            )
        }
    }

    pub fn release_future(self: &Arc<Self>, fut: ResourceFuture<T, E>) {
        self.complete_resolve(ResourceResolve::from((fut.boxed(), self.clone())));
    }

    fn register(&self, reg: Register<T, E>) {
        self.manage
            .register_inject
            .push(reg)
            .unwrap_or_else(|_| panic!("Pool manager injector error"));
        self.shared.notify();
    }

    pub fn shared(&self) -> &Arc<Shared<T>> {
        &self.shared
    }

    pub fn start_drain(self: &Arc<Self>, shutdown: bool) {
        let mut state = ACTIVE;
        let next_state = if shutdown { SHUTDOWN } else { DRAIN };
        loop {
            match self.manage.state.compare_exchange_weak(
                state,
                next_state,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    self.shared.notify();
                }
                Err(DRAIN) if next_state == DRAIN => {
                    break;
                }
                Err(s @ ACTIVE) | Err(s @ DRAIN) => {
                    state = s;
                }
                Err(SHUTDOWN) | Err(STOPPED) => {
                    break;
                }
                Err(_) => panic!("Invalid pool state"),
            }
        }
    }

    pub fn stop_drain(self: &Arc<Self>) {
        self.manage
            .state
            .compare_and_swap(DRAIN, ACTIVE, Ordering::AcqRel);
    }

    pub fn try_acquire_idle(self: &Arc<Self>) -> ResourceResolve<T, E> {
        if self.shared.is_busy() {
            ResourceResolve::empty()
        } else {
            // Wrap the resource guard to ensure it is returned to the queue
            self.shared
                .try_acquire_idle()
                .map(|res| (res, self.shared.clone()))
                .into()
        }
    }

    pub fn try_create(self: &Arc<Self>) -> ResourceResolve<T, E> {
        let mut count = match self.create_from_count() {
            Some(c) => c,
            None => return ResourceResolve::empty(),
        };
        let max = self.shared.max_count();

        loop {
            match self.shared.try_update_count(count, count + 1) {
                Ok(_) => {
                    break self.create();
                }
                Err(c) => {
                    if c > count && max != 0 && c > max {
                        // Count was increased beyond max by another thread
                        break ResourceResolve::empty();
                    }
                    count = c;
                    continue;
                }
            }
        }
    }

    pub fn try_wait(self: &Arc<Self>, started: Instant) -> Waiter<ResourceResolve<T, E>> {
        let (send, receive) = waiter_pair();
        self.register(Register::Waiter(started, send));
        self.shared.notify();
        receive
    }

    pub fn verify(self: &Arc<Self>, guard: ResourceGuard<T>) {
        if guard.info().reusable {
            if let Some(verify) = self.manage.verify.as_ref() {
                if self.shared.count() <= self.shared.min_count() {
                    return self.complete_resolve(verify.apply(guard, &self));
                }
            }
        }
        self.shared.dispose(guard);
    }
}

pub struct Pool<T: Send + 'static, E: 'static> {
    pub(crate) inner: Sentinel<PoolInternal<T, E>>,
}

impl<T: Send, E> Pool<T, E> {
    pub(crate) fn new(inner: PoolInternal<T, E>) -> Self {
        let inner = Arc::new(inner);
        let mgr = inner.clone();
        let sentinel = Sentinel::new(inner, |inner, count| {
            if count == 0 {
                inner.start_drain(true);
            }
        });
        std::thread::spawn(move || mgr.manage());
        Self { inner: sentinel }
    }

    pub fn acquire(&self) -> Acquire<T, E> {
        Acquire::new(self.clone())
    }

    pub fn count(&self) -> usize {
        self.inner.shared.count()
    }

    pub fn drain(self, timeout: Duration) -> PoolDrain<T, E> {
        let (send, receive) = waiter_pair();
        self.inner
            .register(Register::Drain(Instant::now() + timeout, send));
        PoolDrain {
            inner: Some(self.inner),
            receive,
        }
    }
}

impl<T: Send, E> Clone for Pool<T, E> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T: Send, E> Debug for Pool<T, E> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Pool")
            .field("count", &self.count())
            .finish()
    }
}

#[derive(Debug)]
enum Register<T: Send + 'static, E: 'static> {
    Drain(Instant, WaitResponder<bool>),
    Waiter(Instant, WaitResource<T, E>),
}

#[derive(Debug)]
enum Timer<T: Send + 'static, E: 'static> {
    Drain(WaitResponder<bool>),
    Verify(ResourceLock<T>),
    Waiter(WaitResource<T, E>),
}

impl<T: Send + 'static, E: 'static> Timer<T, E> {
    // fn is_canceled(&self) -> bool {
    //     match self {
    //         Self::Drain(ref wait) => wait.is_canceled(),
    //         Self::Verify(..) => false,
    //         Self::Waiter(ref wait) => wait.is_canceled(),
    //     }
    // }
}

pub struct PoolDrain<T: Send + 'static, E: 'static> {
    inner: Option<Sentinel<PoolInternal<T, E>>>,
    receive: Waiter<bool>,
}

impl<T: Send + 'static, E: 'static> Debug for PoolDrain<T, E> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("PoolDrain").finish()
    }
}

impl<T: Send, E> Future for PoolDrain<T, E> {
    type Output = Result<(), Pool<T, E>>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.inner.is_none() {
            return Poll::Ready(Ok(()));
        }

        match Pin::new(&mut *self.receive).poll(cx) {
            Poll::Ready(done) => {
                if done.unwrap_or(false) {
                    Poll::Ready(Ok(()))
                } else {
                    Poll::Ready(Err(Pool {
                        inner: self.inner.take().unwrap(),
                    }))
                }
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

// FIXME test behaviour of cloned WaitResponder + close