tilo-actions 0.5.1

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store.
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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! A value an [`ActionProvider`](super::ActionProvider) produces later.
//!
//! Some answers need the owner of an action — an application that must
//! re-resolve a live directory row — and must not block the caller while it
//! does. [`Pending`] is that answer's receiving end, usable three ways
//! without tying the vocabulary to an async runtime: poll it from a frame
//! loop ([`Pending::poll_ready`]), await it (it is a [`Future`]), or attach a
//! continuation ([`Pending::then`]). Answers available immediately are
//! [`Pending::ready`].

use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak};
use std::task::{Context, Poll, Waker};
use std::time::Duration;
use tilo_lock::MutexRecover as _;

type Continuation<T> = Box<dyn FnOnce(Option<T>) + Send>;
/// Whether whoever a continuation hands the answer to still wants it.
type Interest = Box<dyn Fn() -> bool + Send>;

enum State<T> {
    Waiting {
        waker: Option<Waker>,
        then: Option<Continuation<T>>,
        /// Set with a continuation that only forwards the answer, so that
        /// abandoning the far end abandons this one too.
        interest: Option<Interest>,
    },
    /// Completed (`Some`) or abandoned by its producer (`None`).
    Done(Option<T>),
    Taken,
}

struct Slot<T> {
    state: Mutex<State<T>>,
    settled: Condvar,
    /// Wakes [`Completer::abandoned`] when the receiving end goes away.
    abandon: Arc<AbandonSignal>,
}

/// Where the receiving end of a [`Pending`] reports that it went away.
///
/// It is shared by the slot and the [`Pending`] that reads it, but holds no
/// reference to the slot itself: the producer decides abandonment by the
/// slot's strong count, which a wake-up must not inflate.
#[derive(Default)]
struct AbandonSignal {
    wake: Mutex<AbandonWake>,
}

#[derive(Default)]
struct AbandonWake {
    /// The task waiting in [`Completer::abandoned`].
    waker: Option<Waker>,
    /// The signal of the answer this one forwards to
    /// through [`Pending::map`]: dropping the mapped answer may abandon that one.
    upstream: Option<Arc<AbandonSignal>>,
}

impl AbandonSignal {
    fn register(&self, waker: &Waker) {
        let mut wake = self.wake.lock_recover();
        if !wake
            .waker
            .as_ref()
            .is_some_and(|current| current.will_wake(waker))
        {
            wake.waker = Some(waker.clone());
        }
    }

    fn forward_to(&self, upstream: Arc<Self>) {
        self.wake.lock_recover().upstream = Some(upstream);
    }

    /// Wake whoever waits on this answer's abandonment, and on every answer
    /// it forwards to. The waiter re-checks, so a wake that turns out not
    /// to abandon anything is harmless.
    fn wake(&self) {
        let (waker, upstream) = {
            let wake = self.wake.lock_recover();
            (wake.waker.clone(), wake.upstream.clone())
        };
        if let Some(waker) = waker {
            waker.wake();
        }
        if let Some(upstream) = upstream {
            upstream.wake();
        }
    }
}

/// Held by a [`Pending`] after its slot: dropping the `Pending` first
/// releases the slot, then wakes the producer, which then observes the
/// lower strong count.
struct AbandonOnDrop(Arc<AbandonSignal>);

impl Drop for AbandonOnDrop {
    fn drop(&mut self) {
        self.0.wake();
    }
}

impl<T> Slot<T> {
    fn settle(&self, value: Option<T>) {
        let mut state = self.state.lock_recover();
        match std::mem::replace(&mut *state, State::Taken) {
            State::Waiting {
                then: Some(then), ..
            } => {
                drop(state);
                then(value);
            }
            State::Waiting {
                waker, then: None, ..
            } => {
                *state = State::Done(value);
                drop(state);
                self.settled.notify_all();
                if let Some(waker) = waker {
                    waker.wake();
                }
            }
            already => *state = already,
        }
    }

    /// Whether nobody can observe this answer any more. `own` is how many
    /// strong references the asking side itself holds.
    fn abandoned(slot: &Arc<Self>, own: usize) -> bool {
        if Arc::strong_count(slot) > own {
            return false;
        }
        let state = slot.state.lock_recover();
        match &*state {
            State::Waiting {
                then: Some(_),
                interest,
                ..
            } => interest.as_ref().is_some_and(|wanted| !wanted()),
            State::Waiting { then: None, .. } | State::Done(_) | State::Taken => true,
        }
    }
}

/// The producing end of a [`Pending`]. Dropping it without completing
/// abandons the answer, which the receiving end observes.
pub struct Completer<T> {
    slot: Option<Arc<Slot<T>>>,
}

