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
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crossbeam_queue::ArrayQueue;
use futures::future::{ok, Either, FutureResult};
use futures::sync::mpsc;
use futures::{try_ready, Async, Future, Poll};
use tokio_sync::semaphore::{self, Semaphore};

use crate::librarian::Librarian;
use crate::machine::{Machine, State, Turn};
use crate::resource::{Idle, Manage, Status};

pub trait Env {
    fn now() -> Instant;
}

pub struct DefaultEnv;

impl Env for DefaultEnv {
    fn now() -> Instant {
        Instant::now()
    }
}

/// A check out of a resource from a `Pool`. The resource is automatically returned when the
/// `CheckOut` is dropped.
pub struct CheckOut<M>
where
    M: Manage,
{
    resource: Option<M::Resource>,
    recycled_at: Instant,
    pool: Option<Pool<M>>,
}

impl<M> CheckOut<M>
where
    M: Manage,
{
    fn new(resource: M::Resource, recycled_at: Instant, pool: Pool<M>) -> Self {
        Self {
            resource: Some(resource),
            recycled_at,
            pool: Some(pool),
        }
    }

    /// Lends the resource to an opaque asynchronous computation.
    ///
    /// Like in real life, it is usually a bad idea to lend things you don't own. If the
    /// subcomputation finishes with an error, the resource is lost. `LentCheckOut` takes care of
    /// notifying the pool of that so new resources can be created.
    ///
    /// This is necessary in situation where a resource is taken by value.
    pub fn lend<F, T, B>(mut self, borrower: B) -> LentCheckOut<M, F, T>
    where
        F: Future<Item = (M::Resource, T)>,
        B: FnOnce(M::Resource) -> F,
    {
        LentCheckOut {
            inner: borrower(self.resource.take().unwrap()),
            recycled_at: self.recycled_at,
            pool: self.pool.take(),
        }
    }
}

impl<M> Deref for CheckOut<M>
where
    M: Manage,
{
    type Target = M::Resource;

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

impl<M> DerefMut for CheckOut<M>
where
    M: Manage,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.resource.as_mut().unwrap()
    }
}

impl<M> Drop for CheckOut<M>
where
    M: Manage,
{
    fn drop(&mut self) {
        if let (Some(resource), Some(mut pool)) = (self.resource.take(), self.pool.take()) {
            match pool.shared.manager.status(&resource) {
                Status::Valid => pool
                    .return_chute
                    .try_send(Idle::new(resource, self.recycled_at))
                    .unwrap(),
                Status::Invalid => (),
            }
        }
    }
}

/// A future where a resource is lent to an opaque, asynchronous computation.
pub struct LentCheckOut<M, F, T>
where
    M: Manage,
    F: Future<Item = (M::Resource, T)>,
{
    inner: F,
    recycled_at: Instant,
    pool: Option<Pool<M>>,
}

impl<M, F, T> Future for LentCheckOut<M, F, T>
where
    M: Manage,
    F: Future<Item = (M::Resource, T)>,
{
    type Item = (M::CheckOut, T);

    type Error = F::Error;

    fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
        let (resource, t) = try_ready!(self.inner.poll());
        Ok(Async::Ready((
            CheckOut {
                resource: Some(resource),
                recycled_at: self.recycled_at,
                pool: self.pool.take(),
            }
            .into(),
            t,
        )))
    }
}

impl<M, F, T> Drop for LentCheckOut<M, F, T>
where
    M: Manage,
    F: Future<Item = (M::Resource, T)>,
{
    fn drop(&mut self) {
        if let Some(pool) = self.pool.take() {
            pool.notify_of_lost_resource()
        }
    }
}

pub struct Shared<M>
where
    M: Manage,
{
    pub capacity: usize,

    /// Resources on the shelf are ready to be borrowed. You must increment `checked_out_count`
    /// before grabbing one though.
    pub shelf: ArrayQueue<Idle<M::Resource>>,

    pub checked_out_count: Semaphore,

    pub created_count: AtomicUsize,

    pub manager: M,

    pub recycle_interval: Duration,
}

