Skip to main content

tilo_actions/remote/
wait.rs

1//! Answers that wait for an invocation to move.
2//!
3//! A caller that wants to know when an invocation finishes used to ask
4//! again on a timer: an `Observe` every 200 ms, each a round trip. A waiting
5//! request (`wait_ms` on [`RemoteActionMessage::Observe`] or
6//! [`InvokeRequest`]) is instead held by the provider until the invocation moves
7//! past what the caller has seen, settles, or the wait runs out — so a
8//! result reaches its caller one round trip after the provider records it.
9//!
10//! Nothing here sleeps or holds a thread. A wait parks on the provider's own
11//! change signal ([`ActionProvider::next_change`]) and looks again only when it
12//! fires; a provider that has none answers at once. The state
13//! a waiting answer carries is read when it is answered, as the caller is
14//! then, so a caller who lost access in the meantime hears `None`.
15//!
16//! [`RemoteActionMessage::Observe`]: super::RemoteActionMessage::Observe
17//! [`InvokeRequest`]: super::InvokeRequest
18
19use serde::{Deserialize, Serialize};
20use tilo_clock::time::{Duration, Instant};
21
22use super::{
23    ActionProvider, Caller, Completer, InvocationReceipt, InvocationState, Pending, PendingPoll,
24    ReceiptStatus, pending,
25};
26use crate::outcome::{InvocationId, InvocationUpdate};
27
28/// The longest a provider holds a waiting answer, whatever `wait_ms` asked, so a
29/// server connection or a broker call is never held open indefinitely.
30#[allow(clippy::cast_lossless, reason = "u64::from is not a const fn")]
31pub const MAX_REMOTE_WAIT: Duration = Duration::from_millis(MAX_REMOTE_WAIT_MS as u64);
32
33/// [`MAX_REMOTE_WAIT`] as the `wait_ms` a request carries: a follow asking for more is held no
34/// longer, so it asks for this.
35pub const MAX_REMOTE_WAIT_MS: u32 = 10_000;
36
37/// How often one wait looks again because the provider's change signal had
38/// already fired, before it answers with what it has rather than spin.
39const MAX_IMMEDIATE_WAKES: u32 = 64;
40
41/// How far an invocation's updates had got when its caller last looked:
42/// what a waiting [`Observe`](super::RemoteActionMessage::Observe) asks the
43/// provider to move past.
44#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
45pub enum UpdateMark {
46    Accepted,
47    Progress {
48        sequence: u64,
49    },
50    Item {
51        sequence: u64,
52    },
53    /// Settled: nothing follows.
54    Finished,
55}
56
57impl UpdateMark {
58    /// Where `update` stands.
59    #[must_use]
60    pub const fn of(update: &InvocationUpdate) -> Self {
61        match update {
62            InvocationUpdate::Accepted { .. } => Self::Accepted,
63            InvocationUpdate::Progress { sequence, .. } => Self::Progress {
64                sequence: *sequence,
65            },
66            InvocationUpdate::Item { sequence, .. } => Self::Item {
67                sequence: *sequence,
68            },
69            InvocationUpdate::Succeeded { .. }
70            | InvocationUpdate::Failed { .. }
71            | InvocationUpdate::Cancelled { .. } => Self::Finished,
72        }
73    }
74}
75
76/// When a wait of `wait_ms` asked now ends, capped at [`MAX_REMOTE_WAIT`].
77pub(super) fn deadline(wait_ms: u32) -> Instant {
78    let now = tilo_clock::now();
79    let wait = Duration::from_millis(u64::from(wait_ms)).min(MAX_REMOTE_WAIT);
80    now.checked_add(wait).unwrap_or(now)
81}
82
83/// The state of `invocation`, as [`ActionProvider::observe`] reports it to `caller`, once it has
84/// moved past `seen` — or, with no `seen`, once it settles, or once a followed read holds its
85/// answer ([`InvocationState::read_answered`]) — or at `until`, whichever comes first. A caller
86/// following what it has seen hears the state as it stands at `until` too: no wait outlives the
87/// caller that asked it. A caller across a connection gives up on an answer that does not come and
88/// asks again, and a wait that only a move could end would answer that move once more for every ask
89/// it outlived, to an asker that takes each answer for its latest ask.
90///
91/// It answers at once when the invocation is already there, when `caller`
92/// may not see it (`None`), when the provider cannot signal changes, or when
93/// `caller`'s execution has ended. Otherwise it waits on
94/// [`ActionProvider::next_change`] and looks again each time that fires; the
95/// deadline is checked then, so a provider's bounded change interval bounds how
96/// far past `until` an answer can come.
97pub fn settle_with<H: ActionProvider + Clone + Send + 'static>(
98    provider: &H,
99    caller: &Caller,
100    invocation: InvocationId,
101    seen: Option<UpdateMark>,
102    until: Instant,
103) -> Pending<Option<InvocationState>> {
104    let (answer, settled) = pending();
105    look(Wait {
106        provider: provider.clone(),
107        caller: caller.clone(),
108        invocation,
109        seen,
110        until,
111        answer,
112    });
113    settled
114}
115
116/// `receipt`, held while it says the invocation is still running until it
117/// settles or `until` passes — what a waiting `Invoke` answers with.
118pub(super) fn settle_receipt<H: ActionProvider + Clone + Send + 'static>(
119    provider: &H,
120    caller: &Caller,
121    receipt: Pending<InvocationReceipt>,
122    until: Instant,
123) -> Pending<InvocationReceipt> {
124    let provider = provider.clone();
125    let caller = caller.clone();
126    let (completer, settled) = pending();
127    receipt.then(move |receipt| {
128        // An abandoned admission abandons this answer too: dropping the
129        // completer is how `serve` hears it.
130        let Some(receipt) = receipt else {
131            return;
132        };
133        if !matches!(receipt.status, ReceiptStatus::Accepted) {
134            completer.complete(receipt);
135            return;
136        }
137        settle_with(&provider, &caller, receipt.invocation, None, until).then(move |state| {
138            // Nothing visible to this caller any more: the admission stands,
139            // and the next observe says what became of it.
140            completer.complete(state.flatten().map_or(receipt, |state| state.receipt()));
141        });
142    });
143    settled
144}
145
146/// One parked wait.
147struct Wait<H> {
148    provider: H,
149    caller: Caller,
150    invocation: InvocationId,
151    seen: Option<UpdateMark>,
152    until: Instant,
153    answer: Completer<Option<InvocationState>>,
154}
155
156impl<H: ActionProvider> Wait<H> {
157    /// Whether `state` is worth answering with now.
158    fn arrived(&self, state: Option<&InvocationState>) -> bool {
159        state.is_none_or(|state| {
160            state.is_terminal()
161                // A followed read never ends: its first whole answer is what a caller that saw
162                // nothing yet waits for.
163                || (self.seen.is_none() && state.read_answered)
164                || self
165                    .seen
166                    .is_some_and(|seen| UpdateMark::of(&state.update) != seen)
167        })
168    }
169
170    /// Whether to stop waiting whatever the state says: at `until`, or once its
171    /// caller's execution has ended.
172    fn over(&self) -> bool {
173        tilo_clock::now() >= self.until
174            || self
175                .caller
176                .execution_lease()
177                .is_some_and(|lease| !lease.is_live())
178    }
179}
180
181fn look<H: ActionProvider + Send + 'static>(wait: Wait<H>) {
182    let mut wakes = 0_u32;
183    loop {
184        if wait.answer.is_abandoned() {
185            return;
186        }
187        // Asked for before looking, so a change between the two still wakes
188        // the wait rather than slipping past it.
189        let change = wait.provider.next_change(&wait.caller, &wait.invocation);
190        let state = wait.provider.observe(&wait.caller, &wait.invocation);
191        let answer_now =
192            wait.arrived(state.as_ref()) || wait.over() || wakes >= MAX_IMMEDIATE_WAKES;
193        let Some(mut change) = change.filter(|_| !answer_now) else {
194            wait.answer.complete(state);
195            return;
196        };
197        if matches!(change.poll_ready(), PendingPoll::Waiting) {
198            // Whether it fires or its producer goes away, look again.
199            change.then(move |_| look(wait));
200            return;
201        }
202        wakes = wakes.saturating_add(1);
203    }
204}
205
206#[cfg(test)]
207#[path = "wait_tests.rs"]
208mod tests;