refresh_machines 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,83 @@
1
+ use core::time::Duration;
2
+
3
+ use coalesce_machines::{FlightId, Joined, WaiterId};
4
+
5
+ use crate::{Lease, Refusal};
6
+
7
+ /// What is happening about refreshing a stale value that is being served.
8
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9
+ pub enum Revalidation {
10
+ /// Nobody was refreshing this key. The caller now is: serve the stale
11
+ /// value, refresh in the background, report with the lease.
12
+ Lead(Lease),
13
+ /// Another caller holds a live lease for this key. Just serve.
14
+ InFlight,
15
+ /// The last refresh failed and asked for quiet until this time. Just serve.
16
+ Backoff {
17
+ /// When the next caller will be asked to refresh again.
18
+ until: Duration,
19
+ },
20
+ /// A refresh is due but could not be registered, for the reason given.
21
+ ///
22
+ /// This is not a refused call: the stale value is still served, so
23
+ /// [`crate::Refresher::decide`] is honoured and answers
24
+ /// `Ok(Decision::Stale { .. })`. The failed registration changed nothing
25
+ /// (no lease, no flight, no waiter); only the clock advances, as for any
26
+ /// honoured decision. Just serve; the next caller tries again.
27
+ Unavailable(Refusal),
28
+ }
29
+
30
+ /// The answer to "may I serve what I have for this key?".
31
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
32
+ pub enum Decision {
33
+ /// Serve the cached value.
34
+ Fresh {
35
+ /// Its age at `now`.
36
+ age: Duration,
37
+ },
38
+ /// Serve the cached value, stale, and mind the revalidation.
39
+ Stale {
40
+ /// Its age at `now`.
41
+ age: Duration,
42
+ /// Who refreshes it, if anyone.
43
+ revalidation: Revalidation,
44
+ },
45
+ /// Nothing servable. The caller fetches and reports with the lease.
46
+ Fetch {
47
+ /// The right to refresh this key.
48
+ lease: Lease,
49
+ },
50
+ /// Nothing servable and another caller is already fetching. Wait for a
51
+ /// [`crate::Notification`] carrying this id, then decide again.
52
+ Wait {
53
+ /// The caller's notification id.
54
+ waiter: WaiterId,
55
+ /// The refresh being shared: what [`crate::Refresher::flight`] answers for
56
+ /// the key's live lease, and the [`crate::Notification::flight`] to come.
57
+ flight: FlightId,
58
+ },
59
+ }
60
+
61
+ impl Decision {
62
+ /// A [`Decision::Wait`], rebuilt from its two ids.
63
+ ///
64
+ /// `None` unless they are ids one refresher could have answered together,
65
+ /// as [`Joined::follower`] judges: the same scope, the waiter issued after
66
+ /// the flight it waits on. The ids are not looked up.
67
+ #[must_use]
68
+ pub const fn wait(waiter: WaiterId, flight: FlightId) -> Option<Self> {
69
+ match Joined::follower(waiter, flight) {
70
+ Some(_) => Some(Self::Wait { waiter, flight }),
71
+ None => None,
72
+ }
73
+ }
74
+ }
75
+
76
+ /// What [`crate::Refresher::forget`] did. Both are honoured; neither is a refusal.
77
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
78
+ pub enum Forgetting {
79
+ /// The key had metadata and it was dropped; its slot is free.
80
+ Forgotten,
81
+ /// The key had no metadata: an idempotent repeat that changed nothing.
82
+ NotHeld,
83
+ }
@@ -0,0 +1,123 @@
1
+ //! Registering and settling refreshes on the coalescer inside.
2
+
3
+ use core::time::Duration;
4
+
5
+ use coalesce_machines::{Coalescer, FlightId, Joined, Outcome, WaiterId};
6
+
7
+ use crate::{Lead, Lease, Refresher, Refusal};
8
+
9
+ impl<const KEYS: usize, const FLIGHTS: usize, const WAITERS: usize>
10
+ Refresher<KEYS, FLIGHTS, WAITERS>
11
+ {
12
+ /// Issue a lease for `key`: a new refresh, or a takeover of an overdue one.
13
+ ///
14
+ /// Every check comes before the first id is drawn, so a refused lead
15
+ /// consumes none: a full table first, the spent sequence last, in the
16
+ /// order the coalescer itself refuses a join.
17
+ pub(crate) fn lead(
18
+ &mut self,
19
+ key: u64,
20
+ now: Duration,
21
+ lead_for: Duration,
22
+ ) -> Result<Lease, Refusal> {
23
+ let deadline = now.saturating_add(lead_for);
24
+ let Self { leads, flights, .. } = self;
25
+ if let Some(lead) = leads.iter_mut().flatten().find(|lead| lead.key == key) {
26
+ // A takeover: a new lease on the flight already in the air.
27
+ let lease = flights.reserve()?;
28
+ lead.lease = lease;
29
+ lead.deadline = deadline;
30
+ return Ok(Lease(lease));
31
+ }
32
+ let free = leads
33
+ .iter_mut()
34
+ .find(|lead| lead.is_none())
35
+ .ok_or(Refusal::FlightsFull)?;
36
+ if flights.flight(key).is_some() {
37
+ debug_assert!(false, "every coalesce flight has a lead");
38
+ return Err(Refusal::Stale);
39
+ }
40
+ if flights.in_flight() == FLIGHTS {
41
+ debug_assert!(false, "a free lead slot means a free flight slot");
42
+ return Err(Refusal::FlightsFull);
43
+ }
44
+ // A lease and a flight: with one id left, neither is drawn.
45
+ if flights.remaining() < 2 {
46
+ return Err(Refusal::Exhausted);
47
+ }
48
+ // The key has no flight, so the join leads; the snapshot only serves
49
+ // the arm the type demands, to leave nothing changed if it is reached.
50
+ let before = flights.clone();
51
+ let lease = flights.reserve()?;
52
+ let flight = match flights.join(key) {
53
+ Ok(Joined::Leader(flight)) => flight,
54
+ Ok(Joined::Follower { .. })
55
+ | Err(
56
+ coalesce_machines::Refusal::FlightsFull
57
+ | coalesce_machines::Refusal::WaitersFull
58
+ | coalesce_machines::Refusal::Exhausted
59
+ | coalesce_machines::Refusal::Stale,
60
+ ) => {
61
+ debug_assert!(
62
+ false,
63
+ "a key with no flight leads, with ids and a slot to spare"
64
+ );
65
+ *flights = before;
66
+ return Err(Refusal::Stale);
67
+ }
68
+ };
69
+ *free = Some(Lead {
70
+ lease,
71
+ key,
72
+ flight,
73
+ deadline,
74
+ });
75
+ Ok(Lease(lease))
76
+ }
77
+
78
+ /// Wait on the live lead's flight for `key`.
79
+ pub(crate) fn follow(&mut self, key: u64) -> Result<(WaiterId, FlightId), Refusal> {
80
+ if self.flights.flight(key).is_none() {
81
+ debug_assert!(false, "every lead's flight is in the air");
82
+ return Err(Refusal::Stale);
83
+ }
84
+ // The key is in flight, so the join follows or refuses; the snapshot
85
+ // only serves the arm the type demands, to leave nothing changed.
86
+ let before = self.flights.clone();
87
+ match self.flights.join(key)? {
88
+ Joined::Follower { waiter, flight } => Ok((waiter, flight)),
89
+ Joined::Leader(_) => {
90
+ debug_assert!(false, "a key in flight is never led again");
91
+ self.flights = before;
92
+ Err(Refusal::Stale)
93
+ }
94
+ }
95
+ }
96
+
97
+ /// Settle the flight of the lead held in `slot` and free the slot.
98
+ ///
99
+ /// Every lead's flight is in the air, so the coalescer never refuses; if
100
+ /// it did, it changed nothing and neither does this: the slot is freed
101
+ /// only once the flight has settled.
102
+ pub(crate) fn settle(
103
+ flights: &mut Coalescer<FLIGHTS, WAITERS>,
104
+ slot: &mut Option<Lead>,
105
+ flight: FlightId,
106
+ outcome: Outcome,
107
+ ) -> Result<(), Refusal> {
108
+ let settled = match outcome {
109
+ Outcome::Completed => flights.complete(flight),
110
+ Outcome::Abandoned => flights.abandon(flight),
111
+ };
112
+ match settled {
113
+ Ok(_) => {
114
+ *slot = None;
115
+ Ok(())
116
+ }
117
+ Err(refusal) => {
118
+ debug_assert!(false, "every lead's flight is in the air");
119
+ Err(refusal.into())
120
+ }
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,42 @@
1
+ use periscope_machines::{scope_of, sequence_of};
2
+
3
+ /// The right to refresh one key, and the token that reports how it went.
4
+ ///
5
+ /// Issued by [`crate::Refresher::decide`]. Never reissued: once the refresh is
6
+ /// reported, abandoned, reaped or taken over, the lease is
7
+ /// [`crate::Refusal::Stale`] forever.
8
+ ///
9
+ /// Not ordered: a lease carries its refresher's scope in the top bits, so an
10
+ /// order between leases would rank two scopes against each other, which
11
+ /// means nothing.
12
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13
+ pub struct Lease(pub(crate) u64);
14
+
15
+ impl Lease {
16
+ /// Rebuild a lease from [`Self::raw`], e.g. after it crossed an FFI or queue boundary.
17
+ ///
18
+ /// `None` when the sequence number (the low 48 bits) is zero, which no
19
+ /// refresher issues. Anything else is accepted here: a lease the
20
+ /// refresher never issued, or no longer holds, is [`crate::Refusal::Stale`]
21
+ /// there.
22
+ #[must_use]
23
+ pub const fn from_raw(raw: u64) -> Option<Self> {
24
+ if sequence_of(raw) == 0 {
25
+ None
26
+ } else {
27
+ Some(Self(raw))
28
+ }
29
+ }
30
+
31
+ /// The lease as a plain integer. Never zero for an issued lease.
32
+ #[must_use]
33
+ pub const fn raw(self) -> u64 {
34
+ self.0
35
+ }
36
+
37
+ /// The scope of the refresher that issued this lease, see [`crate::Refresher::with_scope`].
38
+ #[must_use]
39
+ pub const fn scope(self) -> u16 {
40
+ scope_of(self.0)
41
+ }
42
+ }