/// The handle to the pool through which resources are requested.
pub struct Pool<M>
where
    M: Manage,
{
    shared: Arc<Shared<M>>,

    /// Resources are returned by sending them into this chute. Once there, it is the librarian that
    /// will inspect the resource, then take the decision to `drop` it or put is back on the shelf.
    return_chute: mpsc::Sender<Idle<M::Resource>>,
}

impl<M> Pool<M>
where
    M: Manage,
    M::Resource: Send,
{
    /// Starts the process of checking out a resource.
    pub fn check_out(&self) -> CheckOutFuture<M, DefaultEnv> {
        self.check_out_with_environment::<DefaultEnv>()
    }

    pub fn check_out_with_environment<E: Env>(&self) -> CheckOutFuture<M, E> {
        let mut permit = semaphore::Permit::new();
        let inner = if let Ok(()) = permit.try_acquire(&self.shared.checked_out_count) {
            let idle_resource = self.shared.shelf.pop().unwrap();
            if self.is_stale::<E>(&idle_resource) {
                let context = CheckOutContext { pool: self.clone() };
                let future = self.recycle(idle_resource);
                let machine = Machine::new(CheckOutState::Recycling { future }, context);
                Either::A(machine)
            } else {
                let recycled_at = idle_resource.recycled_at();
                let resource = idle_resource.into_resource();
                let entry = CheckOut::new(resource, recycled_at, self.clone()).into();
                Either::B(ok(entry))
            }
        } else {
            let context = CheckOutContext { pool: self.clone() };
            let machine = Machine::new(CheckOutState::start(), context);
            Either::A(machine)
        };
        CheckOutFuture { inner }
    }

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

    pub fn recycle_interval(&self) -> Duration {
        self.shared.recycle_interval
    }

    pub(crate) fn recycle(&self, resource: Idle<M::Resource>) -> M::RecycleFuture {
        self.shared.manager.recycle(resource.into_resource())
    }

    pub(crate) fn is_stale<E: Env>(&self, idle_resource: &Idle<M::Resource>) -> bool {
        E::now() > idle_resource.recycled_at() + self.recycle_interval()
    }

    pub(crate) fn notify_of_lost_resource(&self) {
        self.shared.created_count.fetch_sub(1, Ordering::SeqCst);
    }
}

impl<M> Clone for Pool<M>
where
    M: Manage,
{
    fn clone(&self) -> Self {
        Self {
            shared: Arc::clone(&self.shared),
            return_chute: self.return_chute.clone(),
        }
    }
}

type CheckOutStateMachine<M, E> = Machine<CheckOutState<M, E>>;
type ImmediatelyAvailable<M> = FutureResult<<M as Manage>::CheckOut, <M as Manage>::Error>;
type CheckOutFutureInner<M, E> = Either<CheckOutStateMachine<M, E>, ImmediatelyAvailable<M>>;

/// A `Future` that will yield a resource from the pool on completion.
#[must_use = "futures do nothing unless polled"]
pub struct CheckOutFuture<M, E = DefaultEnv>
where
    M: Manage,
    E: Env,
{
    inner: CheckOutFutureInner<M, E>,
}

impl<M, E> Future for CheckOutFuture<M, E>
where
    M: Manage,
    E: Env,
{
    type Item = M::CheckOut;

    type Error = M::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.inner.poll()
    }
}

struct CheckOutContext<M>
where
    M: Manage,
{
    pool: Pool<M>,
}

enum CheckOutState<M, E>
where
    M: Manage,
    E: Env,
{
    Start { _environment: PhantomData<E> },
    Creating { future: M::CreateFuture },
    Wait { permit: semaphore::Permit },
    Recycling { future: M::RecycleFuture },
}