/// The receiving end: an answer that may not exist yet.
pub struct Pending<T> {
    // Field order matters: `slot` drops before `_abandon` wakes the
    // producer, so the producer sees the slot released.
    slot: Arc<Slot<T>>,
    _abandon: AbandonOnDrop,
}

#[must_use]
pub fn pending<T>() -> (Completer<T>, Pending<T>) {
    let abandon = Arc::new(AbandonSignal::default());
    let slot = Arc::new(Slot {
        state: Mutex::new(State::Waiting {
            waker: None,
            then: None,
            interest: None,
        }),
        settled: Condvar::new(),
        abandon: Arc::clone(&abandon),
    });
    (
        Completer {
            slot: Some(Arc::clone(&slot)),
        },
        Pending {
            slot,
            _abandon: AbandonOnDrop(abandon),
        },
    )
}

impl<T> Completer<T> {
    /// Whether nobody is waiting any more: the [`Pending`] was dropped —
    /// or, through [`Pending::map`], the mapped answer was — so the work
    /// behind this answer may be skipped.
    #[must_use]
    pub fn is_abandoned(&self) -> bool {
        self.slot
            .as_ref()
            .is_none_or(|slot| Slot::abandoned(slot, 1))
    }

    /// Resolves once nobody can observe the answer any more — what
    /// [`Self::is_abandoned`] reports, as a future, so work behind the
    /// answer can stop the moment its asker goes away instead of checking
    /// on a timer. Runtime-agnostic: dropping the [`Pending`] (or, through
    /// [`Pending::map`], the mapped answer) wakes it. An answer handed to a
    /// plain [`Pending::then`] continuation is always wanted, so this never
    /// resolves for it.
    pub fn abandoned(&self) -> Abandoned<'_, T> {
        Abandoned { completer: self }
    }

    /// Deliver the answer. A continuation attached with
    /// [`Pending::then`] runs here, on the completing thread.
    pub fn complete(mut self, value: T) {
        if let Some(slot) = self.slot.take() {
            slot.settle(Some(value));
        }
    }
}

impl<T> Drop for Completer<T> {
    fn drop(&mut self) {
        if let Some(slot) = self.slot.take() {
            slot.settle(None);
        }
    }
}

/// [`Completer::abandoned`] — resolves once the answer is unobservable.
#[must_use = "a future does nothing unless awaited"]
pub struct Abandoned<'a, T> {
    completer: &'a Completer<T>,
}

impl<T> Future for Abandoned<'_, T> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<()> {
        let Some(slot) = self.completer.slot.as_ref() else {
            return Poll::Ready(());
        };
        if Slot::abandoned(slot, 1) {
            return Poll::Ready(());
        }
        slot.abandon.register(context.waker());
        // The receiving end may have gone between the check and the
        // registration; it woke nobody then, so look again.
        if Slot::abandoned(slot, 1) {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    }
}

/// What [`Pending::poll_ready`] found.
#[derive(Debug, PartialEq, Eq)]
pub enum PendingPoll<T> {
    Ready(T),
    Waiting,
    /// The producer went away without answering.
    Abandoned,
}

impl<T> Pending<T> {
    /// An answer that is already known.
    #[must_use]
    pub fn ready(value: T) -> Self {
        let abandon = Arc::new(AbandonSignal::default());
        Self {
            slot: Arc::new(Slot {
                state: Mutex::new(State::Done(Some(value))),
                settled: Condvar::new(),
                abandon: Arc::clone(&abandon),
            }),
            _abandon: AbandonOnDrop(abandon),
        }
    }

    /// Take the answer if it has arrived, without waiting.
    pub fn poll_ready(&mut self) -> PendingPoll<T> {
        let mut state = self.slot.state.lock_recover();
        match std::mem::replace(&mut *state, State::Taken) {
            State::Done(Some(value)) => PendingPoll::Ready(value),
            State::Done(None) | State::Taken => PendingPoll::Abandoned,
            waiting @ State::Waiting { .. } => {
                *state = waiting;
                PendingPoll::Waiting
            }
        }
    }

    /// Block the calling thread until the answer arrives or `timeout`
    /// passes. For threads that do not drive the answer's producer.
    pub fn wait_timeout(mut self, timeout: Duration) -> Result<Option<T>, Self> {
        let deadline = tilo_clock::now().checked_add(timeout);
        let mut state = self.slot.state.lock_recover();
        loop {
            if !matches!(*state, State::Waiting { .. }) {
                drop(state);
                return Ok(match self.poll_ready() {
                    PendingPoll::Ready(value) => Some(value),
                    PendingPoll::Waiting | PendingPoll::Abandoned => None,
                });
            }
            let remaining = deadline.map_or(timeout, |deadline| {
                deadline.saturating_duration_since(tilo_clock::now())
            });
            if remaining.is_zero() {
                drop(state);
                return Err(self);
            }
            state = self
                .slot
                .settled
                .wait_timeout(state, remaining)
                .unwrap_or_else(PoisonError::into_inner)
                .0;
        }
    }

