outbox_machines 0.8.1
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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +106 -0
- data/Cargo.lock +314 -0
- data/Cargo.toml +28 -0
- data/LICENSE.txt +21 -0
- data/README.md +331 -0
- data/ext/outbox_machines_native/core/CHANGELOG.md +81 -0
- data/ext/outbox_machines_native/core/Cargo.toml +23 -0
- data/ext/outbox_machines_native/core/README.md +226 -0
- data/ext/outbox_machines_native/core/src/lib.rs +558 -0
- data/ext/outbox_machines_native/core/src/refusal.rs +48 -0
- data/ext/outbox_machines_native/core/src/values.rs +298 -0
- data/ext/outbox_machines_native/extconf.rb +2 -0
- data/ext/outbox_machines_native/ffi/Cargo.toml +21 -0
- data/ext/outbox_machines_native/ffi/extconf.rb +14 -0
- data/ext/outbox_machines_native/ffi/src/classes.rs +37 -0
- data/ext/outbox_machines_native/ffi/src/init.rs +35 -0
- data/ext/outbox_machines_native/ffi/src/lib.rs +300 -0
- data/ext/outbox_machines_native/ffi/src/values.rs +149 -0
- data/lib/outbox_machines/version.rb +5 -0
- data/lib/outbox_machines.rb +131 -0
- data/sig/outbox_machines.rbs +192 -0
- metadata +92 -0
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
#![no_std]
|
|
2
|
+
#![cfg_attr(not(test), deny(clippy::indexing_slicing))]
|
|
3
|
+
#![doc = include_str!("../README.md")]
|
|
4
|
+
|
|
5
|
+
mod refusal;
|
|
6
|
+
mod values;
|
|
7
|
+
|
|
8
|
+
use core::num::NonZeroU32;
|
|
9
|
+
use core::time::Duration;
|
|
10
|
+
|
|
11
|
+
use periscope_machines::Issuer;
|
|
12
|
+
|
|
13
|
+
pub use refusal::Refusal;
|
|
14
|
+
pub use values::{Claimed, Disposition, Entry, Expired, Pass, Sweep};
|
|
15
|
+
|
|
16
|
+
/// Delivery state of one record.
|
|
17
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
18
|
+
pub enum State {
|
|
19
|
+
/// Waiting to be claimed, no earlier than its availability instant.
|
|
20
|
+
Pending,
|
|
21
|
+
/// Owned by one attempt until its lease expires.
|
|
22
|
+
Claimed,
|
|
23
|
+
/// The caller asserted that the external effect was persisted.
|
|
24
|
+
Confirmed,
|
|
25
|
+
/// Attempts are exhausted; the record will not be claimed again.
|
|
26
|
+
Dead,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/// Honoured outcome of [`Outbox::enqueue`].
|
|
30
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
31
|
+
pub enum Enqueue {
|
|
32
|
+
/// The id is now pending.
|
|
33
|
+
Enqueued,
|
|
34
|
+
/// An idempotent repeat: a record with this id is still present, in any
|
|
35
|
+
/// state. Nothing changed, not even the observed clock.
|
|
36
|
+
Duplicate,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Honoured outcome of [`Outbox::confirm`].
|
|
40
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
41
|
+
pub enum Confirmation {
|
|
42
|
+
/// The live attempt is now confirmed.
|
|
43
|
+
Confirmed,
|
|
44
|
+
/// An idempotent repeat: this same attempt already confirmed the record.
|
|
45
|
+
/// Nothing changed.
|
|
46
|
+
AlreadyConfirmed,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// Honoured outcome of [`Outbox::fail`].
|
|
50
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
51
|
+
pub enum Failure {
|
|
52
|
+
/// The live attempt is over; the record went where the disposition says.
|
|
53
|
+
Failed(Disposition),
|
|
54
|
+
/// An idempotent repeat: `fail` already ended this same attempt with this
|
|
55
|
+
/// same `retry_after`, and no newer attempt exists. Nothing changed; the
|
|
56
|
+
/// disposition is the standing one from the first call.
|
|
57
|
+
AlreadyFailed(Disposition),
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// Honoured outcome of [`Outbox::forget`].
|
|
61
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
62
|
+
pub enum Forgetting {
|
|
63
|
+
/// The terminal record was dropped; its slot and its id are free.
|
|
64
|
+
Forgotten,
|
|
65
|
+
/// No record carries this id: an idempotent repeat that changed nothing.
|
|
66
|
+
NotHeld,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
70
|
+
struct Record {
|
|
71
|
+
id: u64,
|
|
72
|
+
/// Enqueue order among the records held: the held records carry exactly
|
|
73
|
+
/// `0..len`, so it never outgrows the capacity.
|
|
74
|
+
seq: usize,
|
|
75
|
+
state: State,
|
|
76
|
+
attempts: u32,
|
|
77
|
+
/// The latest attempt and its lease; `None` until the record is first
|
|
78
|
+
/// claimed.
|
|
79
|
+
latest: Option<Lease>,
|
|
80
|
+
available_at: Duration,
|
|
81
|
+
/// The `retry_after` of the `fail` that ended the latest attempt; `None`
|
|
82
|
+
/// when it is live, confirmed, or was reaped by `expire_claims`. It is
|
|
83
|
+
/// what lets a repeated `fail` be told from a report on an attempt whose
|
|
84
|
+
/// outcome is unknown, and from a different report on the same attempt.
|
|
85
|
+
failed: Option<Duration>,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// One issued attempt: its identity and the instant its lease ends.
|
|
89
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
90
|
+
struct Lease {
|
|
91
|
+
attempt: u64,
|
|
92
|
+
expires: Duration,
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
impl Record {
|
|
96
|
+
const fn view(&self) -> Entry {
|
|
97
|
+
let attempt = match self.latest {
|
|
98
|
+
Some(lease) => Some(lease.attempt),
|
|
99
|
+
None => None,
|
|
100
|
+
};
|
|
101
|
+
Entry::held(
|
|
102
|
+
self.id,
|
|
103
|
+
self.state,
|
|
104
|
+
self.attempts,
|
|
105
|
+
attempt,
|
|
106
|
+
self.available_at,
|
|
107
|
+
)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// `true` when `attempt` is this record's latest one.
|
|
111
|
+
fn is_latest(&self, attempt: u64) -> bool {
|
|
112
|
+
self.latest.is_some_and(|lease| lease.attempt == attempt)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/// Fixed-capacity delivery-policy table holding at most `N` records.
|
|
117
|
+
///
|
|
118
|
+
/// Lookup is a linear scan: intended for small, explicit capacities.
|
|
119
|
+
///
|
|
120
|
+
/// Equality compares the whole value, sweep cursor and observed clock
|
|
121
|
+
/// included: a refused call leaves the outbox equal to a clone taken before.
|
|
122
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
123
|
+
pub struct Outbox<const N: usize> {
|
|
124
|
+
slots: [Option<Record>; N],
|
|
125
|
+
max_attempts: NonZeroU32,
|
|
126
|
+
observed: Duration,
|
|
127
|
+
/// Issues the attempt identities; it also holds the outbox's scope.
|
|
128
|
+
attempts: Issuer,
|
|
129
|
+
cursor: usize,
|
|
130
|
+
scanned_in_pass: usize,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
impl<const N: usize> Outbox<N> {
|
|
134
|
+
/// Empty table in scope zero; a record dies after `max_attempts` claims
|
|
135
|
+
/// fail or expire.
|
|
136
|
+
#[must_use]
|
|
137
|
+
pub const fn new(max_attempts: NonZeroU32) -> Self {
|
|
138
|
+
Self::with_scope(max_attempts, 0)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/// Empty table whose attempt identities carry `scope`.
|
|
142
|
+
///
|
|
143
|
+
/// An attempt identity is a plain integer, so two outboxes in the same
|
|
144
|
+
/// scope issue the same ones, and a report sent to the wrong outbox can
|
|
145
|
+
/// settle a live attempt there when both hold the record id. Give every
|
|
146
|
+
/// outbox whose reports could meet its own scope: an attempt of another
|
|
147
|
+
/// scope is then always [`Refusal::Stale`]. The outbox cannot pick a
|
|
148
|
+
/// scope itself; keeping them distinct is the caller's job.
|
|
149
|
+
#[must_use]
|
|
150
|
+
pub const fn with_scope(max_attempts: NonZeroU32, scope: u16) -> Self {
|
|
151
|
+
Self {
|
|
152
|
+
slots: [None; N],
|
|
153
|
+
max_attempts,
|
|
154
|
+
observed: Duration::ZERO,
|
|
155
|
+
attempts: Issuer::new(scope),
|
|
156
|
+
cursor: 0,
|
|
157
|
+
scanned_in_pass: 0,
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/// Empty table that continues the attempt sequence of `scope` after
|
|
162
|
+
/// `issued` identities: the restart of an outbox that saved
|
|
163
|
+
/// [`Outbox::issued`].
|
|
164
|
+
///
|
|
165
|
+
/// The next claim carries sequence `issued + 1`, so an attempt that
|
|
166
|
+
/// outlived the restart is never issued again and cannot settle a new
|
|
167
|
+
/// claim. `resumed(max_attempts, scope, 0)` is [`Outbox::with_scope`].
|
|
168
|
+
/// Records are not restored: enqueue them again.
|
|
169
|
+
///
|
|
170
|
+
/// Resuming from a count lower than what was really issued reissues
|
|
171
|
+
/// identities, so save [`Outbox::issued`] before acting on a claim. An
|
|
172
|
+
/// outbox that cannot save it takes a scope no earlier incarnation used
|
|
173
|
+
/// instead.
|
|
174
|
+
///
|
|
175
|
+
/// `None` when `issued` is beyond `SEQUENCE_MAX` (2^48 - 1), which no
|
|
176
|
+
/// outbox reaches.
|
|
177
|
+
#[must_use]
|
|
178
|
+
pub const fn resumed(max_attempts: NonZeroU32, scope: u16, issued: u64) -> Option<Self> {
|
|
179
|
+
let Some(attempts) = Issuer::resumed(scope, issued) else {
|
|
180
|
+
return None;
|
|
181
|
+
};
|
|
182
|
+
let mut outbox = Self::with_scope(max_attempts, scope);
|
|
183
|
+
outbox.attempts = attempts;
|
|
184
|
+
Some(outbox)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/// The scope carried by every attempt identity this outbox issues.
|
|
188
|
+
#[must_use]
|
|
189
|
+
pub const fn scope(&self) -> u16 {
|
|
190
|
+
self.attempts.scope()
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/// How many attempt identities this outbox has issued; also the sequence
|
|
194
|
+
/// number of the latest one. Save it to restart with [`Outbox::resumed`].
|
|
195
|
+
#[must_use]
|
|
196
|
+
pub const fn issued(&self) -> u64 {
|
|
197
|
+
self.attempts.issued()
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/// Compile-time record capacity.
|
|
201
|
+
#[must_use]
|
|
202
|
+
pub const fn capacity(&self) -> usize {
|
|
203
|
+
N
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/// Claims allowed per record before it dies.
|
|
207
|
+
#[must_use]
|
|
208
|
+
pub const fn max_attempts(&self) -> u32 {
|
|
209
|
+
self.max_attempts.get()
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/// Records currently held, in any state.
|
|
213
|
+
#[must_use]
|
|
214
|
+
pub fn len(&self) -> usize {
|
|
215
|
+
self.slots.iter().flatten().count()
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/// `true` when no record is held.
|
|
219
|
+
#[must_use]
|
|
220
|
+
pub fn is_empty(&self) -> bool {
|
|
221
|
+
self.slots.iter().all(Option::is_none)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/// Records currently in `state`.
|
|
225
|
+
#[must_use]
|
|
226
|
+
pub fn count(&self, state: State) -> usize {
|
|
227
|
+
self.slots
|
|
228
|
+
.iter()
|
|
229
|
+
.flatten()
|
|
230
|
+
.filter(|record| record.state == state)
|
|
231
|
+
.count()
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/// Snapshot of the record with this id.
|
|
235
|
+
#[must_use]
|
|
236
|
+
pub fn get(&self, id: u64) -> Option<Entry> {
|
|
237
|
+
self.held(id).map(Record::view)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
fn held(&self, id: u64) -> Option<&Record> {
|
|
241
|
+
self.slots.iter().flatten().find(|record| record.id == id)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
fn check_time(&self, now: Duration) -> Result<(), Refusal> {
|
|
245
|
+
if now < self.observed {
|
|
246
|
+
Err(Refusal::TimeRegression)
|
|
247
|
+
} else {
|
|
248
|
+
Ok(())
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/// Admit a new pending record, claimable immediately.
|
|
253
|
+
///
|
|
254
|
+
/// Answers [`Enqueue::Duplicate`] while a record with this id is present;
|
|
255
|
+
/// that repeat changes nothing. `now` is recorded as observed only when
|
|
256
|
+
/// the record is actually admitted.
|
|
257
|
+
///
|
|
258
|
+
/// # Errors
|
|
259
|
+
/// [`Refusal::TimeRegression`] for backwards time (checked first, also for
|
|
260
|
+
/// a repeat), [`Refusal::Full`] when every slot is occupied.
|
|
261
|
+
pub fn enqueue(&mut self, id: u64, now: Duration) -> Result<Enqueue, Refusal> {
|
|
262
|
+
self.check_time(now)?;
|
|
263
|
+
if self.held(id).is_some() {
|
|
264
|
+
return Ok(Enqueue::Duplicate);
|
|
265
|
+
}
|
|
266
|
+
// The newest record ranks after every held one.
|
|
267
|
+
let seq = self.len();
|
|
268
|
+
let slot = self
|
|
269
|
+
.slots
|
|
270
|
+
.iter_mut()
|
|
271
|
+
.find(|slot| slot.is_none())
|
|
272
|
+
.ok_or(Refusal::Full)?;
|
|
273
|
+
self.observed = now;
|
|
274
|
+
*slot = Some(Record {
|
|
275
|
+
id,
|
|
276
|
+
seq,
|
|
277
|
+
state: State::Pending,
|
|
278
|
+
attempts: 0,
|
|
279
|
+
latest: None,
|
|
280
|
+
available_at: now,
|
|
281
|
+
failed: None,
|
|
282
|
+
});
|
|
283
|
+
Ok(Enqueue::Enqueued)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/// Claim the due pending record that was enqueued first.
|
|
287
|
+
///
|
|
288
|
+
/// Returns `None` when nothing is due. That is an honoured answer about
|
|
289
|
+
/// `now`, so `now` is recorded as observed either way: an earlier instant
|
|
290
|
+
/// is refused afterwards, which keeps "nothing was due at `now`" true.
|
|
291
|
+
/// The lease is a deadline for [`Outbox::expire_claims`]; it is not
|
|
292
|
+
/// enforced against late confirms.
|
|
293
|
+
///
|
|
294
|
+
/// The claim is stamped with an attempt identity from a sequence the
|
|
295
|
+
/// outbox never rewinds: forgetting a record does not free the identities
|
|
296
|
+
/// its attempts used. A scope holds `SEQUENCE_MAX` (2^48 - 1) of them.
|
|
297
|
+
///
|
|
298
|
+
/// # Errors
|
|
299
|
+
/// [`Refusal::TimeRegression`], [`Refusal::InvalidDuration`] for a zero
|
|
300
|
+
/// lease or a lease end that overflows, or [`Refusal::Exhausted`] when a
|
|
301
|
+
/// record is due but the attempt sequence is spent.
|
|
302
|
+
pub fn claim(&mut self, now: Duration, lease: Duration) -> Result<Option<Claimed>, Refusal> {
|
|
303
|
+
self.check_time(now)?;
|
|
304
|
+
let lease_expires = now.checked_add(lease).ok_or(Refusal::InvalidDuration)?;
|
|
305
|
+
if lease.is_zero() {
|
|
306
|
+
return Err(Refusal::InvalidDuration);
|
|
307
|
+
}
|
|
308
|
+
let pick = self
|
|
309
|
+
.slots
|
|
310
|
+
.iter_mut()
|
|
311
|
+
.flatten()
|
|
312
|
+
.filter(|record| record.state == State::Pending && record.available_at <= now)
|
|
313
|
+
.min_by_key(|record| record.seq);
|
|
314
|
+
let Some(record) = pick else {
|
|
315
|
+
self.observed = now;
|
|
316
|
+
return Ok(None);
|
|
317
|
+
};
|
|
318
|
+
let attempt = match self.attempts.issue() {
|
|
319
|
+
Ok(attempt) => attempt,
|
|
320
|
+
Err(periscope_machines::Refusal::Exhausted) => return Err(Refusal::Exhausted),
|
|
321
|
+
};
|
|
322
|
+
self.observed = now;
|
|
323
|
+
record.attempts = record.attempts.saturating_add(1);
|
|
324
|
+
record.latest = Some(Lease {
|
|
325
|
+
attempt,
|
|
326
|
+
expires: lease_expires,
|
|
327
|
+
});
|
|
328
|
+
record.state = State::Claimed;
|
|
329
|
+
record.failed = None;
|
|
330
|
+
Ok(Some(Claimed::issued(record.id, attempt, lease_expires)))
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/// An attempt this outbox never issued names nothing here: one of another
|
|
334
|
+
/// scope, one past what was issued, or sequence zero.
|
|
335
|
+
const fn check_issued(&self, attempt: u64) -> Result<(), Refusal> {
|
|
336
|
+
if self.attempts.owns(attempt) {
|
|
337
|
+
Ok(())
|
|
338
|
+
} else {
|
|
339
|
+
Err(Refusal::Stale)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/// The record `attempt` was issued to, in the order every report checks:
|
|
344
|
+
/// an attempt never issued here, then an id no record carries, then an
|
|
345
|
+
/// attempt that is not the record's latest.
|
|
346
|
+
fn reported(&mut self, id: u64, attempt: u64) -> Result<&mut Record, Refusal> {
|
|
347
|
+
self.check_issued(attempt)?;
|
|
348
|
+
let record = self
|
|
349
|
+
.slots
|
|
350
|
+
.iter_mut()
|
|
351
|
+
.flatten()
|
|
352
|
+
.find(|record| record.id == id)
|
|
353
|
+
.ok_or(Refusal::Unknown)?;
|
|
354
|
+
if record.is_latest(attempt) {
|
|
355
|
+
Ok(record)
|
|
356
|
+
} else {
|
|
357
|
+
Err(Refusal::Stale)
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/// Caller asserts the external effect was persisted for this attempt.
|
|
362
|
+
///
|
|
363
|
+
/// Accepted even after the lease deadline provided no newer attempt has
|
|
364
|
+
/// superseded it: the effect happened, so the record must not be retried.
|
|
365
|
+
///
|
|
366
|
+
/// Answers [`Confirmation::AlreadyConfirmed`] when this same attempt
|
|
367
|
+
/// already confirmed the record. A confirmed record is never claimed
|
|
368
|
+
/// again, so its latest attempt is the confirming one: that repeat is
|
|
369
|
+
/// provable for as long as the record is held, and changes nothing.
|
|
370
|
+
///
|
|
371
|
+
/// # Errors
|
|
372
|
+
/// In this order: [`Refusal::Stale`] for an attempt this outbox never
|
|
373
|
+
/// issued (another scope, or a sequence it has not reached), before any
|
|
374
|
+
/// record is looked up. [`Refusal::Unknown`] when no record carries the
|
|
375
|
+
/// id, which includes a confirmed record that was since forgotten.
|
|
376
|
+
/// [`Refusal::Stale`] when `attempt` is neither the live attempt nor the
|
|
377
|
+
/// confirming one, which includes an attempt of an earlier record that
|
|
378
|
+
/// carried this id.
|
|
379
|
+
pub fn confirm(&mut self, id: u64, attempt: u64) -> Result<Confirmation, Refusal> {
|
|
380
|
+
let record = self.reported(id, attempt)?;
|
|
381
|
+
match record.state {
|
|
382
|
+
State::Claimed => {
|
|
383
|
+
record.state = State::Confirmed;
|
|
384
|
+
Ok(Confirmation::Confirmed)
|
|
385
|
+
}
|
|
386
|
+
State::Confirmed => Ok(Confirmation::AlreadyConfirmed),
|
|
387
|
+
State::Pending | State::Dead => Err(Refusal::Stale),
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/// Caller reports a *known* failed attempt; retry after `retry_after`, or
|
|
392
|
+
/// die once `max_attempts` claims are spent.
|
|
393
|
+
///
|
|
394
|
+
/// Answers [`Failure::AlreadyFailed`] when `fail` already ended this same
|
|
395
|
+
/// attempt with this same `retry_after` and the record has not been
|
|
396
|
+
/// claimed since. That repeat changes nothing, not even the observed
|
|
397
|
+
/// clock, and carries the standing disposition. `now` is the instant of
|
|
398
|
+
/// the call, so it may differ; `retry_after` is what was reported, so a
|
|
399
|
+
/// different one is [`Refusal::Mismatch`], also for a record that died.
|
|
400
|
+
/// A repeat's arguments are still checked like any other call's.
|
|
401
|
+
///
|
|
402
|
+
/// An attempt reaped by [`Outbox::expire_claims`] was not failed: a `fail`
|
|
403
|
+
/// for it is [`Refusal::Stale`].
|
|
404
|
+
///
|
|
405
|
+
/// # Errors
|
|
406
|
+
/// In this order: [`Refusal::Stale`] for an attempt this outbox never
|
|
407
|
+
/// issued (another scope, or a sequence it has not reached), before any
|
|
408
|
+
/// record is looked up, [`Refusal::Unknown`] when no record carries the
|
|
409
|
+
/// id, [`Refusal::Stale`] when `attempt` is neither the live attempt nor
|
|
410
|
+
/// the one `fail` just ended, [`Refusal::TimeRegression`],
|
|
411
|
+
/// [`Refusal::InvalidDuration`] when `now + retry_after` overflows, and
|
|
412
|
+
/// [`Refusal::Mismatch`] for a repeat with another `retry_after`.
|
|
413
|
+
pub fn fail(
|
|
414
|
+
&mut self,
|
|
415
|
+
id: u64,
|
|
416
|
+
attempt: u64,
|
|
417
|
+
now: Duration,
|
|
418
|
+
retry_after: Duration,
|
|
419
|
+
) -> Result<Failure, Refusal> {
|
|
420
|
+
let (observed, max) = (self.observed, self.max_attempts.get());
|
|
421
|
+
let record = self.reported(id, attempt)?;
|
|
422
|
+
// The standing disposition of an attempt `fail` already ended.
|
|
423
|
+
let standing = match (record.state, record.failed) {
|
|
424
|
+
(State::Claimed, _) => None,
|
|
425
|
+
(State::Pending, Some(recorded)) => {
|
|
426
|
+
Some((recorded, Disposition::Retry(record.available_at)))
|
|
427
|
+
}
|
|
428
|
+
(State::Dead, Some(recorded)) => Some((recorded, Disposition::Dead)),
|
|
429
|
+
(State::Pending | State::Dead, None) | (State::Confirmed, _) => {
|
|
430
|
+
return Err(Refusal::Stale);
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
if now < observed {
|
|
434
|
+
return Err(Refusal::TimeRegression);
|
|
435
|
+
}
|
|
436
|
+
let available_at = now
|
|
437
|
+
.checked_add(retry_after)
|
|
438
|
+
.ok_or(Refusal::InvalidDuration)?;
|
|
439
|
+
if let Some((recorded, disposition)) = standing {
|
|
440
|
+
if recorded != retry_after {
|
|
441
|
+
return Err(Refusal::Mismatch);
|
|
442
|
+
}
|
|
443
|
+
return Ok(Failure::AlreadyFailed(disposition));
|
|
444
|
+
}
|
|
445
|
+
record.failed = Some(retry_after);
|
|
446
|
+
let disposition = Self::settle(record, max, available_at);
|
|
447
|
+
self.observed = now;
|
|
448
|
+
Ok(Failure::Failed(disposition))
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const fn settle(record: &mut Record, max: u32, available_at: Duration) -> Disposition {
|
|
452
|
+
if record.attempts >= max {
|
|
453
|
+
record.state = State::Dead;
|
|
454
|
+
Disposition::Dead
|
|
455
|
+
} else {
|
|
456
|
+
record.state = State::Pending;
|
|
457
|
+
record.available_at = available_at;
|
|
458
|
+
Disposition::Retry(available_at)
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/// Reap claims whose lease ended at or before `now`, writing at most
|
|
463
|
+
/// `out.len()` results and examining at most `max_scan` slots.
|
|
464
|
+
///
|
|
465
|
+
/// Every call that is not refused is honoured and records `now` as
|
|
466
|
+
/// observed, including one that reaps nothing.
|
|
467
|
+
///
|
|
468
|
+
/// Resumable: a cursor persists between calls. If `out` fills, the scan
|
|
469
|
+
/// stops *before* the next due claim, so nothing is lost; call again.
|
|
470
|
+
/// Expired claims retry immediately (or die at `max_attempts`).
|
|
471
|
+
///
|
|
472
|
+
/// The first [`Sweep::expired`] entries of `out` are written; the rest are
|
|
473
|
+
/// left untouched. Build the buffer as `[Expired::default(); K]`.
|
|
474
|
+
///
|
|
475
|
+
/// # Errors
|
|
476
|
+
/// [`Refusal::TimeRegression`].
|
|
477
|
+
pub fn expire_claims(
|
|
478
|
+
&mut self,
|
|
479
|
+
now: Duration,
|
|
480
|
+
max_scan: usize,
|
|
481
|
+
out: &mut [Expired],
|
|
482
|
+
) -> Result<Sweep, Refusal> {
|
|
483
|
+
self.check_time(now)?;
|
|
484
|
+
self.observed = now;
|
|
485
|
+
let max = self.max_attempts.get();
|
|
486
|
+
let (mut expired, mut scanned) = (0, 0);
|
|
487
|
+
while scanned < max_scan && self.scanned_in_pass < N {
|
|
488
|
+
// `cursor < N` always; an empty slot and that impossible miss
|
|
489
|
+
// alike hold nothing to reap. A claimed record always carries its
|
|
490
|
+
// lease, so matching on it skips no claim.
|
|
491
|
+
if let Some(Some(record)) = self.slots.get_mut(self.cursor)
|
|
492
|
+
&& record.state == State::Claimed
|
|
493
|
+
&& let Some(lease) = record.latest
|
|
494
|
+
&& lease.expires <= now
|
|
495
|
+
{
|
|
496
|
+
let Some(entry) = out.get_mut(expired) else {
|
|
497
|
+
break;
|
|
498
|
+
};
|
|
499
|
+
let disposition = Self::settle(record, max, now);
|
|
500
|
+
*entry = Expired::reaped(record.id, lease.attempt, disposition);
|
|
501
|
+
expired += 1;
|
|
502
|
+
}
|
|
503
|
+
// Each counter is below its loop bound, and the loop only runs
|
|
504
|
+
// when N > 0, so neither the steps nor `% N` can fault.
|
|
505
|
+
scanned += 1;
|
|
506
|
+
self.scanned_in_pass += 1;
|
|
507
|
+
self.cursor = (self.cursor + 1) % N;
|
|
508
|
+
}
|
|
509
|
+
let complete = self.scanned_in_pass >= N;
|
|
510
|
+
if complete {
|
|
511
|
+
self.scanned_in_pass = 0;
|
|
512
|
+
}
|
|
513
|
+
let pass = if complete {
|
|
514
|
+
Pass::Complete
|
|
515
|
+
} else {
|
|
516
|
+
Pass::Partial
|
|
517
|
+
};
|
|
518
|
+
Ok(Sweep::swept(expired, scanned, pass))
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/// Drop a confirmed or dead record, freeing its slot and its id.
|
|
522
|
+
///
|
|
523
|
+
/// The id may be enqueued again as a new record. The attempt identities
|
|
524
|
+
/// the dropped record used are not freed: a late report carrying one is
|
|
525
|
+
/// [`Refusal::Stale`] against the new record.
|
|
526
|
+
///
|
|
527
|
+
/// Answers [`Forgetting::NotHeld`] when no record carries the id: the
|
|
528
|
+
/// record is already gone, so that repeat is honoured and changes nothing.
|
|
529
|
+
///
|
|
530
|
+
/// # Errors
|
|
531
|
+
/// [`Refusal::NotTerminal`] for a pending or claimed record.
|
|
532
|
+
pub fn forget(&mut self, id: u64) -> Result<Forgetting, Refusal> {
|
|
533
|
+
let Some(record) = self.held(id) else {
|
|
534
|
+
return Ok(Forgetting::NotHeld);
|
|
535
|
+
};
|
|
536
|
+
match record.state {
|
|
537
|
+
State::Confirmed | State::Dead => {}
|
|
538
|
+
State::Pending | State::Claimed => return Err(Refusal::NotTerminal),
|
|
539
|
+
}
|
|
540
|
+
// Ranks are unique: drop that one and close the gap, so the held
|
|
541
|
+
// records keep ranks `0..len`.
|
|
542
|
+
let gone = record.seq;
|
|
543
|
+
for slot in &mut self.slots {
|
|
544
|
+
match slot {
|
|
545
|
+
Some(record) if record.seq == gone => *slot = None,
|
|
546
|
+
Some(record) if record.seq > gone => record.seq -= 1,
|
|
547
|
+
Some(_) | None => {}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
Ok(Forgetting::Forgotten)
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
#[cfg(test)]
|
|
555
|
+
extern crate std;
|
|
556
|
+
|
|
557
|
+
#[cfg(test)]
|
|
558
|
+
mod tests;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
//! The one answer for every call that changed nothing.
|
|
2
|
+
|
|
3
|
+
/// Why a call was not honoured. A refusal changes nothing: no record, no
|
|
4
|
+
/// cursor, and not the observed clock.
|
|
5
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
6
|
+
pub enum Refusal {
|
|
7
|
+
/// No record carries this id, and the attempt is one this outbox issued.
|
|
8
|
+
/// Answered by [`Outbox::confirm`](crate::Outbox::confirm) and
|
|
9
|
+
/// [`Outbox::fail`](crate::Outbox::fail) only; a forgotten record is unknown again.
|
|
10
|
+
Unknown,
|
|
11
|
+
/// `attempt` is neither the record's live attempt nor the attempt whose
|
|
12
|
+
/// outcome the call repeats: it was superseded, reaped, issued to an
|
|
13
|
+
/// earlier record that carried the same id, or never issued by this
|
|
14
|
+
/// outbox (another scope, or a sequence it has not reached). The last is
|
|
15
|
+
/// answered before any record is looked up, whatever the id.
|
|
16
|
+
Stale,
|
|
17
|
+
/// The record is not terminal, so it cannot be forgotten.
|
|
18
|
+
NotTerminal,
|
|
19
|
+
/// `now` is earlier than a previously observed instant.
|
|
20
|
+
TimeRegression,
|
|
21
|
+
/// A zero lease or an instant that overflows [`Duration`].
|
|
22
|
+
InvalidDuration,
|
|
23
|
+
/// The scope has no attempt identity left, so a due record cannot be
|
|
24
|
+
/// claimed. Answered by [`Outbox::claim`](crate::Outbox::claim) only.
|
|
25
|
+
Exhausted,
|
|
26
|
+
/// Every slot is occupied; nothing was evicted.
|
|
27
|
+
Full,
|
|
28
|
+
/// A repeated [`Outbox::fail`](crate::Outbox::fail) names a `retry_after` other than the one
|
|
29
|
+
/// recorded for that attempt, so it is not the same report.
|
|
30
|
+
Mismatch,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
impl core::fmt::Display for Refusal {
|
|
34
|
+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
|
35
|
+
f.write_str(match self {
|
|
36
|
+
Self::Unknown => "no record carries this id",
|
|
37
|
+
Self::Stale => "the attempt is not the live one",
|
|
38
|
+
Self::NotTerminal => "the record is not confirmed or dead",
|
|
39
|
+
Self::TimeRegression => "now is earlier than an observed instant",
|
|
40
|
+
Self::InvalidDuration => "zero lease or overflowing instant",
|
|
41
|
+
Self::Exhausted => "the attempt sequence is spent",
|
|
42
|
+
Self::Full => "every slot is occupied",
|
|
43
|
+
Self::Mismatch => "retry_after is not the one recorded for this attempt",
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
impl core::error::Error for Refusal {}
|