compio-pool 0.0.2

A thread-per-core connection pool for the compio runtime
Documentation
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
//! Per-thread state. Never shared across threads, so it uses `Cell`/`RefCell`
//! and plain `Rc` — no atomics on the acquire fast path.

use std::{
    cell::{Cell, RefCell},
    collections::VecDeque,
    future::Future,
    pin::Pin,
    rc::Rc,
    sync::{Arc, atomic::Ordering::Relaxed},
    task::{Context, Poll, Waker},
};

use crate::{config::Config, manage::Manage, metrics::Counters, slot::Slot};

/// One parked `acquire` on this thread.
struct Waiter {
    notified: Cell<bool>,
    waker: RefCell<Option<Waker>>,
}

/// A single compio thread's slice of the pool.
pub(crate) struct Shard<M: Manage> {
    /// Idle connections, LIFO: the most recently returned is the warmest.
    free: RefCell<Vec<Slot<M::Connection>>>,
    /// Connections this thread owns, idle *and* checked out.
    size: Cell<usize>,
    waiters: RefCell<VecDeque<Rc<Waiter>>>,
    counters: Arc<Counters>,
    manager: Arc<M>,
}

impl<M: Manage> Shard<M> {
    pub(crate) fn new(counters: Arc<Counters>, manager: Arc<M>) -> Self {
        Self {
            free: RefCell::new(Vec::new()),
            size: Cell::new(0),
            waiters: RefCell::new(VecDeque::new()),
            counters,
            manager,
        }
    }

    pub(crate) fn idle_len(&self) -> usize {
        self.free.borrow().len()
    }

    pub(crate) fn size(&self) -> usize {
        self.size.get()
    }

    pub(crate) fn has_waiters(&self) -> bool {
        !self.waiters.borrow().is_empty()
    }

    /// Takes the warmest idle connection, if any. Does **not** check expiry;
    /// the caller does that, because discarding needs the manager.
    pub(crate) fn pop_idle(&self) -> Option<Slot<M::Connection>> {
        let slot = self.free.borrow_mut().pop();
        if slot.is_some() {
            Counters::dec(&self.counters.idle);
        }
        slot
    }

    pub(crate) fn push_idle(&self, slot: Slot<M::Connection>) {
        self.free.borrow_mut().push(slot);
        Counters::inc(&self.counters.idle);
        self.wake_one();
    }

    /// Claims budget for one more connection on this thread.
    ///
    /// `max_size` is per-shard by design — see [`Config`](crate::Config).
    pub(crate) fn try_reserve(&self, max_size: usize) -> bool {
        if self.size.get() < max_size {
            self.size.set(self.size.get() + 1);
            true
        } else {
            false
        }
    }

    /// Gives back budget claimed by `try_reserve`, waking one waiter.
    pub(crate) fn release(&self) {
        self.size.set(self.size.get().saturating_sub(1));
        self.wake_one();
    }

    /// Removes every idle connection that has aged out, returning them so the
    /// caller can run `Manage::disconnect` on each.
    pub(crate) fn drain_expired(&self, cfg: &Config, generation: u64) -> Vec<Slot<M::Connection>> {
        let mut free = self.free.borrow_mut();
        let mut expired = Vec::new();
        let mut i = 0;
        while i < free.len() {
            if free[i].is_expired(cfg, generation) {
                expired.push(free.swap_remove(i));
            } else {
                i += 1;
            }
        }
        self.counters.idle.fetch_sub(expired.len() as u64, Relaxed);
        expired
    }

    /// Empties the free list, for `Pool::close`.
    pub(crate) fn drain_all(&self) -> Vec<Slot<M::Connection>> {
        let drained: Vec<_> = self.free.borrow_mut().drain(..).collect();
        self.counters.idle.fetch_sub(drained.len() as u64, Relaxed);
        drained
    }

    fn wake_one(&self) {
        let waiter = self.waiters.borrow_mut().pop_front();
        if let Some(w) = waiter {
            w.notified.set(true);
            let waker = w.waker.borrow_mut().take();
            if let Some(waker) = waker {
                waker.wake();
            }
        }
    }