    /// Run `then` with the answer once it exists — immediately if it
    /// already does. `None` means the producer abandoned it.
    pub fn then(self, then: impl FnOnce(Option<T>) + Send + 'static) {
        self.then_while(then, None);
    }

    fn then_while(self, then: impl FnOnce(Option<T>) + Send + 'static, interest: Option<Interest>) {
        let mut state = self.slot.state.lock_recover();
        match std::mem::replace(&mut *state, State::Taken) {
            State::Waiting { waker, .. } => {
                *state = State::Waiting {
                    waker,
                    then: Some(Box::new(then)),
                    interest,
                };
            }
            State::Done(value) => {
                drop(state);
                then(value);
            }
            State::Taken => {
                drop(state);
                then(None);
            }
        }
    }
}

impl<T: Send + 'static> Pending<T> {
    /// The answer, transformed once it arrives.
    #[must_use]
    pub fn map<U: Send + 'static>(self, map: impl FnOnce(T) -> U + Send + 'static) -> Pending<U> {
        let (completer, mapped) = pending();
        // Dropping the mapped answer wakes whoever waits on this one's
        // abandonment, which `wanted` then reports.
        mapped
            .slot
            .abandon
            .forward_to(Arc::clone(&self.slot.abandon));
        let far_end = completer.slot.as_ref().map(Arc::downgrade);
        // Upgrading adds one reference to the completer's own.
        let wanted = move || {
            far_end
                .as_ref()
                .and_then(Weak::upgrade)
                .is_some_and(|slot| !Slot::abandoned(&slot, 2))
        };
        self.then_while(
            move |value| {
                if let Some(value) = value {
                    completer.complete(map(value));
                }
            },
            Some(Box::new(wanted)),
        );
        mapped
    }
}

