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.
@@ -0,0 +1,298 @@
1
+ //! The values the outbox answers with, and their validating constructors.
2
+ use core::time::Duration;
3
+
4
+ use periscope_machines::{scope_of, sequence_of};
5
+
6
+ use crate::State;
7
+
8
+ /// `true` for an attempt identity some outbox could have issued: its sequence
9
+ /// starts at 1, so sequence zero names nothing in any scope.
10
+ const fn issuable(attempt: u64) -> bool {
11
+ sequence_of(attempt) != 0
12
+ }
13
+
14
+ /// A successful claim: the id plus the attempt identity that must accompany
15
+ /// [`Outbox::confirm`] and [`Outbox::fail`].
16
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
17
+ pub struct Claimed {
18
+ id: u64,
19
+ attempt: u64,
20
+ lease_expires: Duration,
21
+ }
22
+
23
+ impl Claimed {
24
+ /// A claim value, or `None` for one no outbox answers: an `attempt` whose
25
+ /// sequence is zero (identities start at 1), or a zero `lease_expires`
26
+ /// (a lease is never zero, so it ends after the epoch).
27
+ #[must_use]
28
+ pub const fn new(id: u64, attempt: u64, lease_expires: Duration) -> Option<Self> {
29
+ if issuable(attempt) && !lease_expires.is_zero() {
30
+ Some(Self::issued(id, attempt, lease_expires))
31
+ } else {
32
+ None
33
+ }
34
+ }
35
+
36
+ /// The claim the outbox just made; it upholds what [`Claimed::new`] checks.
37
+ pub(crate) const fn issued(id: u64, attempt: u64, lease_expires: Duration) -> Self {
38
+ Self {
39
+ id,
40
+ attempt,
41
+ lease_expires,
42
+ }
43
+ }
44
+
45
+ /// Claimed record id.
46
+ #[must_use]
47
+ pub const fn id(&self) -> u64 {
48
+ self.id
49
+ }
50
+
51
+ /// Identity of this attempt: issued once for the lifetime of the outbox
52
+ /// and never again, not even after the record is forgotten and its id
53
+ /// enqueued anew. It carries the outbox's scope above a sequence that
54
+ /// starts at 1, so scope zero issues 1, 2, 3. It is not the record's
55
+ /// attempt count; that is [`Entry::attempts`].
56
+ #[must_use]
57
+ pub const fn attempt(&self) -> u64 {
58
+ self.attempt
59
+ }
60
+
61
+ /// Instant at which the lease may be reaped by [`Outbox::expire_claims`].
62
+ #[must_use]
63
+ pub const fn lease_expires(&self) -> Duration {
64
+ self.lease_expires
65
+ }
66
+
67
+ /// The scope of the outbox that issued this attempt, see
68
+ /// [`Outbox::with_scope`].
69
+ #[must_use]
70
+ pub const fn scope(&self) -> u16 {
71
+ scope_of(self.attempt)
72
+ }
73
+ }
74
+
75
+ /// Where a failed or expired attempt went.
76
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
77
+ pub enum Disposition {
78
+ /// Back to pending, claimable at or after the given instant.
79
+ Retry(Duration),
80
+ /// Attempts exhausted.
81
+ Dead,
82
+ }
83
+
84
+ /// One claim reaped by [`Outbox::expire_claims`].
85
+ ///
86
+ /// An expired attempt is an *unknown* outcome: the worker may still be running
87
+ /// or may have produced the external effect. Reconcile before assuming a retry
88
+ /// is safe.
89
+ ///
90
+ /// `Expired::default()` is a placeholder for pre-filling the output buffer:
91
+ /// its attempt is 0, which no outbox of any scope issues, so the outbox never
92
+ /// emits it.
93
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
94
+ pub struct Expired {
95
+ id: u64,
96
+ attempt: u64,
97
+ disposition: Disposition,
98
+ }
99
+
100
+ impl Expired {
101
+ /// A reaped claim, or `None` for an `attempt` whose sequence is zero: no
102
+ /// outbox issues it, so none reaps it. The placeholder with attempt 0 is
103
+ /// [`Expired::default`] only.
104
+ #[must_use]
105
+ pub const fn new(id: u64, attempt: u64, disposition: Disposition) -> Option<Self> {
106
+ if issuable(attempt) {
107
+ Some(Self::reaped(id, attempt, disposition))
108
+ } else {
109
+ None
110
+ }
111
+ }
112
+
113
+ /// A claim the outbox just reaped; its attempt was issued, so it upholds
114
+ /// what [`Expired::new`] checks.
115
+ pub(crate) const fn reaped(id: u64, attempt: u64, disposition: Disposition) -> Self {
116
+ Self {
117
+ id,
118
+ attempt,
119
+ disposition,
120
+ }
121
+ }
122
+
123
+ /// Record id.
124
+ #[must_use]
125
+ pub const fn id(&self) -> u64 {
126
+ self.id
127
+ }
128
+
129
+ /// Identity of the attempt whose lease ran out.
130
+ #[must_use]
131
+ pub const fn attempt(&self) -> u64 {
132
+ self.attempt
133
+ }
134
+
135
+ /// What became of the record.
136
+ #[must_use]
137
+ pub const fn disposition(&self) -> Disposition {
138
+ self.disposition
139
+ }
140
+
141
+ /// The scope of the outbox that issued the reaped attempt.
142
+ #[must_use]
143
+ pub const fn scope(&self) -> u16 {
144
+ scope_of(self.attempt)
145
+ }
146
+ }
147
+
148
+ impl Default for Expired {
149
+ fn default() -> Self {
150
+ Self::reaped(0, 0, Disposition::Dead)
151
+ }
152
+ }
153
+
154
+ /// Where the sweep cursor stands after an [`Outbox::expire_claims`] call.
155
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
156
+ pub enum Pass {
157
+ /// Some slot has not been examined since the last full pass: call again.
158
+ Partial,
159
+ /// The cursor completed a full pass over every slot, cumulatively across
160
+ /// calls; the next call starts a new pass.
161
+ Complete,
162
+ }
163
+
164
+ /// Progress of one bounded [`Outbox::expire_claims`] call.
165
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
166
+ pub struct Sweep {
167
+ expired: usize,
168
+ scanned: usize,
169
+ pass: Pass,
170
+ }
171
+
172
+ impl Sweep {
173
+ /// A sweep report, or `None` when `expired` exceeds `scanned`: every
174
+ /// entry written came from a slot the call examined.
175
+ #[must_use]
176
+ pub const fn new(expired: usize, scanned: usize, pass: Pass) -> Option<Self> {
177
+ if expired <= scanned {
178
+ Some(Self::swept(expired, scanned, pass))
179
+ } else {
180
+ None
181
+ }
182
+ }
183
+
184
+ /// The report of a sweep that wrote only entries it scanned.
185
+ pub(crate) const fn swept(expired: usize, scanned: usize, pass: Pass) -> Self {
186
+ Self {
187
+ expired,
188
+ scanned,
189
+ pass,
190
+ }
191
+ }
192
+
193
+ /// Expired claims written to the front of the caller's buffer.
194
+ #[must_use]
195
+ pub const fn expired(&self) -> usize {
196
+ self.expired
197
+ }
198
+
199
+ /// Slots examined by this call.
200
+ #[must_use]
201
+ pub const fn scanned(&self) -> usize {
202
+ self.scanned
203
+ }
204
+
205
+ /// Where the cursor stands: call again until it is [`Pass::Complete`].
206
+ #[must_use]
207
+ pub const fn pass(&self) -> Pass {
208
+ self.pass
209
+ }
210
+ }
211
+
212
+ /// A read-only view of one record.
213
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
214
+ pub struct Entry {
215
+ id: u64,
216
+ state: State,
217
+ attempts: u32,
218
+ attempt: Option<u64>,
219
+ available_at: Duration,
220
+ }
221
+
222
+ impl Entry {
223
+ /// A record view, or `None` for one no outbox holds. `attempt` is `None`
224
+ /// exactly when `attempts` is zero, a present `attempt` has a sequence of
225
+ /// at least 1, and only a [`State::Pending`] record may be unclaimed.
226
+ #[must_use]
227
+ pub const fn new(
228
+ id: u64,
229
+ state: State,
230
+ attempts: u32,
231
+ attempt: Option<u64>,
232
+ available_at: Duration,
233
+ ) -> Option<Self> {
234
+ let claimed = match attempt {
235
+ Some(attempt) if issuable(attempt) => true,
236
+ Some(_) => return None,
237
+ None => false,
238
+ };
239
+ let reachable = match state {
240
+ State::Pending => true,
241
+ State::Claimed | State::Confirmed | State::Dead => claimed,
242
+ };
243
+ if reachable && claimed == (attempts != 0) {
244
+ Some(Self::held(id, state, attempts, attempt, available_at))
245
+ } else {
246
+ None
247
+ }
248
+ }
249
+
250
+ /// The view of a record the outbox holds; it upholds what [`Entry::new`]
251
+ /// checks.
252
+ pub(crate) const fn held(
253
+ id: u64,
254
+ state: State,
255
+ attempts: u32,
256
+ attempt: Option<u64>,
257
+ available_at: Duration,
258
+ ) -> Self {
259
+ Self {
260
+ id,
261
+ state,
262
+ attempts,
263
+ attempt,
264
+ available_at,
265
+ }
266
+ }
267
+
268
+ /// Record id.
269
+ #[must_use]
270
+ pub const fn id(&self) -> u64 {
271
+ self.id
272
+ }
273
+
274
+ /// Current state.
275
+ #[must_use]
276
+ pub const fn state(&self) -> State {
277
+ self.state
278
+ }
279
+
280
+ /// Claims issued to this record so far; it dies at `max_attempts`.
281
+ #[must_use]
282
+ pub const fn attempts(&self) -> u32 {
283
+ self.attempts
284
+ }
285
+
286
+ /// Identity of the latest attempt, the one [`Claimed::attempt`] carried;
287
+ /// `None` until the record is first claimed.
288
+ #[must_use]
289
+ pub const fn attempt(&self) -> Option<u64> {
290
+ self.attempt
291
+ }
292
+
293
+ /// Earliest instant a pending record may be claimed.
294
+ #[must_use]
295
+ pub const fn available_at(&self) -> Duration {
296
+ self.available_at
297
+ }
298
+ }
@@ -0,0 +1,2 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'ffi/extconf'
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "outbox_machines_native"
3
+ version = "0.1.8"
4
+ edition.workspace = true
5
+ rust-version.workspace = true
6
+ license.workspace = true
7
+ publish = false
8
+
9
+ [lib]
10
+ crate-type = ["cdylib"]
11
+ test = false
12
+ doctest = false
13
+
14
+ [dependencies]
15
+ outbox-machines.workspace = true
16
+ magnus.workspace = true
17
+ rb-sys.workspace = true
18
+ matryona-machines = { workspace = true, features = ["ruby"] }
19
+
20
+ [lints]
21
+ workspace = true
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+ require 'mkmf'
3
+ require 'pathname'
4
+ require 'rb_sys/mkmf'
5
+
6
+ create_rust_makefile('outbox_machines_native/outbox_machines_native') do |e|
7
+ e.ext_dir = Pathname(__dir__).relative_path_from(Pathname(Dir.pwd)).to_s
8
+ e.profile = ENV.fetch('RB_SYS_CARGO_PROFILE', :release).to_sym
9
+ end
10
+ makefile = File.join(Dir.pwd, 'Makefile')
11
+ File.write(makefile, File.read(makefile).gsub(
12
+ /^RB_SYS_CARGO_MANIFEST_DIR \?=.*$/,
13
+ "RB_SYS_CARGO_MANIFEST_DIR ?= #{File.expand_path(__dir__)}"
14
+ ))
@@ -0,0 +1,37 @@
1
+ //! The value classes, resolved once at init and pinned. The exact-class
2
+ //! reads and clone-then-keep are `matryona_machines::ruby`'s.
3
+ use magnus::{Error, RModule, Ruby};
4
+ use matryona_machines::ruby::Class;
5
+
6
+ /// The `Data` classes the binding builds and reads.
7
+ pub struct Classes {
8
+ pub claimed: Class,
9
+ pub retry: Class,
10
+ pub failed: Class,
11
+ pub already_failed: Class,
12
+ pub expired: Class,
13
+ pub sweep: Class,
14
+ pub entry: Class,
15
+ }
16
+
17
+ matryona_machines::registry! {
18
+ static CLASSES: Classes = "outbox_machines";
19
+ /// The classes resolved at init.
20
+ pub fn classes;
21
+ }
22
+
23
+ /// Resolves the classes `lib/outbox_machines.rb` defined before it loaded the
24
+ /// extension. Called once, from init; never by name again.
25
+ pub fn resolve(ruby: &Ruby, module: RModule) -> Result<(), Error> {
26
+ let class = |name| Class::resolve(ruby, module, name);
27
+ let classes = Classes {
28
+ claimed: class("Claimed")?,
29
+ retry: class("Retry")?,
30
+ failed: class("Failed")?,
31
+ already_failed: class("AlreadyFailed")?,
32
+ expired: class("Expired")?,
33
+ sweep: class("Sweep")?,
34
+ entry: class("Entry")?,
35
+ };
36
+ CLASSES.set(ruby, classes).map(drop)
37
+ }
@@ -0,0 +1,35 @@
1
+ //! Private native entry point.
2
+ use crate::{CAPACITY, Outbox, scope_of};
3
+ use magnus::{Error, Ruby, function, method, prelude::*};
4
+ use matryona_machines::ruby::Class;
5
+
6
+ #[magnus::init]
7
+ fn init(ruby: &Ruby) -> Result<(), Error> {
8
+ let module = ruby.define_module("OutboxMachines")?;
9
+ module.const_set("CAPACITY", CAPACITY)?;
10
+ crate::classes::resolve(ruby, module)?;
11
+ crate::values::define(module)?;
12
+ let class = module.define_class("Outbox", ruby.class_object())?;
13
+ class.undef_default_alloc_func();
14
+ class.define_singleton_method("new", function!(Outbox::new, 1))?;
15
+ class.define_singleton_method("with_scope", function!(Outbox::with_scope, 2))?;
16
+ class.define_singleton_method("resumed", function!(Outbox::resumed, 3))?;
17
+ class.define_method("scope", method!(Outbox::scope, 0))?;
18
+ class.define_method("issued", method!(Outbox::issued, 0))?;
19
+ class.define_singleton_method("__scope_of", function!(scope_of, 1))?;
20
+ class.define_method("capacity", method!(Outbox::capacity, 0))?;
21
+ class.define_method("max_attempts", method!(Outbox::max_attempts, 0))?;
22
+ class.define_method("size", method!(Outbox::size, 0))?;
23
+ class.define_method("empty?", method!(Outbox::is_empty, 0))?;
24
+ class.define_method("enqueue", method!(Outbox::enqueue, 2))?;
25
+ class.define_method("claim", method!(Outbox::claim, 2))?;
26
+ class.define_method("confirm", method!(Outbox::confirm, 2))?;
27
+ class.define_method("fail", method!(Outbox::fail, 4))?;
28
+ class.define_method("expire_claims", method!(Outbox::expire_claims, 2))?;
29
+ class.define_method("forget", method!(Outbox::forget, 1))?;
30
+ class.define_method("get", method!(Outbox::get, 1))?;
31
+ class.define_method("count", method!(Outbox::count, 1))?;
32
+ // `new`, `with_scope` and `resumed` answer an Outbox: its class is fixed
33
+ // now, so no conversion runs `Object.const_get` later.
34
+ Class::pin_wrapped::<Outbox>(ruby, class).map(drop)
35
+ }