Skip to main content

tilo_actions/remote/
pending.rs

1//! A value an [`ActionProvider`](super::ActionProvider) produces later.
2//!
3//! Some answers need the owner of an action — an application that must
4//! re-resolve a live directory row — and must not block the caller while it
5//! does. [`Pending`] is that answer's receiving end, usable three ways
6//! without tying the vocabulary to an async runtime: poll it from a frame
7//! loop ([`Pending::poll_ready`]), await it (it is a [`Future`]), or attach a
8//! continuation ([`Pending::then`]). Answers available immediately are
9//! [`Pending::ready`].
10
11use std::future::Future;
12use std::pin::Pin;
13use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak};
14use std::task::{Context, Poll, Waker};
15use std::time::Duration;
16use tilo_lock::MutexRecover as _;
17
18type Continuation<T> = Box<dyn FnOnce(Option<T>) + Send>;
19/// Whether whoever a continuation hands the answer to still wants it.
20type Interest = Box<dyn Fn() -> bool + Send>;
21
22enum State<T> {
23    Waiting {
24        waker: Option<Waker>,
25        then: Option<Continuation<T>>,
26        /// Set with a continuation that only forwards the answer, so that
27        /// abandoning the far end abandons this one too.
28        interest: Option<Interest>,
29    },
30    /// Completed (`Some`) or abandoned by its producer (`None`).
31    Done(Option<T>),
32    Taken,
33}
34
35struct Slot<T> {
36    state: Mutex<State<T>>,
37    settled: Condvar,
38    /// Wakes [`Completer::abandoned`] when the receiving end goes away.
39    abandon: Arc<AbandonSignal>,
40}
41
42/// Where the receiving end of a [`Pending`] reports that it went away.
43///
44/// It is shared by the slot and the [`Pending`] that reads it, but holds no
45/// reference to the slot itself: the producer decides abandonment by the
46/// slot's strong count, which a wake-up must not inflate.
47#[derive(Default)]
48struct AbandonSignal {
49    wake: Mutex<AbandonWake>,
50}
51
52#[derive(Default)]
53struct AbandonWake {
54    /// The task waiting in [`Completer::abandoned`].
55    waker: Option<Waker>,
56    /// The signal of the answer this one forwards to
57    /// through [`Pending::map`]: dropping the mapped answer may abandon that one.
58    upstream: Option<Arc<AbandonSignal>>,
59}
60
61impl AbandonSignal {
62    fn register(&self, waker: &Waker) {
63        let mut wake = self.wake.lock_recover();
64        if !wake
65            .waker
66            .as_ref()
67            .is_some_and(|current| current.will_wake(waker))
68        {
69            wake.waker = Some(waker.clone());
70        }
71    }
72
73    fn forward_to(&self, upstream: Arc<Self>) {
74        self.wake.lock_recover().upstream = Some(upstream);
75    }
76
77    /// Wake whoever waits on this answer's abandonment, and on every answer
78    /// it forwards to. The waiter re-checks, so a wake that turns out not
79    /// to abandon anything is harmless.
80    fn wake(&self) {
81        let (waker, upstream) = {
82            let wake = self.wake.lock_recover();
83            (wake.waker.clone(), wake.upstream.clone())
84        };
85        if let Some(waker) = waker {
86            waker.wake();
87        }
88        if let Some(upstream) = upstream {
89            upstream.wake();
90        }
91    }
92}
93
94/// Held by a [`Pending`] after its slot: dropping the `Pending` first
95/// releases the slot, then wakes the producer, which then observes the
96/// lower strong count.
97struct AbandonOnDrop(Arc<AbandonSignal>);
98
99impl Drop for AbandonOnDrop {
100    fn drop(&mut self) {
101        self.0.wake();
102    }
103}
104
105impl<T> Slot<T> {
106    fn settle(&self, value: Option<T>) {
107        let mut state = self.state.lock_recover();
108        match std::mem::replace(&mut *state, State::Taken) {
109            State::Waiting {
110                then: Some(then), ..
111            } => {
112                drop(state);
113                then(value);
114            }
115            State::Waiting {
116                waker, then: None, ..
117            } => {
118                *state = State::Done(value);
119                drop(state);
120                self.settled.notify_all();
121                if let Some(waker) = waker {
122                    waker.wake();
123                }
124            }
125            already => *state = already,
126        }
127    }
128
129    /// Whether nobody can observe this answer any more. `own` is how many
130    /// strong references the asking side itself holds.
131    fn abandoned(slot: &Arc<Self>, own: usize) -> bool {
132        if Arc::strong_count(slot) > own {
133            return false;
134        }
135        let state = slot.state.lock_recover();
136        match &*state {
137            State::Waiting {
138                then: Some(_),
139                interest,
140                ..
141            } => interest.as_ref().is_some_and(|wanted| !wanted()),
142            State::Waiting { then: None, .. } | State::Done(_) | State::Taken => true,
143        }
144    }
145}
146
147/// The producing end of a [`Pending`]. Dropping it without completing
148/// abandons the answer, which the receiving end observes.
149pub struct Completer<T> {
150    slot: Option<Arc<Slot<T>>>,
151}
152
153/// The receiving end: an answer that may not exist yet.
154pub struct Pending<T> {
155    // Field order matters: `slot` drops before `_abandon` wakes the
156    // producer, so the producer sees the slot released.
157    slot: Arc<Slot<T>>,
158    _abandon: AbandonOnDrop,
159}
160
161#[must_use]
162pub fn pending<T>() -> (Completer<T>, Pending<T>) {
163    let abandon = Arc::new(AbandonSignal::default());
164    let slot = Arc::new(Slot {
165        state: Mutex::new(State::Waiting {
166            waker: None,
167            then: None,
168            interest: None,
169        }),
170        settled: Condvar::new(),
171        abandon: Arc::clone(&abandon),
172    });
173    (
174        Completer {
175            slot: Some(Arc::clone(&slot)),
176        },
177        Pending {
178            slot,
179            _abandon: AbandonOnDrop(abandon),
180        },
181    )
182}
183
184impl<T> Completer<T> {
185    /// Whether nobody is waiting any more: the [`Pending`] was dropped —
186    /// or, through [`Pending::map`], the mapped answer was — so the work
187    /// behind this answer may be skipped.
188    #[must_use]
189    pub fn is_abandoned(&self) -> bool {
190        self.slot
191            .as_ref()
192            .is_none_or(|slot| Slot::abandoned(slot, 1))
193    }
194
195    /// Resolves once nobody can observe the answer any more — what
196    /// [`Self::is_abandoned`] reports, as a future, so work behind the
197    /// answer can stop the moment its asker goes away instead of checking
198    /// on a timer. Runtime-agnostic: dropping the [`Pending`] (or, through
199    /// [`Pending::map`], the mapped answer) wakes it. An answer handed to a
200    /// plain [`Pending::then`] continuation is always wanted, so this never
201    /// resolves for it.
202    pub fn abandoned(&self) -> Abandoned<'_, T> {
203        Abandoned { completer: self }
204    }
205
206    /// Deliver the answer. A continuation attached with
207    /// [`Pending::then`] runs here, on the completing thread.
208    pub fn complete(mut self, value: T) {
209        if let Some(slot) = self.slot.take() {
210            slot.settle(Some(value));
211        }
212    }
213}
214
215impl<T> Drop for Completer<T> {
216    fn drop(&mut self) {
217        if let Some(slot) = self.slot.take() {
218            slot.settle(None);
219        }
220    }
221}
222
223/// [`Completer::abandoned`] — resolves once the answer is unobservable.
224#[must_use = "a future does nothing unless awaited"]
225pub struct Abandoned<'a, T> {
226    completer: &'a Completer<T>,
227}
228
229impl<T> Future for Abandoned<'_, T> {
230    type Output = ();
231
232    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<()> {
233        let Some(slot) = self.completer.slot.as_ref() else {
234            return Poll::Ready(());
235        };
236        if Slot::abandoned(slot, 1) {
237            return Poll::Ready(());
238        }
239        slot.abandon.register(context.waker());
240        // The receiving end may have gone between the check and the
241        // registration; it woke nobody then, so look again.
242        if Slot::abandoned(slot, 1) {
243            Poll::Ready(())
244        } else {
245            Poll::Pending
246        }
247    }
248}
249
250/// What [`Pending::poll_ready`] found.
251#[derive(Debug, PartialEq, Eq)]
252pub enum PendingPoll<T> {
253    Ready(T),
254    Waiting,
255    /// The producer went away without answering.
256    Abandoned,
257}
258
259impl<T> Pending<T> {
260    /// An answer that is already known.
261    #[must_use]
262    pub fn ready(value: T) -> Self {
263        let abandon = Arc::new(AbandonSignal::default());
264        Self {
265            slot: Arc::new(Slot {
266                state: Mutex::new(State::Done(Some(value))),
267                settled: Condvar::new(),
268                abandon: Arc::clone(&abandon),
269            }),
270            _abandon: AbandonOnDrop(abandon),
271        }
272    }
273
274    /// Take the answer if it has arrived, without waiting.
275    pub fn poll_ready(&mut self) -> PendingPoll<T> {
276        let mut state = self.slot.state.lock_recover();
277        match std::mem::replace(&mut *state, State::Taken) {
278            State::Done(Some(value)) => PendingPoll::Ready(value),
279            State::Done(None) | State::Taken => PendingPoll::Abandoned,
280            waiting @ State::Waiting { .. } => {
281                *state = waiting;
282                PendingPoll::Waiting
283            }
284        }
285    }
286
287    /// Block the calling thread until the answer arrives, however long that takes. For threads
288    /// that do not drive the answer's producer.
289    pub fn wait(mut self) -> Option<T> {
290        loop {
291            match self.wait_timeout(Duration::from_secs(3600)) {
292                Ok(answer) => return answer,
293                Err(waiting) => self = waiting,
294            }
295        }
296    }
297
298    /// Block the calling thread until the answer arrives or `timeout`
299    /// passes. For threads that do not drive the answer's producer.
300    pub fn wait_timeout(mut self, timeout: Duration) -> Result<Option<T>, Self> {
301        let deadline = tilo_clock::now().checked_add(timeout);
302        let mut state = self.slot.state.lock_recover();
303        loop {
304            if !matches!(*state, State::Waiting { .. }) {
305                drop(state);
306                return Ok(match self.poll_ready() {
307                    PendingPoll::Ready(value) => Some(value),
308                    PendingPoll::Waiting | PendingPoll::Abandoned => None,
309                });
310            }
311            let remaining = deadline.map_or(timeout, |deadline| {
312                deadline.saturating_duration_since(tilo_clock::now())
313            });
314            if remaining.is_zero() {
315                drop(state);
316                return Err(self);
317            }
318            state = self
319                .slot
320                .settled
321                .wait_timeout(state, remaining)
322                .unwrap_or_else(PoisonError::into_inner)
323                .0;
324        }
325    }
326
327    /// Run `then` with the answer once it exists — immediately if it
328    /// already does. `None` means the producer abandoned it.
329    pub fn then(self, then: impl FnOnce(Option<T>) + Send + 'static) {
330        self.then_while(then, None);
331    }
332
333    fn then_while(self, then: impl FnOnce(Option<T>) + Send + 'static, interest: Option<Interest>) {
334        let mut state = self.slot.state.lock_recover();
335        match std::mem::replace(&mut *state, State::Taken) {
336            State::Waiting { waker, .. } => {
337                *state = State::Waiting {
338                    waker,
339                    then: Some(Box::new(then)),
340                    interest,
341                };
342            }
343            State::Done(value) => {
344                drop(state);
345                then(value);
346            }
347            State::Taken => {
348                drop(state);
349                then(None);
350            }
351        }
352    }
353}
354
355impl<T: Send + 'static> Pending<T> {
356    /// The answer, transformed once it arrives.
357    #[must_use]
358    pub fn map<U: Send + 'static>(self, map: impl FnOnce(T) -> U + Send + 'static) -> Pending<U> {
359        let (completer, mapped) = pending();
360        // Dropping the mapped answer wakes whoever waits on this one's
361        // abandonment, which `wanted` then reports.
362        mapped
363            .slot
364            .abandon
365            .forward_to(Arc::clone(&self.slot.abandon));
366        let far_end = completer.slot.as_ref().map(Arc::downgrade);
367        // Upgrading adds one reference to the completer's own.
368        let wanted = move || {
369            far_end
370                .as_ref()
371                .and_then(Weak::upgrade)
372                .is_some_and(|slot| !Slot::abandoned(&slot, 2))
373        };
374        self.then_while(
375            move |value| {
376                if let Some(value) = value {
377                    completer.complete(map(value));
378                }
379            },
380            Some(Box::new(wanted)),
381        );
382        mapped
383    }
384}
385
386impl<T> Future for Pending<T> {
387    /// `None` if the producer abandoned the answer.
388    type Output = Option<T>;
389
390    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<T>> {
391        let this = self.get_mut();
392        let mut state = this.slot.state.lock_recover();
393        match std::mem::replace(&mut *state, State::Taken) {
394            State::Done(value) => Poll::Ready(value),
395            State::Taken => Poll::Ready(None),
396            State::Waiting { then, interest, .. } => {
397                *state = State::Waiting {
398                    waker: Some(context.waker().clone()),
399                    then,
400                    interest,
401                };
402                Poll::Pending
403            }
404        }
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    /// Counts how often a producer waiting on abandonment is woken.
413    struct CountingWaker(std::sync::atomic::AtomicUsize);
414
415    impl std::task::Wake for CountingWaker {
416        fn wake(self: Arc<Self>) {
417            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
418        }
419    }
420
421    impl CountingWaker {
422        fn woken(&self) -> usize {
423            self.0.load(std::sync::atomic::Ordering::SeqCst)
424        }
425    }
426
427    tilo_test_env::scenario! {
428        fn a_pending_answer_wakes_whoever_waits_on_it;
429
430        phase a_pending_answer_resolves_however_it_is_waited_on;
431        // A pending answer is polled, awaited or continued; dropping a mapped answer abandons the
432        // original; waiting across threads sees the answer or times out; a ready answer resolves as a
433        // future without a runtime.
434        // Runs each phase below in order; every phase builds its own fixture.
435        {
436            a_pending_answer_is_polled_awaited_or_continued();
437            dropping_a_mapped_answer_abandons_the_original();
438            waiting_across_threads_sees_the_answer_or_times_out();
439            a_ready_answer_resolves_as_a_future_without_a_runtime();
440        }
441
442        phase dropping_the_asker_wakes_a_producer_waiting_on_abandonment;
443        // The producer of an answer learns that its asker went away the moment
444        // it does, as a wake-up rather than by checking again later: dropping
445        // the answer, or the answer mapped from it, wakes
446        // [`Completer::abandoned`]; an answer a plain continuation took stays
447        // wanted. No runtime is involved.
448        {
449            let counter = Arc::new(CountingWaker(std::sync::atomic::AtomicUsize::new(0)));
450            let waker = Waker::from(Arc::clone(&counter));
451            let mut context = Context::from_waker(&waker);
452
453            let (completer, answer) = pending::<u8>();
454            let mut abandoned = std::pin::pin!(completer.abandoned());
455            assert_eq!(abandoned.as_mut().poll(&mut context), Poll::Pending);
456            assert_eq!(counter.woken(), 0, "nothing happened yet");
457            drop(answer);
458            assert_eq!(counter.woken(), 1, "dropping the answer wakes its producer");
459            assert_eq!(abandoned.as_mut().poll(&mut context), Poll::Ready(()));
460
461            let (completer, answer) = pending::<u8>();
462            let mapped = answer.map(|value| value.saturating_add(1));
463            let mut abandoned = std::pin::pin!(completer.abandoned());
464            assert_eq!(abandoned.as_mut().poll(&mut context), Poll::Pending);
465            let before = counter.woken();
466            drop(mapped);
467            assert!(
468                counter.woken() > before,
469                "dropping the mapped answer wakes the original producer"
470            );
471            assert_eq!(abandoned.as_mut().poll(&mut context), Poll::Ready(()));
472
473            let (completer, answer) = pending::<u8>();
474            answer.then(|_| {});
475            let mut abandoned = std::pin::pin!(completer.abandoned());
476            assert_eq!(
477                abandoned.as_mut().poll(&mut context),
478                Poll::Pending,
479                "a plain continuation always wants the answer"
480            );
481
482            let (completer, answer) = pending::<u8>();
483            drop(answer);
484            let mut abandoned = std::pin::pin!(completer.abandoned());
485            assert_eq!(
486                abandoned.as_mut().poll(&mut context),
487                Poll::Ready(()),
488                "an answer dropped before anyone waited is already abandoned"
489            );
490        }
491
492        phase a_producer_on_another_thread_wakes_when_the_asker_drops_the_answer;
493        // A producer on another thread wakes as soon as the asker drops the
494        // answer, with nothing polling in between.
495        {
496            let (completer, answer) = pending::<u8>();
497            let (parked, ready) = std::sync::mpsc::channel();
498            let producer = std::thread::spawn(move || {
499                struct Unpark(std::thread::Thread);
500                impl std::task::Wake for Unpark {
501                    fn wake(self: Arc<Self>) {
502                        self.0.unpark();
503                    }
504                }
505                let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
506                let mut context = Context::from_waker(&waker);
507                let mut abandoned = std::pin::pin!(completer.abandoned());
508                let mut announced = false;
509                let deadline = tilo_test_env::hang_deadline();
510                loop {
511                    if abandoned.as_mut().poll(&mut context).is_ready() {
512                        return true;
513                    }
514                    if !announced {
515                        parked.send(()).expect("announce parking");
516                        announced = true;
517                    }
518                    let remaining = deadline.saturating_duration_since(tilo_clock::now());
519                    if remaining.is_zero() {
520                        return false;
521                    }
522                    std::thread::park_timeout(remaining);
523                }
524            });
525            ready
526                .recv_timeout(tilo_test_env::hang_bound())
527                .expect("the producer waits");
528            drop(answer);
529            assert!(
530                producer.join().expect("producer thread"),
531                "the producer saw its asker go away"
532            );
533        }
534    }
535
536    #[allow(
537        clippy::arithmetic_side_effects,
538        reason = "test phase: arithmetic on small fixed test values cannot overflow"
539    )]
540    fn a_pending_answer_is_polled_awaited_or_continued() {
541        let (completer, mut answer) = pending::<u32>();
542        assert_eq!(answer.poll_ready(), PendingPoll::Waiting);
543        completer.complete(7);
544        assert_eq!(answer.poll_ready(), PendingPoll::Ready(7));
545        assert_eq!(answer.poll_ready(), PendingPoll::Abandoned);
546
547        let (completer, answer) = pending::<u32>();
548        let doubled = answer.map(|value| value * 2);
549        completer.complete(21);
550        assert_eq!(doubled.wait_timeout(Duration::ZERO).ok(), Some(Some(42)));
551
552        let (completer, mut answer) = pending::<u32>();
553        drop(completer);
554        assert_eq!(answer.poll_ready(), PendingPoll::Abandoned);
555    }
556
557    #[allow(
558        clippy::arithmetic_side_effects,
559        reason = "test phase: arithmetic on small fixed test values cannot overflow"
560    )]
561    fn dropping_a_mapped_answer_abandons_the_original() {
562        let (completer, answer) = pending::<u32>();
563        let mapped = answer.map(|value| value + 1);
564        assert!(!completer.is_abandoned());
565        drop(mapped);
566        assert!(completer.is_abandoned());
567
568        let (completer, answer) = pending::<u32>();
569        answer.then(|_| {});
570        assert!(
571            !completer.is_abandoned(),
572            "a plain continuation always wants the answer"
573        );
574    }
575
576    fn waiting_across_threads_sees_the_answer_or_times_out() {
577        let (completer, answer) = pending::<&'static str>();
578        let answer = answer
579            .wait_timeout(Duration::from_millis(10))
580            .expect_err("nothing has answered yet");
581        let producer = std::thread::spawn(move || completer.complete("done"));
582        assert_eq!(
583            answer.wait_timeout(tilo_test_env::hang_bound()).ok(),
584            Some(Some("done"))
585        );
586        producer.join().expect("producer thread");
587    }
588
589    fn a_ready_answer_resolves_as_a_future_without_a_runtime() {
590        let waker = Waker::noop();
591        let mut context = Context::from_waker(waker);
592        let mut ready = Pending::ready(3_u8);
593        assert_eq!(
594            Pin::new(&mut ready).poll(&mut context),
595            Poll::Ready(Some(3))
596        );
597        let (completer, mut waiting) = pending::<u8>();
598        assert_eq!(Pin::new(&mut waiting).poll(&mut context), Poll::Pending);
599        completer.complete(4);
600        assert_eq!(
601            Pin::new(&mut waiting).poll(&mut context),
602            Poll::Ready(Some(4))
603        );
604    }
605}