causal_machines 0.6.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,200 @@
1
+ //! Fixed memberships and the version vectors counted over them.
2
+
3
+ use crate::{Refusal, ReplicaId};
4
+
5
+ /// How two version vectors relate in the causal partial order.
6
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7
+ pub enum Causality {
8
+ /// Both have seen exactly the same events.
9
+ Equal,
10
+ /// The left side has seen a strict subset of the right side's events.
11
+ Before,
12
+ /// The left side has seen a strict superset of the right side's events.
13
+ After,
14
+ /// Each side has seen an event the other has not.
15
+ Concurrent,
16
+ }
17
+
18
+ /// Up to `N` distinct replicas, each bound to one slot for good.
19
+ ///
20
+ /// Membership never changes. A different set of replicas is a different
21
+ /// membership, and the caller gives it a new generation.
22
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
23
+ pub struct Membership<const N: usize> {
24
+ ids: [ReplicaId; N],
25
+ len: usize,
26
+ }
27
+
28
+ impl<const N: usize> Membership<N> {
29
+ /// Binds each replica in `ids` to the slot of its position.
30
+ ///
31
+ /// Returns `None` when `ids` holds more than `N` replicas or names one
32
+ /// twice.
33
+ #[must_use]
34
+ pub fn from_slice(ids: &[ReplicaId]) -> Option<Self> {
35
+ if ids.len() > N {
36
+ return None;
37
+ }
38
+ let mut bound = [0; N];
39
+ for (index, (slot, id)) in bound.iter_mut().zip(ids).enumerate() {
40
+ if ids.iter().take(index).any(|earlier| earlier == id) {
41
+ return None;
42
+ }
43
+ *slot = *id;
44
+ }
45
+ Some(Self {
46
+ ids: bound,
47
+ len: ids.len(),
48
+ })
49
+ }
50
+
51
+ /// Number of member replicas.
52
+ #[must_use]
53
+ pub const fn len(&self) -> usize {
54
+ self.len
55
+ }
56
+
57
+ /// Whether no replica is a member.
58
+ #[must_use]
59
+ pub const fn is_empty(&self) -> bool {
60
+ self.len == 0
61
+ }
62
+
63
+ /// Member replicas in slot order.
64
+ #[must_use]
65
+ pub fn ids(&self) -> &[ReplicaId] {
66
+ self.ids.get(..self.len).unwrap_or_else(|| {
67
+ debug_assert!(false, "len never exceeds N");
68
+ &[]
69
+ })
70
+ }
71
+
72
+ /// Slot bound to `replica`.
73
+ #[must_use]
74
+ pub fn slot(&self, replica: ReplicaId) -> Option<usize> {
75
+ self.ids().iter().position(|id| *id == replica)
76
+ }
77
+
78
+ /// Replica bound to `slot`.
79
+ #[must_use]
80
+ pub fn replica(&self, slot: usize) -> Option<ReplicaId> {
81
+ self.ids().get(slot).copied()
82
+ }
83
+
84
+ /// Whether `clock` counts nothing outside this membership's slots.
85
+ #[must_use]
86
+ pub fn admits(&self, clock: &VersionVector<N>) -> bool {
87
+ clock
88
+ .counters
89
+ .iter()
90
+ .skip(self.len)
91
+ .all(|count| *count == 0)
92
+ }
93
+ }
94
+
95
+ /// One event counter per membership slot.
96
+ ///
97
+ /// Entry `k` is the number of events from slot `k`'s replica this vector has
98
+ /// seen. Vectors are only comparable within one membership generation.
99
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
100
+ pub struct VersionVector<const N: usize> {
101
+ counters: [u64; N],
102
+ }
103
+
104
+ impl<const N: usize> Default for VersionVector<N> {
105
+ fn default() -> Self {
106
+ Self::new()
107
+ }
108
+ }
109
+
110
+ impl<const N: usize> VersionVector<N> {
111
+ /// A vector that has seen nothing.
112
+ #[must_use]
113
+ pub const fn new() -> Self {
114
+ Self { counters: [0; N] }
115
+ }
116
+
117
+ /// A vector holding exactly `counters`, in slot order.
118
+ #[must_use]
119
+ pub const fn from_counters(counters: [u64; N]) -> Self {
120
+ Self { counters }
121
+ }
122
+
123
+ /// Counters in slot order.
124
+ #[must_use]
125
+ pub const fn counters(&self) -> &[u64; N] {
126
+ &self.counters
127
+ }
128
+
129
+ /// Counter at `slot`, or `None` past the last slot.
130
+ #[must_use]
131
+ pub fn get(&self, slot: usize) -> Option<u64> {
132
+ self.counters.get(slot).copied()
133
+ }
134
+
135
+ /// Counts one more event at `slot` and returns the new counter.
136
+ ///
137
+ /// # Errors
138
+ ///
139
+ /// [`Refusal::UnknownMember`] past the last slot, [`Refusal::Exhausted`]
140
+ /// at `u64::MAX`. The vector is unchanged in both cases.
141
+ pub fn increment(&mut self, slot: usize) -> Result<u64, Refusal> {
142
+ let counter = self.counters.get_mut(slot).ok_or(Refusal::UnknownMember)?;
143
+ let next = counter.checked_add(1).ok_or(Refusal::Exhausted)?;
144
+ *counter = next;
145
+ Ok(next)
146
+ }
147
+
148
+ /// Where this vector sits relative to `other` in the causal order.
149
+ #[must_use]
150
+ pub fn compare(&self, other: &Self) -> Causality {
151
+ let mut behind = false;
152
+ let mut ahead = false;
153
+ for (mine, theirs) in self.counters.iter().zip(&other.counters) {
154
+ behind |= mine < theirs;
155
+ ahead |= mine > theirs;
156
+ }
157
+ match (behind, ahead) {
158
+ (false, false) => Causality::Equal,
159
+ (true, false) => Causality::Before,
160
+ (false, true) => Causality::After,
161
+ (true, true) => Causality::Concurrent,
162
+ }
163
+ }
164
+
165
+ /// Whether this vector has seen everything `other` has (equal counts).
166
+ #[must_use]
167
+ pub fn dominates(&self, other: &Self) -> bool {
168
+ match self.compare(other) {
169
+ Causality::Equal | Causality::After => true,
170
+ Causality::Before | Causality::Concurrent => false,
171
+ }
172
+ }
173
+
174
+ /// Whether each vector has seen an event the other has not.
175
+ #[must_use]
176
+ pub fn concurrent(&self, other: &Self) -> bool {
177
+ self.compare(other) == Causality::Concurrent
178
+ }
179
+
180
+ /// Raises every counter to the larger of the two sides.
181
+ ///
182
+ /// Commutative, associative and idempotent; with a fixed `N` it cannot
183
+ /// run out of room.
184
+ pub fn merge(&mut self, other: &Self) {
185
+ for (mine, theirs) in self.counters.iter_mut().zip(&other.counters) {
186
+ *mine = (*mine).max(*theirs);
187
+ }
188
+ }
189
+
190
+ /// The merge of both vectors, leaving each untouched.
191
+ #[must_use]
192
+ pub fn merged(mut self, other: &Self) -> Self {
193
+ self.merge(other);
194
+ self
195
+ }
196
+
197
+ pub(crate) fn counter_mut(&mut self, slot: usize) -> Option<&mut u64> {
198
+ self.counters.get_mut(slot)
199
+ }
200
+ }
@@ -0,0 +1,2 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'ffi/extconf'
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "causal_machines_native"
3
+ version = "0.1.6"
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
+ causal-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('causal_machines_native/causal_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,43 @@
1
+ //! The `Data` classes, resolved once at load and pinned. The exact-class
2
+ //! reads and clone-then-keep are `matryona_machines::ruby`'s.
3
+ //!
4
+ //! A value read back must be an instance of exactly the gem's class: a
5
+ //! subclass constant leaks past the seal and `Data#initialize` can be bound
6
+ //! directly, so `is_a?` is not enough. Its fields are read straight from the
7
+ //! struct (no reader runs) and rebuilt through the core constructor, which
8
+ //! `Marshal.load` skipped.
9
+ use magnus::{Error, RModule, Ruby};
10
+ use matryona_machines::ruby::Class;
11
+
12
+ /// Every `Data` class the binding checks or builds.
13
+ pub struct Classes {
14
+ pub vector: Class,
15
+ pub membership: Class,
16
+ pub stamp: Class,
17
+ pub deliver: Class,
18
+ pub obsolete: Class,
19
+ pub gap: Class,
20
+ pub page: Class,
21
+ }
22
+
23
+ matryona_machines::registry! {
24
+ static CLASSES: Classes = "causal_machines";
25
+ /// The classes resolved at load.
26
+ pub fn classes;
27
+ }
28
+
29
+ /// Resolve the classes `causal_machines.rb` defined before requiring the
30
+ /// extension.
31
+ pub fn resolve(ruby: &Ruby, module: RModule) -> Result<&'static Classes, Error> {
32
+ let class = |name| Class::resolve(ruby, module, name);
33
+ let resolved = Classes {
34
+ vector: class("VersionVector")?,
35
+ membership: class("Membership")?,
36
+ stamp: class("Stamp")?,
37
+ deliver: class("Deliver")?,
38
+ obsolete: class("Obsolete")?,
39
+ gap: class("Gap")?,
40
+ page: class("Page")?,
41
+ };
42
+ CLASSES.set(ruby, resolved)
43
+ }
@@ -0,0 +1,56 @@
1
+ //! Private native entry point.
2
+ use crate::{HOLD, MEMBERS, Tracker, classes, values, vectors};
3
+ use magnus::{Error, RModule, 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("CausalMachines")?;
9
+ module.const_set("MEMBERS", MEMBERS)?;
10
+ module.const_set("CAPACITY", HOLD)?;
11
+ hooks(module)?;
12
+ let classes = classes::resolve(ruby, module)?;
13
+ let vector = classes.vector.get(ruby);
14
+ vector.define_method("get", method!(vectors::get, 1))?;
15
+ vector.define_method("increment", method!(vectors::increment, 1))?;
16
+ vector.define_method("compare", method!(vectors::compare, 1))?;
17
+ vector.define_method("dominates?", method!(vectors::dominates, 1))?;
18
+ vector.define_method("concurrent?", method!(vectors::concurrent, 1))?;
19
+ vector.define_method("merged", method!(vectors::merged, 1))?;
20
+ let membership = classes.membership.get(ruby);
21
+ membership.define_method("slot", method!(vectors::slot, 1))?;
22
+ membership.define_method("replica", method!(vectors::replica, 1))?;
23
+ membership.define_method("len", method!(vectors::len, 0))?;
24
+ membership.define_method("empty?", method!(vectors::is_empty, 0))?;
25
+ membership.define_method("admits?", method!(vectors::admits, 1))?;
26
+ let class = module.define_class("Causal", ruby.class_object())?;
27
+ class.undef_default_alloc_func();
28
+ class.define_singleton_method("new", function!(Tracker::new, 3))?;
29
+ class.define_singleton_method("restore", function!(Tracker::restore, 4))?;
30
+ class.define_method("stamp", method!(Tracker::stamp, 0))?;
31
+ class.define_method("check", method!(Tracker::check, 1))?;
32
+ class.define_method("receive", method!(Tracker::receive, 1))?;
33
+ class.define_method("release", method!(Tracker::release, 0))?;
34
+ class.define_method("forget", method!(Tracker::forget, 2))?;
35
+ class.define_method("missing", method!(Tracker::missing, 3))?;
36
+ class.define_method("absorb", method!(Tracker::absorb, 2))?;
37
+ class.define_method("clock", method!(Tracker::clock, 0))?;
38
+ class.define_method("held", method!(Tracker::held, 0))?;
39
+ class.define_method("membership", method!(Tracker::membership, 0))?;
40
+ class.define_method("local", method!(Tracker::local, 0))?;
41
+ class.define_method("generation", method!(Tracker::generation, 0))?;
42
+ class.define_method("capacity", function!(Tracker::capacity, 0))?;
43
+ // Fix magnus's class for Causal now: building one later runs no Ruby.
44
+ Class::pin_wrapped::<Tracker>(ruby, class).map(drop)
45
+ }
46
+
47
+ /// The private validating hooks the `Data` values call from `initialize`.
48
+ fn hooks(module: RModule) -> Result<(), Error> {
49
+ module.define_singleton_method("__counters", function!(vectors::checked_counters, 1))?;
50
+ module.define_singleton_method("__ids", function!(vectors::checked_ids, 1))?;
51
+ module.define_singleton_method("__stamp", function!(values::checked_stamp, 3))?;
52
+ module.define_singleton_method("__release", function!(values::checked_release, 1))?;
53
+ module.define_singleton_method("__gap", function!(values::checked_gap_fields, 3))?;
54
+ module.define_singleton_method("__page", function!(values::checked_page, 2))?;
55
+ Ok(())
56
+ }
@@ -0,0 +1,247 @@
1
+ //! Thin binding to the causal-delivery tracker and its version vectors.
2
+ mod classes;
3
+ mod init;
4
+ mod values;
5
+ mod vectors;
6
+
7
+ use std::cell::RefCell;
8
+
9
+ use causal_machines::{Absorbing, Causal, Forgetting, Gap, Readiness, Receipt, Refusal, Release};
10
+ use classes::classes;
11
+ use magnus::{Error, Ruby, Value, prelude::*, typed_data::Obj};
12
+ use matryona_machines::ruby::{Symbols, integer, integer_in, keep};
13
+ use values::{gap_value, stamp_value};
14
+ use vectors::{Clock, clock, clock_value, members, members_value};
15
+
16
+ const MEMBERS: usize = 8;
17
+ const HOLD: usize = 64;
18
+
19
+ type Core = Causal<MEMBERS, HOLD>;
20
+
21
+ /// A `RangeError`: right type, a value the core does not accept.
22
+ fn range_error(ruby: &Ruby, message: impl Into<std::borrow::Cow<'static, str>>) -> Error {
23
+ Error::new(ruby.exception_range_error(), message)
24
+ }
25
+
26
+ matryona_machines::symbols! {
27
+ /// The core's refusals, each the snake case of its variant.
28
+ pub(crate) Refusals for Refusal as "a refusal" {
29
+ UnknownMember => "unknown_member",
30
+ StaleGeneration => "stale_generation",
31
+ FutureGeneration => "future_generation",
32
+ Exhausted => "exhausted",
33
+ Conflict => "conflict",
34
+ Malformed => "malformed",
35
+ Full => "full",
36
+ }
37
+ }
38
+
39
+ matryona_machines::symbols! {
40
+ /// What `check` answers.
41
+ Readinesses for Readiness as "a readiness" {
42
+ Deliverable => "deliverable",
43
+ Duplicate => "duplicate",
44
+ Missing => "missing",
45
+ }
46
+ }
47
+
48
+ matryona_machines::symbols! {
49
+ /// What `receive` answers.
50
+ Receipts for Receipt as "a receipt" {
51
+ Delivered => "delivered",
52
+ Held => "held",
53
+ AlreadyHeld => "already_held",
54
+ Duplicate => "duplicate",
55
+ }
56
+ }
57
+
58
+ matryona_machines::symbols! {
59
+ /// What `forget` answers.
60
+ Forgettings for Forgetting as "a forgetting" {
61
+ Forgotten => "forgotten",
62
+ NotHeld => "not_held",
63
+ }
64
+ }
65
+
66
+ matryona_machines::symbols! {
67
+ /// What `absorb` answers.
68
+ Absorbings for Absorbing as "an absorbing" {
69
+ Absorbed => "absorbed",
70
+ AlreadyCovered => "already_covered",
71
+ }
72
+ }
73
+
74
+ /// The refusal's symbol.
75
+ fn refusal(ruby: &Ruby, refusal: Refusal) -> Value {
76
+ Refusals::symbol(ruby, refusal).as_value()
77
+ }
78
+
79
+ /// The symbol naming an honoured outcome through its table `T`, or the
80
+ /// refusal's symbol.
81
+ fn answer<T: Symbols>(ruby: &Ruby, outcome: Result<T::Variant, Refusal>) -> Value {
82
+ match outcome {
83
+ Ok(honoured) => T::symbol(ruby, honoured).as_value(),
84
+ Err(why) => refusal(ruby, why),
85
+ }
86
+ }
87
+
88
+ #[magnus::wrap(class = "CausalMachines::Causal", free_immediately, size)]
89
+ struct Tracker {
90
+ core: RefCell<Core>,
91
+ }
92
+
93
+ impl Tracker {
94
+ fn new(ruby: &Ruby, members: Value, local: Value, generation: Value) -> Result<Self, Error> {
95
+ Self::build(ruby, members, local, generation, None)
96
+ }
97
+
98
+ fn restore(
99
+ ruby: &Ruby,
100
+ members: Value,
101
+ local: Value,
102
+ generation: Value,
103
+ delivered: Value,
104
+ ) -> Result<Self, Error> {
105
+ Self::build(ruby, members, local, generation, Some(delivered))
106
+ }
107
+
108
+ fn build(
109
+ ruby: &Ruby,
110
+ membership: Value,
111
+ local: Value,
112
+ generation: Value,
113
+ delivered: Option<Value>,
114
+ ) -> Result<Self, Error> {
115
+ let (local, generation) = (integer(local, "local")?, integer(generation, "generation")?);
116
+ let membership = members(ruby, membership)?;
117
+ let delivered = match delivered {
118
+ Some(value) => clock(ruby, value)?,
119
+ None => Clock::new(),
120
+ };
121
+ let core = Causal::restore(membership, local, generation, delivered).ok_or_else(|| {
122
+ range_error(
123
+ ruby,
124
+ "local must be a member, and delivered must count member slots only",
125
+ )
126
+ })?;
127
+ Ok(Self {
128
+ core: RefCell::new(core),
129
+ })
130
+ }
131
+
132
+ /// Clone-then-keep: the answer is a `Stamp` built through `new`.
133
+ fn stamp(ruby: &Ruby, this: Obj<Self>) -> Result<Value, Error> {
134
+ keep(
135
+ ruby,
136
+ this,
137
+ &this.core,
138
+ Core::stamp,
139
+ |outcome| match outcome {
140
+ Ok(stamp) => stamp_value(ruby, &stamp),
141
+ Err(why) => Ok(refusal(ruby, why)),
142
+ },
143
+ )
144
+ }
145
+
146
+ fn check(ruby: &Ruby, this: Obj<Self>, stamp: Value) -> Result<Value, Error> {
147
+ let stamp = values::stamp(ruby, stamp)?;
148
+ let outcome = this.core.borrow().check(&stamp);
149
+ Ok(answer::<Readinesses>(ruby, outcome))
150
+ }
151
+
152
+ fn receive(ruby: &Ruby, this: Obj<Self>, stamp: Value) -> Result<Value, Error> {
153
+ this.check_frozen()?;
154
+ let stamp = values::stamp(ruby, stamp)?;
155
+ let outcome = this.core.borrow_mut().receive(&stamp);
156
+ Ok(answer::<Receipts>(ruby, outcome))
157
+ }
158
+
159
+ /// A `Deliver` or an `Obsolete` wrapping the stamp, or `nil`.
160
+ /// Clone-then-keep: the stamp leaves the hold table only once its answer
161
+ /// is built.
162
+ fn release(ruby: &Ruby, this: Obj<Self>) -> Result<Value, Error> {
163
+ keep(ruby, this, &this.core, Core::release, |released| {
164
+ let Some(released) = released else {
165
+ return Ok(ruby.qnil().as_value());
166
+ };
167
+ let classes = classes(ruby)?;
168
+ let (class, stamp) = match released {
169
+ Release::Deliver(stamp) => (classes.deliver, stamp),
170
+ Release::Obsolete(stamp) => (classes.obsolete, stamp),
171
+ };
172
+ let stamp = stamp_value(ruby, &stamp)?;
173
+ class.get(ruby).funcall("new", (stamp,))
174
+ })
175
+ }
176
+
177
+ fn forget(ruby: &Ruby, this: Obj<Self>, sender: Value, counter: Value) -> Result<Value, Error> {
178
+ this.check_frozen()?;
179
+ let (sender, counter) = (integer(sender, "sender")?, integer(counter, "counter")?);
180
+ let outcome = this.core.borrow_mut().forget(sender, counter);
181
+ Ok(answer::<Forgettings>(ruby, outcome))
182
+ }
183
+
184
+ fn missing(
185
+ ruby: &Ruby,
186
+ this: Obj<Self>,
187
+ stamp: Value,
188
+ cursor: Value,
189
+ limit: Value,
190
+ ) -> Result<Value, Error> {
191
+ let cursor: usize = integer(cursor, "cursor")?;
192
+ let limit = integer_in(limit, "limit", 0..=MEMBERS)?;
193
+ let stamp = values::stamp(ruby, stamp)?;
194
+ let mut gaps = [Gap::default(); MEMBERS];
195
+ let out = gaps.get_mut(..limit).unwrap_or(&mut []);
196
+ let outcome = this.core.borrow().missing(&stamp, cursor, out);
197
+ let page = match outcome {
198
+ Ok(page) => page,
199
+ Err(why) => return Ok(refusal(ruby, why)),
200
+ };
201
+ let listed = ruby.ary_new_capa(page.gaps());
202
+ for gap in gaps.iter().take(page.gaps()) {
203
+ listed.push(gap_value(ruby, gap)?)?;
204
+ }
205
+ let class = classes(ruby)?.page.get(ruby);
206
+ class.funcall("new", (listed, page.next()))
207
+ }
208
+
209
+ fn absorb(
210
+ ruby: &Ruby,
211
+ this: Obj<Self>,
212
+ generation: Value,
213
+ seen: Value,
214
+ ) -> Result<Value, Error> {
215
+ this.check_frozen()?;
216
+ let generation = integer(generation, "generation")?;
217
+ let seen = clock(ruby, seen)?;
218
+ let outcome = this.core.borrow_mut().absorb(generation, &seen);
219
+ Ok(answer::<Absorbings>(ruby, outcome))
220
+ }
221
+
222
+ fn clock(ruby: &Ruby, this: Obj<Self>) -> Result<Value, Error> {
223
+ let delivered = *this.core.borrow().clock();
224
+ clock_value(ruby, &delivered)
225
+ }
226
+
227
+ fn held(&self) -> usize {
228
+ self.core.borrow().held()
229
+ }
230
+
231
+ fn membership(ruby: &Ruby, this: Obj<Self>) -> Result<Value, Error> {
232
+ let membership = *this.core.borrow().membership();
233
+ members_value(ruby, &membership)
234
+ }
235
+
236
+ fn local(&self) -> u64 {
237
+ self.core.borrow().local()
238
+ }
239
+
240
+ fn generation(&self) -> u64 {
241
+ self.core.borrow().generation()
242
+ }
243
+
244
+ const fn capacity() -> usize {
245
+ HOLD
246
+ }
247
+ }
@@ -0,0 +1,108 @@
1
+ //! Validating hooks for the `Stamp`, `Gap`, `Page`, `Deliver` and `Obsolete`
2
+ //! values, and the conversions the tracker uses.
3
+ use causal_machines::{Gap, Page, Stamp};
4
+ use magnus::{Error, RArray, Ruby, Value, prelude::*};
5
+ use matryona_machines::ruby::{exact_array, exact_fields, integer, optional};
6
+
7
+ use crate::classes::classes;
8
+ use crate::vectors::{clock, clock_value, entry};
9
+ use crate::{MEMBERS, range_error};
10
+
11
+ /// A `CausalMachines::Stamp` of `stamp`, built through `new`.
12
+ pub fn stamp_value(ruby: &Ruby, stamp: &Stamp<MEMBERS>) -> Result<Value, Error> {
13
+ let clock = clock_value(ruby, stamp.clock())?;
14
+ let class = classes(ruby)?.stamp.get(ruby);
15
+ class.funcall("new", (stamp.generation(), stamp.sender(), clock))
16
+ }
17
+
18
+ /// A `CausalMachines::Gap` of `gap`, built through `new`.
19
+ pub fn gap_value(ruby: &Ruby, gap: &Gap) -> Result<Value, Error> {
20
+ let class = classes(ruby)?.gap.get(ruby);
21
+ class.funcall("new", (gap.replica(), gap.from(), gap.through()))
22
+ }
23
+
24
+ /// What `Stamp.new` stores: `Stamp::new` takes any generation, sender and
25
+ /// vector, so only types and ranges are checked.
26
+ pub fn checked_stamp(
27
+ ruby: &Ruby,
28
+ generation: Value,
29
+ sender: Value,
30
+ clock: Value,
31
+ ) -> Result<(u64, u64, Value), Error> {
32
+ let (generation, sender) = (
33
+ integer(generation, "generation")?,
34
+ integer(sender, "sender")?,
35
+ );
36
+ self::clock(ruby, clock)?;
37
+ Ok((generation, sender, clock))
38
+ }
39
+
40
+ /// The core stamp of a `CausalMachines::Stamp`.
41
+ pub fn stamp(ruby: &Ruby, value: Value) -> Result<Stamp<MEMBERS>, Error> {
42
+ let message = "expected a CausalMachines::Stamp";
43
+ let [generation, sender, seen] =
44
+ exact_fields(ruby, value, classes(ruby)?.stamp.get(ruby), message)?;
45
+ let generation = integer(generation, "generation")?;
46
+ let sender = integer(sender, "sender")?;
47
+ let seen = clock(ruby, seen)?;
48
+ Ok(Stamp::new(generation, sender, seen))
49
+ }
50
+
51
+ /// What `Deliver.new` and `Obsolete.new` store: a `CausalMachines::Stamp`.
52
+ pub fn checked_release(ruby: &Ruby, held: Value) -> Result<Value, Error> {
53
+ stamp(ruby, held)?;
54
+ Ok(held)
55
+ }
56
+
57
+ /// The core gap of a `CausalMachines::Gap`, rebuilt through `Gap::new`.
58
+ fn gap(ruby: &Ruby, value: Value) -> Result<Gap, Error> {
59
+ let message = "expected a CausalMachines::Gap";
60
+ let [replica, from, through] =
61
+ exact_fields(ruby, value, classes(ruby)?.gap.get(ruby), message)?;
62
+ checked_gap(ruby, replica, from, through)
63
+ }
64
+
65
+ fn checked_gap(ruby: &Ruby, replica: Value, from: Value, through: Value) -> Result<Gap, Error> {
66
+ let replica = integer(replica, "replica")?;
67
+ let (from, through) = (integer(from, "from")?, integer(through, "through")?);
68
+ Gap::new(replica, from, through).ok_or_else(|| {
69
+ range_error(
70
+ ruby,
71
+ "a gap runs from a counter of at least 1 through one no smaller",
72
+ )
73
+ })
74
+ }
75
+
76
+ /// What `Gap.new` stores: the parts `Gap::new` accepts.
77
+ pub fn checked_gap_fields(
78
+ ruby: &Ruby,
79
+ replica: Value,
80
+ from: Value,
81
+ through: Value,
82
+ ) -> Result<(u64, u64, u64), Error> {
83
+ let gap = checked_gap(ruby, replica, from, through)?;
84
+ Ok((gap.replica(), gap.from(), gap.through()))
85
+ }
86
+
87
+ /// What `Page.new` stores: the gaps (each a `CausalMachines::Gap`, frozen
88
+ /// into a copy) and the cursor of a page `Page::new` accepts.
89
+ pub fn checked_page(ruby: &Ruby, gaps: Value, next: Value) -> Result<(RArray, Option<u64>), Error> {
90
+ let next: Option<u64> = optional(next, "next")?;
91
+ let gaps = exact_array(ruby, gaps, "expected an Array of CausalMachines::Gap")?;
92
+ let held = ruby.ary_new_capa(gaps.len());
93
+ for index in 0..gaps.len() {
94
+ let each = entry(gaps, index)?;
95
+ gap(ruby, each)?;
96
+ held.push(each)?;
97
+ }
98
+ let cursor = next.map(|cursor| usize::try_from(cursor).unwrap_or(usize::MAX));
99
+ Page::new::<MEMBERS>(held.len(), cursor).ok_or_else(|| {
100
+ range_error(
101
+ ruby,
102
+ "no listing answers this page: one gap per slot before the cursor, \
103
+ and the cursor names a membership slot",
104
+ )
105
+ })?;
106
+ held.freeze();
107
+ Ok((held, next))
108
+ }