impl<T> Future for Pending<T> {
    /// `None` if the producer abandoned the answer.
    type Output = Option<T>;

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<T>> {
        let this = self.get_mut();
        let mut state = this.slot.state.lock_recover();
        match std::mem::replace(&mut *state, State::Taken) {
            State::Done(value) => Poll::Ready(value),
            State::Taken => Poll::Ready(None),
            State::Waiting { then, interest, .. } => {
                *state = State::Waiting {
                    waker: Some(context.waker().clone()),
                    then,
                    interest,
                };
                Poll::Pending
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Counts how often a producer waiting on abandonment is woken.
    struct CountingWaker(std::sync::atomic::AtomicUsize);

    impl std::task::Wake for CountingWaker {
        fn wake(self: Arc<Self>) {
            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        }
    }

    impl CountingWaker {
        fn woken(&self) -> usize {
            self.0.load(std::sync::atomic::Ordering::SeqCst)
        }
    }

    tilo_test_env::scenario! {
        fn a_pending_answer_wakes_whoever_waits_on_it;

        phase a_pending_answer_resolves_however_it_is_waited_on;
        // A pending answer is polled, awaited or continued; dropping a mapped answer abandons the
        // original; waiting across threads sees the answer or times out; a ready answer resolves as a
        // future without a runtime.
        // Runs each phase below in order; every phase builds its own fixture.
        {
            a_pending_answer_is_polled_awaited_or_continued();
            dropping_a_mapped_answer_abandons_the_original();
            waiting_across_threads_sees_the_answer_or_times_out();
            a_ready_answer_resolves_as_a_future_without_a_runtime();
        }

        phase dropping_the_asker_wakes_a_producer_waiting_on_abandonment;
        // The producer of an answer learns that its asker went away the moment
        // it does, as a wake-up rather than by checking again later: dropping
        // the answer, or the answer mapped from it, wakes
        // [`Completer::abandoned`]; an answer a plain continuation took stays
        // wanted. No runtime is involved.
        {
            let counter = Arc::new(CountingWaker(std::sync::atomic::AtomicUsize::new(0)));
            let waker = Waker::from(Arc::clone(&counter));
            let mut context = Context::from_waker(&waker);

            let (completer, answer) = pending::<u8>();
            let mut abandoned = std::pin::pin!(completer.abandoned());
            assert_eq!(abandoned.as_mut().poll(&mut context), Poll::Pending);
            assert_eq!(counter.woken(), 0, "nothing happened yet");
            drop(answer);
            assert_eq!(counter.woken(), 1, "dropping the answer wakes its producer");
            assert_eq!(abandoned.as_mut().poll(&mut context), Poll::Ready(()));

            let (completer, answer) = pending::<u8>();
            let mapped = answer.map(|value| value.saturating_add(1));
            let mut abandoned = std::pin::pin!(completer.abandoned());
            assert_eq!(abandoned.as_mut().poll(&mut context), Poll::Pending);
            let before = counter.woken();
            drop(mapped);
            assert!(
                counter.woken() > before,
                "dropping the mapped answer wakes the original producer"
            );
            assert_eq!(abandoned.as_mut().poll(&mut context), Poll::Ready(()));

            let (completer, answer) = pending::<u8>();
            answer.then(|_| {});
            let mut abandoned = std::pin::pin!(completer.abandoned());
            assert_eq!(
                abandoned.as_mut().poll(&mut context),
                Poll::Pending,
                "a plain continuation always wants the answer"
            );

            let (completer, answer) = pending::<u8>();
            drop(answer);
            let mut abandoned = std::pin::pin!(completer.abandoned());
            assert_eq!(
                abandoned.as_mut().poll(&mut context),
                Poll::Ready(()),
                "an answer dropped before anyone waited is already abandoned"
            );
        }

        phase a_producer_on_another_thread_wakes_when_the_asker_drops_the_answer;
        // A producer on another thread wakes as soon as the asker drops the
        // answer, with nothing polling in between.
        {
            let (completer, answer) = pending::<u8>();
            let (parked, ready) = std::sync::mpsc::channel();
            let producer = std::thread::spawn(move || {
                struct Unpark(std::thread::Thread);
                impl std::task::Wake for Unpark {
                    fn wake(self: Arc<Self>) {
                        self.0.unpark();
                    }
                }
                let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
                let mut context = Context::from_waker(&waker);
                let mut abandoned = std::pin::pin!(completer.abandoned());
                let mut announced = false;
                let deadline = tilo_test_env::hang_deadline();
                loop {
                    if abandoned.as_mut().poll(&mut context).is_ready() {
                        return true;
                    }
                    if !announced {
                        parked.send(()).expect("announce parking");
                        announced = true;
                    }
                    let remaining = deadline.saturating_duration_since(tilo_clock::now());
                    if remaining.is_zero() {
                        return false;
                    }
                    std::thread::park_timeout(remaining);
                }
            });
            ready
                .recv_timeout(tilo_test_env::hang_bound())
                .expect("the producer waits");
            drop(answer);
            assert!(
                producer.join().expect("producer thread"),
                "the producer saw its asker go away"
            );
        }
    }

    #[allow(
        clippy::arithmetic_side_effects,
        reason = "test phase: arithmetic on small fixed test values cannot overflow"
    )]
    fn a_pending_answer_is_polled_awaited_or_continued() {
        let (completer, mut answer) = pending::<u32>();
        assert_eq!(answer.poll_ready(), PendingPoll::Waiting);
        completer.complete(7);
        assert_eq!(answer.poll_ready(), PendingPoll::Ready(7));
        assert_eq!(answer.poll_ready(), PendingPoll::Abandoned);

        let (completer, answer) = pending::<u32>();
        let doubled = answer.map(|value| value * 2);
        completer.complete(21);
        assert_eq!(doubled.wait_timeout(Duration::ZERO).ok(), Some(Some(42)));

        let (completer, mut answer) = pending::<u32>();
        drop(completer);
        assert_eq!(answer.poll_ready(), PendingPoll::Abandoned);
    }

    #[allow(
        clippy::arithmetic_side_effects,
        reason = "test phase: arithmetic on small fixed test values cannot overflow"
    )]
    fn dropping_a_mapped_answer_abandons_the_original() {
        let (completer, answer) = pending::<u32>();
        let mapped = answer.map(|value| value + 1);
        assert!(!completer.is_abandoned());
        drop(mapped);
        assert!(completer.is_abandoned());

        let (completer, answer) = pending::<u32>();
        answer.then(|_| {});
        assert!(
            !completer.is_abandoned(),
            "a plain continuation always wants the answer"
        );
    }

    fn waiting_across_threads_sees_the_answer_or_times_out() {
        let (completer, answer) = pending::<&'static str>();
        let answer = answer
            .wait_timeout(Duration::from_millis(10))
            .expect_err("nothing has answered yet");
        let producer = std::thread::spawn(move || completer.complete("done"));
        assert_eq!(
            answer.wait_timeout(tilo_test_env::hang_bound()).ok(),
            Some(Some("done"))
        );
        producer.join().expect("producer thread");
    }

    fn a_ready_answer_resolves_as_a_future_without_a_runtime() {
        let waker = Waker::noop();
        let mut context = Context::from_waker(waker);
        let mut ready = Pending::ready(3_u8);
        assert_eq!(
            Pin::new(&mut ready).poll(&mut context),
            Poll::Ready(Some(3))
        );
        let (completer, mut waiting) = pending::<u8>();
        assert_eq!(Pin::new(&mut waiting).poll(&mut context), Poll::Pending);
        completer.complete(4);
        assert_eq!(
            Pin::new(&mut waiting).poll(&mut context),
            Poll::Ready(Some(4))
        );
    }
}