    /// Waits until a connection is returned or budget frees up on this thread.
    ///
    /// Cross-thread wakeups are deliberately not part of this: a thread that is
    /// at `max_size` has outstanding connections *of its own* that will come
    /// back, so waiting locally always makes progress.
    pub(crate) fn wait(&self) -> WaitForSlot<'_, M> {
        WaitForSlot {
            shard: self,
            waiter: None,
        }
    }
}

impl<M: Manage> Drop for Shard<M> {
    fn drop(&mut self) {
        // Reached at thread exit. Every `Pooled` guard holds an `Rc<Shard>`, so
        // by construction nothing is checked out here — `size` is all idle.
        //
        // This runs on the thread whose compio driver owns these connections,
        // which is the only thread allowed to close them.
        let n = self.size.get() as u64;
        let idle: Vec<_> = self.free.borrow_mut().drain(..).collect();
        self.counters.idle.fetch_sub(idle.len() as u64, Relaxed);
        for slot in idle {
            self.manager.disconnect(slot.conn);
        }
        self.counters.live.fetch_sub(n, Relaxed);
        self.counters.closed.fetch_add(n, Relaxed);
    }
}

/// Future returned by [`Shard::wait`].
pub(crate) struct WaitForSlot<'a, M: Manage> {
    shard: &'a Shard<M>,
    waiter: Option<Rc<Waiter>>,
}

impl<M: Manage> Future for WaitForSlot<'_, M> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        let this = self.get_mut();
        match &this.waiter {
            None => {
                let waiter = Rc::new(Waiter {
                    notified: Cell::new(false),
                    waker: RefCell::new(Some(cx.waker().clone())),
                });
                this.shard.waiters.borrow_mut().push_back(waiter.clone());
                this.waiter = Some(waiter);
                Poll::Pending
            }
            Some(waiter) => {
                if waiter.notified.get() {
                    // Clear it so `Drop` knows the wakeup was consumed.
                    this.waiter = None;
                    Poll::Ready(())
                } else {
                    *waiter.waker.borrow_mut() = Some(cx.waker().clone());
                    Poll::Pending
                }
            }
        }
    }
}