impl<M, E> CheckOutState<M, E>
where
    M: Manage,
    E: Env,
{
    fn start() -> Self {
        CheckOutState::Start {
            _environment: PhantomData,
        }
    }

    fn on_start(context: &mut CheckOutContext<M>) -> Result<Turn<Self>, <Self as State>::Error> {
        loop {
            let pool = &mut context.pool;
            let created_count = pool.shared.created_count.load(Ordering::SeqCst);
            if created_count == pool.shared.capacity {
                return Ok(Turn::Continue(CheckOutState::Wait {
                    permit: semaphore::Permit::new(),
                }));
            }

            let swap_result = pool.shared.created_count.compare_and_swap(
                created_count,
                created_count + 1,
                Ordering::SeqCst,
            );
            if created_count == swap_result {
                let future = pool.shared.manager.create();
                return Ok(Turn::Continue(CheckOutState::Creating { future }));
            }
        }
    }

    fn on_creating(
        mut future: M::CreateFuture,
        _context: &mut CheckOutContext<M>,
    ) -> Result<Turn<Self>, <Self as State>::Error> {
        match future.poll()? {
            Async::NotReady => Ok(Turn::Suspend(CheckOutState::Creating { future })),
            Async::Ready(resource) => Ok(Turn::Done(Idle::new(resource, E::now()))),
        }
    }

    fn on_wait(
        mut permit: semaphore::Permit,
        context: &mut CheckOutContext<M>,
    ) -> Result<Turn<Self>, <Self as State>::Error> {
        let poll = permit
            .poll_acquire(&context.pool.shared.checked_out_count)
            .unwrap();
        match poll {
            Async::NotReady => Ok(Turn::Suspend(CheckOutState::Wait { permit })),
            Async::Ready(()) => {
                let idle_resource = context.pool.shared.shelf.pop().unwrap();
                if context.pool.is_stale::<E>(&idle_resource) {
                    let future = context.pool.recycle(idle_resource);
                    Ok(Turn::Continue(CheckOutState::Recycling { future }))
                } else {
                    Ok(Turn::Done(idle_resource))
                }
            }
        }
    }

    fn on_recycling(
        mut future: M::RecycleFuture,
        context: &mut CheckOutContext<M>,
    ) -> Result<Turn<Self>, <Self as State>::Error> {
        match future.poll() {
            Ok(Async::NotReady) => Ok(Turn::Suspend(CheckOutState::Recycling { future })),
            Ok(Async::Ready(Some(resource))) => Ok(Turn::Done(Idle::new(resource, E::now()))),
            Ok(Async::Ready(None)) | Err(_) => {
                context.pool.notify_of_lost_resource();
                Ok(Turn::Continue(CheckOutState::start()))
            }
        }
    }
}

impl<M, E> State for CheckOutState<M, E>
where
    M: Manage,
    E: Env,
{
    type Final = Idle<M::Resource>;

    type Item = M::CheckOut;

    type Error = M::Error;

    type Context = CheckOutContext<M>;

    fn turn(state: Self, context: &mut Self::Context) -> Result<Turn<Self>, Self::Error> {
        match state {
            CheckOutState::Start { .. } => Self::on_start(context),
            CheckOutState::Creating { future } => Self::on_creating(future, context),
            CheckOutState::Wait { permit } => Self::on_wait(permit, context),
            CheckOutState::Recycling { future } => Self::on_recycling(future, context),
        }
    }

    fn finalize(resource: Self::Final, context: Self::Context) -> Result<Self::Item, Self::Error> {
        let recycled_at = resource.recycled_at();
        Ok(CheckOut::new(resource.into_resource(), recycled_at, context.pool).into())
    }
}

pub struct Builder {
    recycle_interval: Duration,
}

impl Builder {
    pub fn new() -> Self {
        Self {
            recycle_interval: Duration::from_secs(30),
        }
    }

    pub fn recycle_interval(mut self, recycle_interval: Duration) -> Self {
        self.recycle_interval = recycle_interval;
        self
    }

    pub fn build<M>(self, capacity: usize, manager: M) -> (Pool<M>, Librarian<M>)
    where
        M: Manage,
    {
        let (sender, receiver) = mpsc::channel(capacity);

        let shared = Arc::new(Shared {
            capacity,
            shelf: ArrayQueue::new(capacity),
            checked_out_count: Semaphore::new(0),
            created_count: AtomicUsize::new(0),
            manager,
            recycle_interval: self.recycle_interval,
        });

        let pool = Pool {
            shared: shared.clone(),
            return_chute: sender,
        };
        let librarian = Librarian::new(shared, receiver);
        (pool, librarian)
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}