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,152 @@
1
+ //! The `VersionVector` and `Membership` values: their validating hooks, the
2
+ //! conversions to and from the core types, and their methods.
3
+ use causal_machines::{Causality, Membership, VersionVector};
4
+ use magnus::{Error, RArray, Ruby, Value, prelude::*};
5
+ use matryona_machines::ruby::{Symbols, exact_array, exact_fields, integer};
6
+
7
+ use crate::classes::classes;
8
+ use crate::{MEMBERS, range_error, refusal};
9
+
10
+ pub type Clock = VersionVector<MEMBERS>;
11
+ pub type Members = Membership<MEMBERS>;
12
+
13
+ /// The Integers of a Ruby Array of at most [`MEMBERS`] entries, `name`
14
+ /// naming each in a conversion error.
15
+ fn numbers(ruby: &Ruby, value: Value, name: &str) -> Result<([u64; MEMBERS], usize), Error> {
16
+ let array = exact_array(ruby, value, "expected an Array of Integers")?;
17
+ let len = array.len();
18
+ if len > MEMBERS {
19
+ return Err(range_error(ruby, format!("at most {MEMBERS} entries fit")));
20
+ }
21
+ let mut out = [0; MEMBERS];
22
+ for (index, slot) in out.iter_mut().enumerate().take(len) {
23
+ *slot = integer(entry(array, index)?, name)?;
24
+ }
25
+ Ok((out, len))
26
+ }
27
+
28
+ /// Entry `index` of `array`; past `isize::MAX` reads as past the end.
29
+ pub fn entry(array: RArray, index: usize) -> Result<Value, Error> {
30
+ array.entry(isize::try_from(index).unwrap_or(isize::MAX))
31
+ }
32
+
33
+ /// A frozen Ruby Array of `values`.
34
+ fn frozen(ruby: &Ruby, values: &[u64]) -> Result<RArray, Error> {
35
+ let out = ruby.ary_new_capa(values.len());
36
+ for value in values {
37
+ out.push(*value)?;
38
+ }
39
+ out.freeze();
40
+ Ok(out)
41
+ }
42
+
43
+ /// What `VersionVector.new` stores: every one of the core's `MEMBERS`
44
+ /// counters, the ones not given as zero (`from_counters`).
45
+ pub fn checked_counters(ruby: &Ruby, counters: Value) -> Result<RArray, Error> {
46
+ let (counters, _) = numbers(ruby, counters, "counter")?;
47
+ frozen(ruby, Clock::from_counters(counters).counters())
48
+ }
49
+
50
+ /// The core vector of a `CausalMachines::VersionVector`.
51
+ pub fn clock(ruby: &Ruby, value: Value) -> Result<Clock, Error> {
52
+ let message = "expected a CausalMachines::VersionVector";
53
+ let [counters] = exact_fields(ruby, value, classes(ruby)?.vector.get(ruby), message)?;
54
+ let (counters, _) = numbers(ruby, counters, "counter")?;
55
+ Ok(Clock::from_counters(counters))
56
+ }
57
+
58
+ /// A `CausalMachines::VersionVector` of `clock`, built through `new`.
59
+ pub fn clock_value(ruby: &Ruby, clock: &Clock) -> Result<Value, Error> {
60
+ let class = classes(ruby)?.vector.get(ruby);
61
+ class.funcall("new", (frozen(ruby, clock.counters())?,))
62
+ }
63
+
64
+ pub fn get(ruby: &Ruby, this: Value, slot: Value) -> Result<Option<u64>, Error> {
65
+ let slot = integer(slot, "slot")?;
66
+ Ok(clock(ruby, this)?.get(slot))
67
+ }
68
+
69
+ /// The incremented vector, or the refusal; `self` is a value and stays as is.
70
+ pub fn increment(ruby: &Ruby, this: Value, slot: Value) -> Result<Value, Error> {
71
+ let slot = integer(slot, "slot")?;
72
+ let mut vector = clock(ruby, this)?;
73
+ match vector.increment(slot) {
74
+ Ok(_) => clock_value(ruby, &vector),
75
+ Err(why) => Ok(refusal(ruby, why)),
76
+ }
77
+ }
78
+
79
+ matryona_machines::symbols! {
80
+ /// What `compare` answers.
81
+ Causalities for Causality as "a causality" {
82
+ Equal => "equal",
83
+ Before => "before",
84
+ After => "after",
85
+ Concurrent => "concurrent",
86
+ }
87
+ }
88
+
89
+ pub fn compare(ruby: &Ruby, this: Value, other: Value) -> Result<Value, Error> {
90
+ let causality = clock(ruby, this)?.compare(&clock(ruby, other)?);
91
+ Ok(Causalities::symbol(ruby, causality).as_value())
92
+ }
93
+
94
+ pub fn dominates(ruby: &Ruby, this: Value, other: Value) -> Result<bool, Error> {
95
+ Ok(clock(ruby, this)?.dominates(&clock(ruby, other)?))
96
+ }
97
+
98
+ pub fn concurrent(ruby: &Ruby, this: Value, other: Value) -> Result<bool, Error> {
99
+ Ok(clock(ruby, this)?.concurrent(&clock(ruby, other)?))
100
+ }
101
+
102
+ pub fn merged(ruby: &Ruby, this: Value, other: Value) -> Result<Value, Error> {
103
+ let merged = clock(ruby, this)?.merged(&clock(ruby, other)?);
104
+ clock_value(ruby, &merged)
105
+ }
106
+
107
+ fn distinct(ruby: &Ruby, ids: &[u64; MEMBERS], len: usize) -> Result<Members, Error> {
108
+ Membership::from_slice(ids.get(..len).unwrap_or(&[]))
109
+ .ok_or_else(|| range_error(ruby, "members must be distinct replica ids"))
110
+ }
111
+
112
+ /// What `Membership.new` stores: the ids `Membership::from_slice` accepts.
113
+ pub fn checked_ids(ruby: &Ruby, ids: Value) -> Result<RArray, Error> {
114
+ let (ids, len) = numbers(ruby, ids, "id")?;
115
+ frozen(ruby, distinct(ruby, &ids, len)?.ids())
116
+ }
117
+
118
+ /// The core membership of a `CausalMachines::Membership`.
119
+ pub fn members(ruby: &Ruby, value: Value) -> Result<Members, Error> {
120
+ let message = "expected a CausalMachines::Membership";
121
+ let [ids] = exact_fields(ruby, value, classes(ruby)?.membership.get(ruby), message)?;
122
+ let (ids, len) = numbers(ruby, ids, "id")?;
123
+ distinct(ruby, &ids, len)
124
+ }
125
+
126
+ /// A `CausalMachines::Membership` of `members`.
127
+ pub fn members_value(ruby: &Ruby, members: &Members) -> Result<Value, Error> {
128
+ let class = classes(ruby)?.membership.get(ruby);
129
+ class.funcall("new", (frozen(ruby, members.ids())?,))
130
+ }
131
+
132
+ pub fn slot(ruby: &Ruby, this: Value, replica: Value) -> Result<Option<usize>, Error> {
133
+ let replica = integer(replica, "replica")?;
134
+ Ok(members(ruby, this)?.slot(replica))
135
+ }
136
+
137
+ pub fn replica(ruby: &Ruby, this: Value, slot: Value) -> Result<Option<u64>, Error> {
138
+ let slot = integer(slot, "slot")?;
139
+ Ok(members(ruby, this)?.replica(slot))
140
+ }
141
+
142
+ pub fn len(ruby: &Ruby, this: Value) -> Result<usize, Error> {
143
+ Ok(members(ruby, this)?.len())
144
+ }
145
+
146
+ pub fn is_empty(ruby: &Ruby, this: Value) -> Result<bool, Error> {
147
+ Ok(members(ruby, this)?.is_empty())
148
+ }
149
+
150
+ pub fn admits(ruby: &Ruby, this: Value, vector: Value) -> Result<bool, Error> {
151
+ Ok(members(ruby, this)?.admits(&clock(ruby, vector)?))
152
+ }
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CausalMachines
4
+ VERSION = '0.6.1'
5
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'causal_machines/version'
4
+
5
+ # Every value below validates at construction through the core: a wrong type
6
+ # raises TypeError, a value the core would not build raises RangeError. A value
7
+ # built by hand is held to the same rule as one the gem returned.
8
+ module CausalMachines
9
+ # The core's `VersionVector<MEMBERS>`: one counter per membership slot.
10
+ # `VersionVector.new` is the core's `new()` (nothing seen) and
11
+ # `VersionVector.new(counters)` its `from_counters`: at most MEMBERS
12
+ # Integers in 0..2**64-1; slots not given count zero, so `counters` always
13
+ # holds MEMBERS entries. Methods (native): get, increment, compare,
14
+ # dominates?, concurrent?, merged.
15
+ VersionVector = Data.define(:counters) do
16
+ def initialize(counters: [])
17
+ super(counters: CausalMachines.__send__(:__counters, counters))
18
+ end
19
+ end
20
+
21
+ # The core's `Membership<MEMBERS>`: up to MEMBERS distinct replica ids,
22
+ # each bound to the slot of its position, as `Membership::from_slice`
23
+ # accepts them (duplicates or too many raise RangeError). Methods (native):
24
+ # slot, replica, len, empty?, admits?.
25
+ Membership = Data.define(:ids) do
26
+ def initialize(ids:)
27
+ super(ids: CausalMachines.__send__(:__ids, ids))
28
+ end
29
+ end
30
+
31
+ # Causal metadata one message travels with: the sender's VersionVector at
32
+ # send time. Like the core's `Stamp::new`, any generation and sender build
33
+ # one; the receiving tracker judges it.
34
+ Stamp = Data.define(:generation, :sender, :clock) do
35
+ def initialize(generation:, sender:, clock:)
36
+ generation, sender, clock = CausalMachines.__send__(:__stamp, generation, sender, clock)
37
+ super
38
+ end
39
+ end
40
+
41
+ # Causal#release: a held stamp whose dependencies arrived; it is now
42
+ # delivered, so apply its payload. The core's `Release::Deliver(stamp)`.
43
+ Deliver = Data.define(:stamp) do
44
+ def initialize(stamp:)
45
+ super(stamp: CausalMachines.__send__(:__release, stamp))
46
+ end
47
+ end
48
+
49
+ # Causal#release: a held stamp the delivered clock already covers; drop its
50
+ # payload. The core's `Release::Obsolete(stamp)`.
51
+ Obsolete = Data.define(:stamp) do
52
+ def initialize(stamp:)
53
+ super(stamp: CausalMachines.__send__(:__release, stamp))
54
+ end
55
+ end
56
+
57
+ # An inclusive run of undelivered counters from one replica, as `Gap::new`
58
+ # accepts it: 1 <= from <= through.
59
+ Gap = Data.define(:replica, :from, :through) do
60
+ def initialize(replica:, from:, through:)
61
+ replica, from, through = CausalMachines.__send__(:__gap, replica, from, through)
62
+ super
63
+ end
64
+ end
65
+
66
+ # One bounded page of a missing-dependency listing. `gaps` holds the entries
67
+ # the core writes to its output buffer (it reports their count as `written`),
68
+ # at most MEMBERS; `next` is the cursor for the next call, a slot below
69
+ # MEMBERS, or nil when the listing is done.
70
+ Page = Data.define(:gaps, :next) do
71
+ def initialize(gaps:, next:)
72
+ gaps, cursor = CausalMachines.__send__(:__page, gaps, binding.local_variable_get(:next))
73
+ super(gaps: gaps, next: cursor)
74
+ end
75
+ end
76
+ end
77
+
78
+ # Native is required: no algorithm fallback. It validates and builds the Data
79
+ # values above, so they must exist first.
80
+ require 'causal_machines_native/causal_machines_native'
81
+
82
+ module CausalMachines
83
+ private_class_method :__counters, :__ids, :__stamp, :__release, :__gap, :__page
84
+
85
+ # The values are final. `initialize` is where each validates, and a subclass
86
+ # could override it, or `allocate` build an instance that never ran it:
87
+ # subclassing raises TypeError (as subclassing Class does) and `allocate`
88
+ # is gone. `new`, keywords, `with` and `dup` all still run the check.
89
+ [VersionVector, Membership, Stamp, Deliver, Obsolete, Gap, Page].each do |value|
90
+ value.singleton_class.undef_method(:allocate)
91
+ value.define_singleton_method(:inherited) { |_| raise TypeError, "#{value} cannot be subclassed" }
92
+ end
93
+ end
@@ -0,0 +1,148 @@
1
+ module CausalMachines
2
+ VERSION: String
3
+ MEMBERS: Integer
4
+ CAPACITY: Integer
5
+
6
+ # Why a stamp is not acceptable here at all. A refused call changed nothing.
7
+ # Every refusal is the snake_case of one core `Refusal` variant; there is no
8
+ # catch-all symbol.
9
+ type unfit = :stale_generation | :future_generation | :unknown_member | :malformed
10
+
11
+ # Every value validates at construction through the core: TypeError for a
12
+ # wrong type, RangeError for a value the core would not build. They are
13
+ # final: subclassing one raises TypeError, and `allocate` is undefined.
14
+
15
+ # The core's `VersionVector<MEMBERS>`. `new` with no counters is the core's
16
+ # `new()`; with counters, its `from_counters` (at most MEMBERS, the rest
17
+ # zero, so `counters` always holds MEMBERS entries).
18
+ class VersionVector < Data
19
+ attr_reader counters: Array[Integer]
20
+ def self.new: (?Array[Integer] counters) -> VersionVector
21
+ | (?counters: Array[Integer]) -> VersionVector
22
+
23
+ # The counter at `slot`, or nil past the last slot.
24
+ def get: (Integer slot) -> Integer?
25
+ # Honoured: a new vector counting one more event at `slot` (self is
26
+ # unchanged; the new counter is its `get(slot)`). Refusals:
27
+ # :unknown_member past the last slot, :exhausted at 2**64 - 1.
28
+ def increment: (Integer slot) -> (VersionVector | :unknown_member | :exhausted)
29
+ def compare: (VersionVector other) -> (:equal | :before | :after | :concurrent)
30
+ def dominates?: (VersionVector other) -> bool
31
+ def concurrent?: (VersionVector other) -> bool
32
+ # The core's `merged`: the pointwise maximum.
33
+ def merged: (VersionVector other) -> VersionVector
34
+ end
35
+
36
+ # The core's `Membership<MEMBERS>`: distinct replica ids, as
37
+ # `Membership::from_slice` accepts them.
38
+ class Membership < Data
39
+ attr_reader ids: Array[Integer]
40
+ def self.new: (Array[Integer] ids) -> Membership
41
+ | (ids: Array[Integer]) -> Membership
42
+
43
+ def slot: (Integer replica) -> Integer?
44
+ def replica: (Integer slot) -> Integer?
45
+ def len: () -> Integer
46
+ def empty?: () -> bool
47
+ # Whether the vector counts nothing outside these slots.
48
+ def admits?: (VersionVector clock) -> bool
49
+ end
50
+
51
+ class Stamp < Data
52
+ attr_reader generation: Integer
53
+ attr_reader sender: Integer
54
+ attr_reader clock: VersionVector
55
+ def self.new: (Integer generation, Integer sender, VersionVector clock) -> Stamp
56
+ | (generation: Integer, sender: Integer, clock: VersionVector) -> Stamp
57
+ end
58
+
59
+ # The core's `Release::Deliver(stamp)`: now delivered, apply its payload.
60
+ class Deliver < Data
61
+ attr_reader stamp: Stamp
62
+ def self.new: (Stamp stamp) -> Deliver
63
+ | (stamp: Stamp) -> Deliver
64
+ end
65
+
66
+ # The core's `Release::Obsolete(stamp)`: already covered, drop its payload.
67
+ class Obsolete < Data
68
+ attr_reader stamp: Stamp
69
+ def self.new: (Stamp stamp) -> Obsolete
70
+ | (stamp: Stamp) -> Obsolete
71
+ end
72
+
73
+ # As `Gap::new` accepts it: 1 <= from <= through.
74
+ class Gap < Data
75
+ attr_reader replica: Integer
76
+ attr_reader from: Integer
77
+ attr_reader through: Integer
78
+ def self.new: (Integer replica, Integer from, Integer through) -> Gap
79
+ | (replica: Integer, from: Integer, through: Integer) -> Gap
80
+ end
81
+
82
+ # At most MEMBERS gaps; `next` is a slot below MEMBERS, or nil.
83
+ class Page < Data
84
+ attr_reader gaps: Array[Gap]
85
+ attr_reader next: Integer?
86
+ def self.new: (Array[Gap] gaps, Integer? next) -> Page
87
+ | (gaps: Array[Gap], next: Integer?) -> Page
88
+ end
89
+
90
+ class Causal
91
+ # RangeError when `local` is not a member (restore: or `delivered` counts
92
+ # a slot outside the membership).
93
+ def self.new: (Membership members, Integer local, Integer generation) -> Causal
94
+ def self.restore: (Membership members, Integer local, Integer generation,
95
+ VersionVector delivered) -> Causal
96
+
97
+ # Honoured: a Stamp. Refusal: :exhausted.
98
+ def stamp: () -> (Stamp | :exhausted)
99
+
100
+ # Answers: :deliverable, :duplicate, :missing. Refusals: the unfit symbols,
101
+ # and :conflict when a different stamp with the same sender and counter
102
+ # is held, whichever of the three the stamp would otherwise be.
103
+ def check: (Stamp stamp) -> (:deliverable | :duplicate | :missing | :conflict | unfit)
104
+
105
+ # Honoured: :delivered, :held, and the repeats :already_held and :duplicate.
106
+ # Refusals: the unfit symbols, :conflict as for check (a held stamp is
107
+ # never dropped or replaced for a different one), and :full when the
108
+ # stamp must wait and no hold slot is free.
109
+ def receive: (Stamp stamp) -> (:delivered | :held | :already_held | :duplicate | :conflict | :full | unfit)
110
+
111
+ # nil when nothing is ready. Never refuses.
112
+ def release: () -> (Deliver | Obsolete | nil)
113
+
114
+ # Honoured: :forgotten when a held stamp was dropped, and the repeat
115
+ # :not_held when none was held. Refusal: :unknown_member. The only call
116
+ # that discards a held stamp without handing it back.
117
+ def forget: (Integer sender, Integer counter) -> (:forgotten | :not_held | :unknown_member)
118
+
119
+ # Honoured: a Page. Refusals: the unfit symbols, :conflict as for check,
120
+ # then :unknown_member when `cursor` is past the last member slot (a
121
+ # cursor the tracker never handed out). RangeError for a limit above
122
+ # MEMBERS.
123
+ def missing: (Stamp stamp, Integer cursor, Integer limit) -> (Page | :conflict | unfit)
124
+
125
+ # Honoured: :absorbed when the delivered clock advanced, and the repeat
126
+ # :already_covered when it already covered `clock` (nothing changed).
127
+ # Refusals: :stale_generation, :future_generation, and :malformed when
128
+ # `clock` counts a slot outside the membership.
129
+ def absorb: (Integer generation, VersionVector clock)
130
+ -> (:absorbed | :already_covered | :stale_generation | :future_generation | :malformed)
131
+
132
+ def clock: () -> VersionVector
133
+ def held: () -> Integer
134
+ def membership: () -> Membership
135
+ def local: () -> Integer
136
+ def generation: () -> Integer
137
+ def capacity: () -> Integer
138
+ end
139
+
140
+ # Private native hooks each Data value's `initialize` validates through.
141
+ # The Arrays answered are frozen copies.
142
+ private def self.__counters: (Array[Integer] counters) -> Array[Integer]
143
+ private def self.__ids: (Array[Integer] ids) -> Array[Integer]
144
+ private def self.__stamp: (Integer generation, Integer sender, VersionVector clock) -> [Integer, Integer, VersionVector]
145
+ private def self.__release: (Stamp stamp) -> Stamp
146
+ private def self.__gap: (Integer replica, Integer from, Integer through) -> [Integer, Integer, Integer]
147
+ private def self.__page: (Array[Gap] gaps, Integer? next) -> [Array[Gap], Integer?]
148
+ end
metadata ADDED
@@ -0,0 +1,89 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: causal_machines
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.6.1
5
+ platform: ruby
6
+ authors:
7
+ - Abdelkader Boudih
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rb_sys
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.9'
19
+ - - ">="
20
+ - !ruby/object:Gem::Version
21
+ version: 0.9.130
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - "~>"
27
+ - !ruby/object:Gem::Version
28
+ version: '0.9'
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 0.9.130
32
+ description: 'Causal-order policy core: parks early stamps until their dependencies
33
+ land; holds no payloads and owns no transport or execution.'
34
+ email:
35
+ - oss@seuros.com
36
+ executables: []
37
+ extensions:
38
+ - ext/causal_machines_native/extconf.rb
39
+ extra_rdoc_files: []
40
+ files:
41
+ - CHANGELOG.md
42
+ - Cargo.lock
43
+ - Cargo.toml
44
+ - LICENSE.txt
45
+ - README.md
46
+ - ext/causal_machines_native/core/CHANGELOG.md
47
+ - ext/causal_machines_native/core/Cargo.toml
48
+ - ext/causal_machines_native/core/README.md
49
+ - ext/causal_machines_native/core/src/lib.rs
50
+ - ext/causal_machines_native/core/src/tracker.rs
51
+ - ext/causal_machines_native/core/src/vector.rs
52
+ - ext/causal_machines_native/extconf.rb
53
+ - ext/causal_machines_native/ffi/Cargo.toml
54
+ - ext/causal_machines_native/ffi/extconf.rb
55
+ - ext/causal_machines_native/ffi/src/classes.rs
56
+ - ext/causal_machines_native/ffi/src/init.rs
57
+ - ext/causal_machines_native/ffi/src/lib.rs
58
+ - ext/causal_machines_native/ffi/src/values.rs
59
+ - ext/causal_machines_native/ffi/src/vectors.rs
60
+ - lib/causal_machines.rb
61
+ - lib/causal_machines/version.rb
62
+ - sig/causal_machines.rbs
63
+ homepage: https://github.com/seuros/causal_machines
64
+ licenses:
65
+ - MIT
66
+ metadata:
67
+ source_code_uri: https://github.com/seuros/causal_machines
68
+ rubygems_mfa_required: 'true'
69
+ cargo_crate_name: causal_machines_native
70
+ cargo_manifest_path: ext/causal_machines_native/ffi/Cargo.toml
71
+ rdoc_options: []
72
+ require_paths:
73
+ - lib
74
+ required_ruby_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: 4.0.0
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: '0'
84
+ requirements: []
85
+ rubygems_version: 4.0.20
86
+ specification_version: 4
87
+ summary: Fixed-membership version vectors and causal-delivery readiness with a native
88
+ Rust core
89
+ test_files: []