impl<M: Manage> Drop for WaitForSlot<'_, M> {
    fn drop(&mut self) {
        let Some(waiter) = self.waiter.take() else {
            return;
        };
        if waiter.notified.get() {
            // We were handed a wakeup but are being cancelled (acquire timeout,
            // or the caller's future was dropped). Passing it on is mandatory:
            // the connection that triggered it is idle, and if we swallow the
            // notification the next waiter sleeps until its own timeout.
            self.shard.wake_one();
        } else {
            let mut queue = self.shard.waiters.borrow_mut();
            if let Some(pos) = queue.iter().position(|w| Rc::ptr_eq(w, &waiter)) {
                queue.remove(pos);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::task::Context;

    use super::*;
    use crate::{
        slot::Slot,
        test_support::{Counts, TestConn, TestManager, counting_waker},
    };

    /// A shard wired to fresh counters, plus handles to observe both.
    fn shard() -> (Rc<Shard<TestManager>>, Arc<Counters>, Arc<Counts>) {
        let manager = Arc::new(TestManager::new());
        let counts = manager.counts();
        let counters = Arc::new(Counters::default());
        (
            Rc::new(Shard::new(counters.clone(), manager)),
            counters,
            counts,
        )
    }

    fn slot(id: u64, generation: u64) -> Slot<TestConn> {
        Slot::new(TestConn::new(id), generation)
    }

    fn untimed() -> Config {
        Config::new().max_lifetime(None).idle_timeout(None)
    }

    #[test]
    fn a_new_shard_is_empty() {
        let (shard, counters, _) = shard();
        assert_eq!(shard.size(), 0);
        assert_eq!(shard.idle_len(), 0);
        assert!(!shard.has_waiters());
        assert_eq!(counters.idle.load(Relaxed), 0);
    }

    #[test]
    fn push_and_pop_track_the_idle_gauge() {
        let (shard, counters, _) = shard();

        shard.push_idle(slot(0, 0));
        shard.push_idle(slot(1, 0));
        assert_eq!(shard.idle_len(), 2);
        assert_eq!(counters.idle.load(Relaxed), 2);

        let popped = shard.pop_idle().expect("two were pushed");
        assert_eq!(popped.conn.id, 1, "LIFO: the warmest comes back first");
        assert_eq!(counters.idle.load(Relaxed), 1);
    }

    #[test]
    fn popping_an_empty_free_list_leaves_the_gauge_alone() {
        let (shard, counters, _) = shard();
        assert!(shard.pop_idle().is_none());
        assert_eq!(
            counters.idle.load(Relaxed),
            0,
            "a miss must not decrement past zero"
        );
    }

    #[test]
    fn try_reserve_stops_at_max_size() {
        let (shard, _, _) = shard();

        assert!(shard.try_reserve(2));
        assert!(shard.try_reserve(2));
        assert!(!shard.try_reserve(2), "max_size is a hard per-shard cap");
        assert_eq!(shard.size(), 2, "a refused reservation must not count");
    }

    #[test]
    fn release_gives_budget_back() {
        let (shard, _, _) = shard();
        assert!(shard.try_reserve(1));
        shard.release();
        assert_eq!(shard.size(), 0);
        assert!(shard.try_reserve(1), "the slot is usable again");
    }

    /// `release` saturates rather than wrapping: a bookkeeping slip must not
    /// turn `size` into `usize::MAX` and wedge the shard forever.
    #[test]
    fn releasing_an_empty_shard_saturates() {
        let (shard, _, _) = shard();
        shard.release();
        assert_eq!(shard.size(), 0);
    }

    #[test]
    fn drain_expired_removes_only_the_stale_slots() {
        let (shard, counters, _) = shard();
        // Generation is the easiest expiry knob to drive deterministically.
        for (id, generation) in [(0, 0), (1, 1), (2, 0), (3, 1)] {
            shard.push_idle(slot(id, generation));
        }

        let expired = shard.drain_expired(&untimed(), 1);

        let mut ids: Vec<_> = expired.iter().map(|s| s.conn.id).collect();
        ids.sort();
        assert_eq!(ids, vec![0, 2], "only the older generation goes");
        assert_eq!(shard.idle_len(), 2);
        assert_eq!(counters.idle.load(Relaxed), 2, "the gauge follows");
    }

    #[test]
    fn drain_expired_keeps_everything_when_nothing_aged_out() {
        let (shard, counters, _) = shard();
        shard.push_idle(slot(0, 0));
        shard.push_idle(slot(1, 0));

        assert!(shard.drain_expired(&untimed(), 0).is_empty());
        assert_eq!(shard.idle_len(), 2);
        assert_eq!(counters.idle.load(Relaxed), 2);
    }

    #[test]
    fn drain_all_empties_the_free_list() {
        let (shard, counters, _) = shard();
        shard.push_idle(slot(0, 0));
        shard.push_idle(slot(1, 0));

        assert_eq!(shard.drain_all().len(), 2);
        assert_eq!(shard.idle_len(), 0);
        assert_eq!(counters.idle.load(Relaxed), 0);
        assert!(shard.drain_all().is_empty(), "draining twice is harmless");
    }

    #[test]
    fn waking_with_no_waiters_is_a_no_op() {
        let (shard, _, _) = shard();
        shard.push_idle(slot(0, 0)); // push_idle wakes one; there is nobody
        shard.release();
        assert_eq!(shard.idle_len(), 1);
    }

    #[test]
    fn a_waiter_is_registered_and_then_woken_by_a_returned_connection() {
        let (shard, _, _) = shard();
        let (woken, waker) = counting_waker();
        let mut cx = Context::from_waker(&waker);
        let mut fut = Box::pin(shard.wait());

        // First poll registers; there is nothing to hand out yet.
        assert!(fut.as_mut().poll(&mut cx).is_pending());
        assert!(shard.has_waiters());
        assert_eq!(woken.count(), 0);

        // A spurious re-poll must stay pending and keep the waiter queued.
        assert!(fut.as_mut().poll(&mut cx).is_pending());
        assert!(shard.has_waiters());

        shard.push_idle(slot(0, 0));
        assert_eq!(woken.count(), 1, "push_idle must wake a waiter");
        assert!(!shard.has_waiters(), "wake_one dequeues as it notifies");
        assert!(fut.as_mut().poll(&mut cx).is_ready());
    }

    #[test]
    fn freeing_budget_also_wakes_a_waiter() {
        let (shard, _, _) = shard();
        let (woken, waker) = counting_waker();
        let mut cx = Context::from_waker(&waker);
        let mut fut = Box::pin(shard.wait());
        assert!(fut.as_mut().poll(&mut cx).is_pending());

        // Not only returned connections: budget freed by a destroyed one counts.
        shard.release();
        assert_eq!(woken.count(), 1);
        assert!(fut.as_mut().poll(&mut cx).is_ready());
    }

    #[test]
    fn a_waiter_dropped_before_being_woken_leaves_the_queue() {
        let (shard, _, _) = shard();
        let (_woken, waker) = counting_waker();
        let mut cx = Context::from_waker(&waker);

        let mut fut = Box::pin(shard.wait());
        assert!(fut.as_mut().poll(&mut cx).is_pending());
        assert!(shard.has_waiters());

        drop(fut);
        assert!(
            !shard.has_waiters(),
            "an abandoned waiter must not keep receiving wakeups"
        );
    }

    /// The wakeup is a resource: whoever cannot use it has to pass it on, or the
    /// idle connection that caused it sits there while the next waiter sleeps.
    #[test]
    fn a_notified_but_cancelled_waiter_forwards_its_wakeup() {
        let (shard, _, _) = shard();
        let (first_woken, first_waker) = counting_waker();
        let (second_woken, second_waker) = counting_waker();

        let mut first = Box::pin(shard.wait());
        let mut second = Box::pin(shard.wait());
        assert!(
            first
                .as_mut()
                .poll(&mut Context::from_waker(&first_waker))
                .is_pending()
        );
        assert!(
            second
                .as_mut()
                .poll(&mut Context::from_waker(&second_waker))
                .is_pending()
        );

        // FIFO: the notification goes to `first`, which is then cancelled.
        shard.release();
        assert_eq!(first_woken.count(), 1);
        assert_eq!(second_woken.count(), 0);

        drop(first);
        assert_eq!(second_woken.count(), 1, "the wakeup was handed along");
        assert!(
            second
                .as_mut()
                .poll(&mut Context::from_waker(&second_waker))
                .is_ready()
        );
    }

    #[test]
    fn a_waiter_dropped_without_ever_being_polled_is_harmless() {
        let (shard, _, _) = shard();
        drop(shard.wait());
        assert!(!shard.has_waiters());
    }

    /// A completed `WaitForSlot` has already cleared its waiter, so its `Drop`
    /// must not forward a second wakeup.
    #[test]
    fn a_consumed_wakeup_is_not_forwarded_twice() {
        let (shard, _, _) = shard();
        let (first_woken, first_waker) = counting_waker();
        let (second_woken, second_waker) = counting_waker();

        let mut first = Box::pin(shard.wait());
        assert!(
            first
                .as_mut()
                .poll(&mut Context::from_waker(&first_waker))
                .is_pending()
        );
        shard.release();
        assert!(
            first
                .as_mut()
                .poll(&mut Context::from_waker(&first_waker))
                .is_ready()
        );

        let mut second = Box::pin(shard.wait());
        assert!(
            second
                .as_mut()
                .poll(&mut Context::from_waker(&second_waker))
                .is_pending()
        );
        drop(first);
        assert_eq!(
            second_woken.count(),
            0,
            "the first waiter already used its wakeup"
        );
        assert_eq!(first_woken.count(), 1);
    }

    /// At thread exit the shard closes what it holds — on the thread whose
    /// driver owns those handles — and squares the global gauges.
    #[test]
    fn dropping_a_shard_closes_its_idle_connections() {
        let (shard, counters, counts) = shard();
        counters.live.store(2, Relaxed);
        assert!(shard.try_reserve(2));
        assert!(shard.try_reserve(2));
        shard.push_idle(slot(0, 0));
        shard.push_idle(slot(1, 0));

        drop(shard);

        assert_eq!(counts.disconnected(), 2, "closed through the manager");
        assert_eq!(counters.idle.load(Relaxed), 0);
        assert_eq!(counters.live.load(Relaxed), 0);
        assert_eq!(counters.closed.load(Relaxed), 2);
    }

    #[test]
    fn dropping_an_untouched_shard_changes_nothing() {
        let (shard, counters, counts) = shard();
        drop(shard);
        assert_eq!(counts.disconnected(), 0);
        assert_eq!(counters.closed.load(Relaxed), 0);
    }
}