turnloop-io 0.1.0-beta.2

Shared async stream and sans-I/O driver glue for turnloop
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
//! Shared executor scheduling for sans-I/O connection pools. Policies stay in
//! protocol crates; this module owns sockets, waiter wakeups and absolute timers.
use crate::{Backend, ExecutorHandle, Instant, error};
use std::{
    cell::RefCell,
    future::{Future, poll_fn},
    io,
    ops::{Deref, DerefMut},
    pin::Pin,
    rc::Rc,
    task::{Context, Poll, Waker},
    time::Duration,
};
use turnloop::{Handle, JoinHandle, Sleep};

pub enum Action<I, L> {
    Connect(I),
    Close(I),
    Remove(I),
    Acquired { token: u64, lease: L },
    Failed { token: u64, error: io::Error },
    Ended,
}
pub trait Policy: 'static {
    type Id: Copy + Eq;
    type Lease: Copy;
    fn id(lease: Self::Lease) -> Self::Id;
    fn checkout(&mut self, token: u64, now: Instant, deadline: Instant) -> io::Result<()>;
    fn cancel(&mut self, token: u64, now: Instant);
    fn connected(&mut self, id: Self::Id, now: Instant) -> io::Result<()>;
    fn connect_failed(&mut self, id: Self::Id, now: Instant) -> io::Result<()>;
    fn checkin(&mut self, lease: Self::Lease, now: Instant, destroy: bool) -> io::Result<()>;
    fn closed(&mut self, id: Self::Id, now: Instant) -> io::Result<()>;
    fn event(&mut self) -> Option<Action<Self::Id, Self::Lease>>;
    fn next_deadline(&self) -> Option<Instant>;
    fn expire(&mut self, now: Instant);
    fn end(&mut self) -> io::Result<()>;
}
pub trait Connection: 'static {
    fn reusable(&self) -> bool;
    fn handle(&self) -> Option<Handle>;
}
pub trait Connector<B: Backend>: 'static {
    type Connection: Connection;
    fn connect(
        &self,
        executor: &ExecutorHandle<B>,
        deadline: Instant,
    ) -> impl Future<Output = io::Result<Self::Connection>> + 'static;
}
type Connecting<C> = Pin<Box<dyn Future<Output = io::Result<C>>>>;
struct Entry<B: Backend, I, C> {
    id: I,
    client: Option<C>,
    connecting: Option<Connecting<C>>,
    handle: Option<Handle>,
    closing: Option<turnloop::Close<B>>,
    closed: bool,
}
struct Waiter<L> {
    token: u64,
    result: Option<io::Result<L>>,
    waker: Option<Waker>,
}
struct State<B: Backend, P: Policy, C> {
    policy: P,
    entries: Vec<Entry<B, P::Id, C>>,
    waiters: Vec<Waiter<P::Lease>>,
    token: u64,
    changed: Option<Waker>,
    ended: bool,
    end_wakers: Vec<Waker>,
    failure: Option<String>,
}
struct Owner<B: Backend, P: Policy, C> {
    state: Rc<RefCell<State<B, P, C>>>,
    executor: ExecutorHandle<B>,
    _task: JoinHandle<()>,
}
/// Cloneable pool. Checkout and release reuse retained slots after warm-up.
pub struct Pool<B: Backend, P: Policy, C> {
    owner: Rc<Owner<B, P, C>>,
}
impl<B: Backend, P: Policy, C> Clone for Pool<B, P, C> {
    fn clone(&self) -> Self {
        Self {
            owner: self.owner.clone(),
        }
    }
}
fn wake(waker: &Option<Waker>) {
    if let Some(w) = waker {
        w.wake_by_ref();
    }
}
impl<B: Backend + 'static, P: Policy, C: Connection> Pool<B, P, C> {
    pub fn new<F: Connector<B, Connection = C>>(
        executor: &ExecutorHandle<B>,
        policy: P,
        connector: F,
        connect_timeout: Duration,
        capacity: usize,
    ) -> io::Result<Self> {
        let state = Rc::new(RefCell::new(State {
            policy,
            entries: Vec::with_capacity(capacity),
            waiters: Vec::with_capacity(capacity),
            token: 0,
            changed: None,
            ended: false,
            end_wakers: Vec::new(),
            failure: None,
        }));
        let shared = state.clone();
        let exec = executor.clone();
        let mut timer: Option<(Instant, Sleep<B>)> = None;
        let task = executor
            .spawn_local(poll_fn(move |cx| {
                let mut state = shared.borrow_mut();
                state.changed = Some(cx.waker().clone());
                let result = drive(
                    &mut state,
                    &exec,
                    &connector,
                    connect_timeout,
                    &mut timer,
                    cx,
                );
                if let Err(e) = result {
                    state.failure = Some(e.to_string());
                    for waiter in &state.waiters {
                        wake(&waiter.waker);
                    }
                    for w in &state.end_wakers {
                        w.wake_by_ref();
                    }
                    // Physical sockets close even if their client is currently leased.
                    for entry in &state.entries {
                        if let Some(h) = entry.handle {
                            let _ = exec.driver().close(h, turnloop::Token(0));
                        }
                    }
                    state.entries.clear();
                    return Poll::Ready(());
                }
                if state.ended && state.entries.is_empty() {
                    Poll::Ready(())
                } else {
                    Poll::Pending
                }
            }))
            .map_err(error)?;
        Ok(Self {
            owner: Rc::new(Owner {
                state,
                executor: executor.clone(),
                _task: task,
            }),
        })
    }
    pub fn total(&self) -> usize {
        self.owner.state.borrow().entries.len()
    }
    /// Apply a topology-driven policy change and wake the pool's scheduler.
    pub fn update_policy(&self, update: impl FnOnce(&mut P)) {
        let mut state = self.owner.state.borrow_mut();
        update(&mut state.policy);
        wake(&state.changed);
    }
    pub async fn acquire(&self, at: Instant) -> io::Result<Lease<B, P, C>> {
        let token = {
            let mut state = self.owner.state.borrow_mut();
            if let Some(e) = &state.failure {
                return Err(io::Error::other(e.clone()));
            }
            state.token = state
                .token
                .checked_add(1)
                .ok_or_else(|| io::Error::other("pool token exhausted"))?;
            let token = state.token;
            state
                .policy
                .checkout(token, self.owner.executor.now(), at)?;
            state.waiters.push(Waiter {
                token,
                result: None,
                waker: None,
            });
            wake(&state.changed);
            token
        };
        let mut pending = Pending {
            owner: &self.owner,
            token,
            done: false,
        };
        let result = crate::deadline(
            &self.owner.executor,
            at,
            poll_fn(|cx| {
                let mut state = self.owner.state.borrow_mut();
                if let Some(e) = &state.failure {
                    return Poll::Ready(Err(io::Error::other(e.clone())));
                }
                let Some(index) = state.waiters.iter().position(|w| w.token == token) else {
                    return Poll::Ready(Err(io::Error::other("missing pool waiter")));
                };
                if let Some(result) = state.waiters[index].result.take() {
                    state.waiters.swap_remove(index);
                    return Poll::Ready(result.and_then(|lease| {
                        let entry = state
                            .entries
                            .iter_mut()
                            .find(|e| e.id == P::id(lease))
                            .ok_or_else(|| io::Error::other("missing pooled connection"))?;
                        let client = entry
                            .client
                            .take()
                            .ok_or_else(|| io::Error::other("connection already leased"))?;
                        Ok(Lease {
                            owner: self.owner.clone(),
                            client: Some(client),
                            lease,
                        })
                    }));
                }
                state.waiters[index].waker = Some(cx.waker().clone());
                Poll::Pending
            }),
        )
        .await;
        pending.done = result.is_ok();
        result
    }
    pub async fn end(&self) -> io::Result<()> {
        {
            let mut state = self.owner.state.borrow_mut();
            state.policy.end()?;
            wake(&state.changed);
        }
        poll_fn(|cx| {
            let mut state = self.owner.state.borrow_mut();
            if let Some(e) = &state.failure {
                return Poll::Ready(Err(io::Error::other(e.clone())));
            }
            if state.ended && state.entries.is_empty() {
                return Poll::Ready(Ok(()));
            }
            if !state.end_wakers.iter().any(|w| w.will_wake(cx.waker())) {
                state.end_wakers.push(cx.waker().clone());
            }
            Poll::Pending
        })
        .await
    }
}
fn drive<B: Backend, P: Policy, C: Connection, F: Connector<B, Connection = C>>(
    state: &mut State<B, P, C>,
    executor: &ExecutorHandle<B>,
    connector: &F,
    timeout: Duration,
    timer: &mut Option<(Instant, Sleep<B>)>,
    cx: &mut Context<'_>,
) -> io::Result<()> {
    let now = executor.now();
    state.policy.expire(now);
    loop {
        while let Some(action) = state.policy.event() {
            match action {
                Action::Connect(id) => state.entries.push(Entry {
                    id,
                    client: None,
                    connecting: Some(Box::pin(connector.connect(executor, now + timeout))),
                    handle: None,
                    closing: None,
                    closed: false,
                }),
                Action::Close(id) => {
                    if let Some(entry) = state.entries.iter_mut().find(|e| e.id == id) {
                        if let Some(h) = entry.handle {
                            // Register physical-close observation before dropping the
                            // client; its destructor may independently request close.
                            entry.closing = Some(executor.close(h));
                        }
                        entry.client = None;
                        entry.connecting = None;
                        if entry.closing.is_none() {
                            entry.closed = true;
                            state.policy.closed(id, now)?;
                        }
                    } else {
                        state.policy.closed(id, now)?;
                    }
                }
                Action::Remove(id) => {
                    if let Some(i) = state.entries.iter().position(|e| e.id == id) {
                        state.entries.swap_remove(i);
                    }
                }
                Action::Acquired { token, lease } => {
                    if let Some(w) = state.waiters.iter_mut().find(|w| w.token == token) {
                        w.result = Some(Ok(lease));
                        wake(&w.waker);
                    } else {
                        state.policy.checkin(lease, now, true)?;
                    }
                }
                Action::Failed { token, error } => {
                    if let Some(w) = state.waiters.iter_mut().find(|w| w.token == token) {
                        w.result = Some(Err(error));
                        wake(&w.waker);
                    }
                }
                Action::Ended => {
                    state.ended = true;
                    for w in &state.end_wakers {
                        w.wake_by_ref();
                    }
                }
            }
        }
        let mut progressed = false;
        let closing = state.entries.iter().any(|entry| entry.closing.is_some());
        for entry in &mut state.entries {
            if let Some(future) = &mut entry.closing
                && let Poll::Ready(result) = Pin::new(future).poll(cx)
            {
                result.map_err(error)?;
                entry.closing = None;
                entry.closed = true;
                progressed = true;
                state.policy.closed(entry.id, now)?;
            }
            if !closing
                && let Some(future) = &mut entry.connecting
                && let Poll::Ready(result) = future.as_mut().poll(cx)
            {
                entry.connecting = None;
                progressed = true;
                match result {
                    Ok(client) => {
                        entry.handle = client.handle();
                        entry.client = Some(client);
                        state.policy.connected(entry.id, now)?;
                    }
                    Err(_) => state.policy.connect_failed(entry.id, now)?,
                }
            }
        }
        state.entries.retain(|entry| !entry.closed);
        if state.ended && state.entries.is_empty() {
            for w in &state.end_wakers {
                w.wake_by_ref();
            }
        }
        if !progressed {
            break;
        }
    }
    let at = state.policy.next_deadline();
    if timer.as_ref().map(|(at, _)| *at) != at {
        *timer = at.map(|at| (at, executor.sleep_until(at)));
    }
    if let Some((_, sleep)) = timer
        && let Poll::Ready(result) = Pin::new(sleep).poll(cx)
    {
        result.map_err(error)?;
        *timer = None;
        cx.waker().wake_by_ref();
    }
    Ok(())
}
struct Pending<'a, B: Backend, P: Policy, C> {
    owner: &'a Rc<Owner<B, P, C>>,
    token: u64,
    done: bool,
}
impl<B: Backend, P: Policy, C> Drop for Pending<'_, B, P, C> {
    fn drop(&mut self) {
        if !self.done {
            let mut state = self.owner.state.borrow_mut();
            if let Some(i) = state.waiters.iter().position(|w| w.token == self.token) {
                if let Some(Ok(lease)) = state.waiters.swap_remove(i).result {
                    let _ = state.policy.checkin(lease, self.owner.executor.now(), true);
                } else {
                    state.policy.cancel(self.token, self.owner.executor.now());
                }
            }
            wake(&state.changed);
        }
    }
}
/// Exclusive client ownership. A cancelled query makes reusable() false; release
/// then destroys the connection instead of handing wire state to another caller.
pub struct Lease<B: Backend, P: Policy, C: Connection> {
    owner: Rc<Owner<B, P, C>>,
    client: Option<C>,
    lease: P::Lease,
}
impl<B: Backend, P: Policy, C: Connection> Deref for Lease<B, P, C> {
    type Target = C;
    fn deref(&self) -> &C {
        self.client.as_ref().expect("owned lease")
    }
}
impl<B: Backend, P: Policy, C: Connection> DerefMut for Lease<B, P, C> {
    fn deref_mut(&mut self) -> &mut C {
        self.client.as_mut().expect("owned lease")
    }
}
impl<B: Backend, P: Policy, C: Connection> Drop for Lease<B, P, C> {
    fn drop(&mut self) {
        let mut state = self.owner.state.borrow_mut();
        if let Some(client) = self.client.take()
            && let Some(entry) = state.entries.iter_mut().find(|e| e.id == P::id(self.lease))
        {
            let destroy = !client.reusable();
            entry.client = Some(client);
            let _ = state
                .policy
                .checkin(self.lease, self.owner.executor.now(), destroy);
        }
        wake(&state.changed);
    }
}