election_machines 0.1.5 → 0.5.2
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 +4 -4
- data/CHANGELOG.md +65 -0
- data/Cargo.lock +323 -0
- data/Cargo.toml +2 -1
- data/README.md +110 -52
- data/ext/election_machines_native/core/CHANGELOG.md +40 -0
- data/ext/election_machines_native/core/Cargo.toml +4 -2
- data/ext/election_machines_native/core/README.md +95 -4
- data/ext/election_machines_native/core/src/lib.rs +172 -46
- data/ext/election_machines_native/core/src/refusal.rs +50 -0
- data/ext/election_machines_native/ffi/Cargo.toml +2 -2
- data/ext/election_machines_native/ffi/src/classes.rs +34 -0
- data/ext/election_machines_native/ffi/src/election.rs +152 -0
- data/ext/election_machines_native/ffi/src/init.rs +46 -11
- data/ext/election_machines_native/ffi/src/lib.rs +4 -152
- data/ext/election_machines_native/ffi/src/names.rs +54 -0
- data/ext/election_machines_native/ffi/src/values.rs +19 -49
- data/lib/election_machines/version.rb +1 -1
- data/lib/election_machines.rb +168 -0
- data/sig/election_machines.rbs +160 -7
- metadata +6 -1
|
@@ -1,154 +1,6 @@
|
|
|
1
|
-
//! Thin
|
|
1
|
+
//! Thin binding to lease-backed nomination; no storage, clocks or I/O.
|
|
2
|
+
mod classes;
|
|
3
|
+
mod election;
|
|
2
4
|
mod init;
|
|
5
|
+
mod names;
|
|
3
6
|
mod values;
|
|
4
|
-
use election_machines::{Election, Leadership};
|
|
5
|
-
use lease_machines::{Checkpoint, Decision, FencingToken, Lease, OwnerId};
|
|
6
|
-
use magnus::{Error, RArray, Ruby, prelude::*, typed_data::Obj};
|
|
7
|
-
use std::{cell::RefCell, sync::Arc};
|
|
8
|
-
use values::{Id, Seconds};
|
|
9
|
-
|
|
10
|
-
type Outcome = (String, Option<u64>, Option<u64>, Option<f64>);
|
|
11
|
-
|
|
12
|
-
#[magnus::wrap(class = "ElectionMachines::Checkpoint", free_immediately, size)]
|
|
13
|
-
struct Saved {
|
|
14
|
-
owner: Arc<()>,
|
|
15
|
-
revision: u64,
|
|
16
|
-
checkpoint: Checkpoint,
|
|
17
|
-
}
|
|
18
|
-
#[magnus::wrap(class = "ElectionMachines::Election", free_immediately, size)]
|
|
19
|
-
struct Wrapper {
|
|
20
|
-
owner: Arc<()>,
|
|
21
|
-
state: RefCell<(Election, u64)>,
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
fn lease_outcome(status: &str, lease: Lease) -> Outcome {
|
|
25
|
-
(
|
|
26
|
-
status.into(),
|
|
27
|
-
Some(lease.owner().value()),
|
|
28
|
-
Some(lease.token().value()),
|
|
29
|
-
Some(lease.expires_at().as_secs_f64()),
|
|
30
|
-
)
|
|
31
|
-
}
|
|
32
|
-
fn decision(result: Decision) -> Outcome {
|
|
33
|
-
match result {
|
|
34
|
-
Decision::Granted(lease) => lease_outcome("granted", lease),
|
|
35
|
-
Decision::Renewed(lease) => lease_outcome("renewed", lease),
|
|
36
|
-
Decision::Released => ("released".into(), None, None, None),
|
|
37
|
-
Decision::Rejected(reason) => (format!("{reason:?}"), None, None, None),
|
|
38
|
-
_ => ("unknown".into(), None, None, None),
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
impl Wrapper {
|
|
42
|
-
fn new() -> Self {
|
|
43
|
-
Self {
|
|
44
|
-
owner: Arc::new(()),
|
|
45
|
-
state: RefCell::new((Election::default(), 0)),
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
fn next_revision(&self, ruby: &Ruby) -> Result<u64, Error> {
|
|
49
|
-
let revision = self.state.borrow().1.checked_add(1);
|
|
50
|
-
revision.ok_or_else(|| Error::new(ruby.exception_range_error(), "revision exhausted"))
|
|
51
|
-
}
|
|
52
|
-
/// Runs `step` against the election under the next revision, which stales
|
|
53
|
-
/// every checkpoint taken before it.
|
|
54
|
-
fn advance<T>(&self, ruby: &Ruby, step: impl FnOnce(&mut Election) -> T) -> Result<T, Error> {
|
|
55
|
-
let revision = self.next_revision(ruby)?;
|
|
56
|
-
let mut state = self.state.borrow_mut();
|
|
57
|
-
state.1 = revision;
|
|
58
|
-
Ok(step(&mut state.0))
|
|
59
|
-
}
|
|
60
|
-
fn elect(
|
|
61
|
-
ruby: &Ruby,
|
|
62
|
-
rb_self: Obj<Self>,
|
|
63
|
-
candidates: RArray,
|
|
64
|
-
now: Seconds,
|
|
65
|
-
ttl: Seconds,
|
|
66
|
-
) -> Result<Outcome, Error> {
|
|
67
|
-
rb_self.check_frozen()?;
|
|
68
|
-
values::interval(ruby, now, ttl)?;
|
|
69
|
-
let count = candidates.len();
|
|
70
|
-
if count > 64 {
|
|
71
|
-
return Err(Error::new(
|
|
72
|
-
ruby.exception_arg_error(),
|
|
73
|
-
"at most 64 candidates",
|
|
74
|
-
));
|
|
75
|
-
}
|
|
76
|
-
let mut owners = [OwnerId::new(0); 64];
|
|
77
|
-
for (index, owner) in owners[..count].iter_mut().enumerate() {
|
|
78
|
-
*owner = OwnerId::new(candidates.entry::<Id>(index.cast_signed())?.0);
|
|
79
|
-
}
|
|
80
|
-
let result = rb_self.advance(ruby, |election| {
|
|
81
|
-
election.elect(&owners[..count], now.0, ttl.0)
|
|
82
|
-
})?;
|
|
83
|
-
Ok(match result {
|
|
84
|
-
Leadership::Elected(lease) => lease_outcome("elected", lease),
|
|
85
|
-
Leadership::Incumbent(lease) => lease_outcome("incumbent", lease),
|
|
86
|
-
Leadership::NoCandidates => ("no_candidates".into(), None, None, None),
|
|
87
|
-
Leadership::Rejected(reason) => (format!("{reason:?}"), None, None, None),
|
|
88
|
-
_ => ("unknown".into(), None, None, None),
|
|
89
|
-
})
|
|
90
|
-
}
|
|
91
|
-
fn heartbeat(
|
|
92
|
-
ruby: &Ruby,
|
|
93
|
-
rb_self: Obj<Self>,
|
|
94
|
-
owner: Id,
|
|
95
|
-
token: Id,
|
|
96
|
-
now: Seconds,
|
|
97
|
-
ttl: Seconds,
|
|
98
|
-
) -> Result<Outcome, Error> {
|
|
99
|
-
rb_self.check_frozen()?;
|
|
100
|
-
values::interval(ruby, now, ttl)?;
|
|
101
|
-
let token = values::token(ruby, token)?;
|
|
102
|
-
let result = rb_self.advance(ruby, |election| {
|
|
103
|
-
election.heartbeat(OwnerId::new(owner.0), token, now.0, ttl.0)
|
|
104
|
-
})?;
|
|
105
|
-
Ok(decision(result))
|
|
106
|
-
}
|
|
107
|
-
fn resign(
|
|
108
|
-
ruby: &Ruby,
|
|
109
|
-
rb_self: Obj<Self>,
|
|
110
|
-
owner: Id,
|
|
111
|
-
token: Id,
|
|
112
|
-
now: Seconds,
|
|
113
|
-
) -> Result<Outcome, Error> {
|
|
114
|
-
rb_self.check_frozen()?;
|
|
115
|
-
let token: FencingToken = values::token(ruby, token)?;
|
|
116
|
-
let result = rb_self.advance(ruby, |election| {
|
|
117
|
-
election.resign(OwnerId::new(owner.0), token, now.0)
|
|
118
|
-
})?;
|
|
119
|
-
Ok(decision(result))
|
|
120
|
-
}
|
|
121
|
-
fn checkpoint(&self) -> Saved {
|
|
122
|
-
let (checkpoint, revision) = {
|
|
123
|
-
let state = self.state.borrow();
|
|
124
|
-
(state.0.checkpoint(), state.1)
|
|
125
|
-
};
|
|
126
|
-
Saved {
|
|
127
|
-
owner: Arc::clone(&self.owner),
|
|
128
|
-
revision,
|
|
129
|
-
checkpoint,
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
fn restore(ruby: &Ruby, rb_self: Obj<Self>, saved: &Saved) -> Result<bool, Error> {
|
|
133
|
-
rb_self.check_frozen()?;
|
|
134
|
-
if !Arc::ptr_eq(&rb_self.owner, &saved.owner) || rb_self.state.borrow().1 != saved.revision
|
|
135
|
-
{
|
|
136
|
-
return Err(Error::new(
|
|
137
|
-
ruby.exception_arg_error(),
|
|
138
|
-
"cross-instance or stale checkpoint",
|
|
139
|
-
));
|
|
140
|
-
}
|
|
141
|
-
let revision = rb_self.next_revision(ruby)?;
|
|
142
|
-
*rb_self.state.borrow_mut() = (Election::restore(saved.checkpoint), revision);
|
|
143
|
-
Ok(true)
|
|
144
|
-
}
|
|
145
|
-
fn lease(&self) -> Option<(u64, u64, f64)> {
|
|
146
|
-
self.state.borrow().0.checkpoint().lease().map(|lease| {
|
|
147
|
-
(
|
|
148
|
-
lease.owner().value(),
|
|
149
|
-
lease.token().value(),
|
|
150
|
-
lease.expires_at().as_secs_f64(),
|
|
151
|
-
)
|
|
152
|
-
})
|
|
153
|
-
}
|
|
154
|
-
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
//! Symbol names for the core's enums. Every match is exhaustive: a new
|
|
2
|
+
//! variant fails to compile here until it has a name.
|
|
3
|
+
use election_machines::{ClockPolicy, LeaseRefusal, Refusal};
|
|
4
|
+
|
|
5
|
+
/// Exactly the refusals an election call can answer: its own, and the lease
|
|
6
|
+
/// refusals `elect`, `heartbeat` and `resign` can carry.
|
|
7
|
+
pub const REFUSALS: [&str; 9] = [
|
|
8
|
+
"no_candidates",
|
|
9
|
+
"no_lease",
|
|
10
|
+
"wrong_owner",
|
|
11
|
+
"stale_token",
|
|
12
|
+
"unknown",
|
|
13
|
+
"expired",
|
|
14
|
+
"clock_regressed",
|
|
15
|
+
"invalid_ttl",
|
|
16
|
+
"exhausted",
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
matryona_machines::symbols! {
|
|
20
|
+
/// The lease core's refusals as Symbols, the lease gem's own names.
|
|
21
|
+
pub LeaseRefusals for LeaseRefusal as "a lease refusal" {
|
|
22
|
+
Occupied => "occupied",
|
|
23
|
+
Held => "held",
|
|
24
|
+
NoLease => "no_lease",
|
|
25
|
+
WrongOwner => "wrong_owner",
|
|
26
|
+
StaleToken => "stale_token",
|
|
27
|
+
Unknown => "unknown",
|
|
28
|
+
Expired => "expired",
|
|
29
|
+
ClockRegressed => "clock_regressed",
|
|
30
|
+
InvalidTtl => "invalid_ttl",
|
|
31
|
+
Exhausted => "exhausted",
|
|
32
|
+
Fenced => "fenced",
|
|
33
|
+
OutOfPhase => "out_of_phase",
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
matryona_machines::symbols! {
|
|
38
|
+
/// The election's clock policies as Symbols: `TypeError` for a
|
|
39
|
+
/// non-Symbol, `RangeError` for another Symbol.
|
|
40
|
+
pub ClockPolicies for ClockPolicy as "clock policy" {
|
|
41
|
+
Reject => "reject",
|
|
42
|
+
Clamp => "clamp",
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
matryona_machines::symbols! {
|
|
47
|
+
/// The election's refusals as Symbols: a carried lease refusal answers
|
|
48
|
+
/// under the lease core's own name. Its `NAMES` lists every lease name;
|
|
49
|
+
/// `REFUSALS` keeps the ones an election call can answer.
|
|
50
|
+
pub Refusals for Refusal as "a refusal" => names_only {
|
|
51
|
+
NoCandidates => "no_candidates",
|
|
52
|
+
Lease(inner) => use LeaseRefusals,
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -1,51 +1,21 @@
|
|
|
1
|
-
//!
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
1
|
+
//! Values read from Ruby and built for it.
|
|
2
|
+
//!
|
|
3
|
+
//! Tokens, leases and checkpoints are read and built by
|
|
4
|
+
//! `matryona_machines::ruby::fencing` over [`Family`]: this gem's own class
|
|
5
|
+
//! read from the struct, a sibling gem's value of the same shape read by its
|
|
6
|
+
//! public readers, a subclass refused, each field converted and the value
|
|
7
|
+
//! rebuilt through the core constructor, so a forged value raises before it
|
|
8
|
+
//! reaches the core.
|
|
9
|
+
use election_machines::{Checkpoint, FencingToken, Lease, OwnerId};
|
|
10
|
+
|
|
11
|
+
use crate::classes::classes;
|
|
12
|
+
|
|
13
|
+
matryona_machines::fencing_family! {
|
|
14
|
+
/// The election core's lease family (lease-machines' types), for
|
|
15
|
+
/// `matryona_machines::ruby::fencing`.
|
|
16
|
+
pub Family in classes {
|
|
17
|
+
token: FencingToken,
|
|
18
|
+
lease: Lease, owner: OwnerId,
|
|
19
|
+
checkpoint: Checkpoint,
|
|
16
20
|
}
|
|
17
21
|
}
|
|
18
|
-
#[derive(Clone, Copy)]
|
|
19
|
-
pub struct Seconds(pub Duration);
|
|
20
|
-
impl TryConvert for Seconds {
|
|
21
|
-
fn try_convert(value: Value) -> Result<Self, Error> {
|
|
22
|
-
let ruby = Ruby::get_with(value);
|
|
23
|
-
if Integer::from_value(value).is_none() && Float::from_value(value).is_none() {
|
|
24
|
-
return Err(Error::new(
|
|
25
|
-
ruby.exception_type_error(),
|
|
26
|
-
"seconds must be Integer or Float",
|
|
27
|
-
));
|
|
28
|
-
}
|
|
29
|
-
Duration::try_from_secs_f64(f64::try_convert(value)?)
|
|
30
|
-
.map(Self)
|
|
31
|
-
.map_err(|_| {
|
|
32
|
-
Error::new(
|
|
33
|
-
ruby.exception_arg_error(),
|
|
34
|
-
"seconds must be finite, nonnegative and representable",
|
|
35
|
-
)
|
|
36
|
-
})
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
pub fn token(ruby: &Ruby, value: Id) -> Result<FencingToken, Error> {
|
|
40
|
-
FencingToken::new(value.0)
|
|
41
|
-
.ok_or_else(|| Error::new(ruby.exception_arg_error(), "token must be positive"))
|
|
42
|
-
}
|
|
43
|
-
pub fn interval(ruby: &Ruby, now: Seconds, ttl: Seconds) -> Result<(), Error> {
|
|
44
|
-
if ttl.0.is_zero() || now.0.checked_add(ttl.0).is_none() {
|
|
45
|
-
return Err(Error::new(
|
|
46
|
-
ruby.exception_arg_error(),
|
|
47
|
-
"TTL must be positive and expiration representable",
|
|
48
|
-
));
|
|
49
|
-
}
|
|
50
|
-
Ok(())
|
|
51
|
-
}
|
data/lib/election_machines.rb
CHANGED
|
@@ -1,3 +1,171 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
|
+
|
|
2
3
|
require_relative 'election_machines/version'
|
|
4
|
+
|
|
5
|
+
# Every value mirrors the core type of the same name, field for field, and
|
|
6
|
+
# every method takes the core's arguments in the core's order. Every instant
|
|
7
|
+
# and span (`now`, `ttl`, `expires_at`, `observed`) is Integer nanoseconds.
|
|
8
|
+
# Owners are Integers: the core's `OwnerId` is the caller's number.
|
|
9
|
+
#
|
|
10
|
+
# FencingToken, Lease and Checkpoint are the lease core's types, which the
|
|
11
|
+
# election core re-exports. Wherever a method takes one it reads it by its
|
|
12
|
+
# readers, so the `lease_machines` gem's values of the same names fit as they
|
|
13
|
+
# are; this gem does not depend on that one.
|
|
14
|
+
#
|
|
15
|
+
# The native side is the authority on every value it reads: one of this gem's
|
|
16
|
+
# classes must be exactly that class (a subclass is a TypeError, whatever it
|
|
17
|
+
# holds), and every field is validated again through the core constructor, so
|
|
18
|
+
# a value forged past `initialize` (`Marshal.load`, a bound
|
|
19
|
+
# `Data#initialize`) raises TypeError or RangeError and never reaches the core.
|
|
20
|
+
module ElectionMachines
|
|
21
|
+
|
|
22
|
+
# A fencing token: the issuing election's scope in the top 16 bits of `raw`
|
|
23
|
+
# above a sequence number counted from 1. Plain data, so it survives a trip
|
|
24
|
+
# over the wire as `raw` and comes back with `from_raw`. A token built here
|
|
25
|
+
# proves nothing by itself: the election still answers :unknown to one it
|
|
26
|
+
# never issued.
|
|
27
|
+
#
|
|
28
|
+
# Tokens of one scope are ordered; tokens of two scopes are not, so there is
|
|
29
|
+
# no `<` or `<=>`. Compare with `order` and `newer_than?`.
|
|
30
|
+
FencingToken = Data.define(:raw) do
|
|
31
|
+
# The core's `FencingToken::from_raw`. RangeError when the sequence number
|
|
32
|
+
# is zero, which no election issues.
|
|
33
|
+
def self.from_raw(raw) = new(raw)
|
|
34
|
+
|
|
35
|
+
def initialize(raw:)
|
|
36
|
+
ElectionMachines.__send__(:native_raw, raw)
|
|
37
|
+
super
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# The scope of the election that issued this token.
|
|
41
|
+
def scope = ElectionMachines.__send__(:native_token_scope, self)
|
|
42
|
+
|
|
43
|
+
# -1, 0 or 1 against a token of the same scope; nil across scopes.
|
|
44
|
+
def order(other) = ElectionMachines.__send__(:native_token_order, self, other)
|
|
45
|
+
|
|
46
|
+
# Whether this token is of `other`'s scope and strictly newer. False across
|
|
47
|
+
# scopes, so its negation does not mean "older or equal".
|
|
48
|
+
def newer_than?(other) = ElectionMachines.__send__(:native_token_newer, self, other)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# One leadership: who leads, under which token, until when. Built by hand
|
|
52
|
+
# it is held to the rule a granted one is: an Integer owner in 0..2**64-1,
|
|
53
|
+
# a token read by its `raw` reader and kept as this gem's FencingToken,
|
|
54
|
+
# Integer nanoseconds. TypeError for the wrong type, RangeError for a value
|
|
55
|
+
# outside that.
|
|
56
|
+
Lease = Data.define(:owner, :token, :expires_at) do
|
|
57
|
+
def initialize(owner:, token:, expires_at:)
|
|
58
|
+
super(owner:, token: ElectionMachines.__send__(:native_lease, owner, token, expires_at), expires_at:)
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Committed election state, the core's `Checkpoint`: persist the four fields
|
|
63
|
+
# before exposing a decision, rebuild with `from_parts`. RangeError when
|
|
64
|
+
# `issued` is beyond the scope's token space or `lease` is not the grant
|
|
65
|
+
# that history ends with (it must carry token number `issued` of `scope`).
|
|
66
|
+
#
|
|
67
|
+
# `lease` is read by its readers and kept as this gem's Lease.
|
|
68
|
+
Checkpoint = Data.define(:scope, :issued, :lease, :observed) do
|
|
69
|
+
# The core's `Checkpoint::from_parts`.
|
|
70
|
+
def self.from_parts(scope, issued, lease, observed) = new(scope, issued, lease, observed)
|
|
71
|
+
|
|
72
|
+
def initialize(scope:, issued:, lease:, observed:)
|
|
73
|
+
held = ElectionMachines.__send__(:native_checkpoint, scope, issued, lease, observed)
|
|
74
|
+
super(scope:, issued:, lease: held, observed:)
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# The core's `Leadership::Elected`: the smallest candidate now leads under
|
|
79
|
+
# `lease`, which carries a new token. `lease` is read by its readers and
|
|
80
|
+
# kept as this gem's Lease, validated like one.
|
|
81
|
+
Elected = Data.define(:lease) do
|
|
82
|
+
def initialize(lease:) = super(lease: ElectionMachines.__send__(:native_held, lease))
|
|
83
|
+
|
|
84
|
+
def incumbent? = false
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# The core's `Leadership::Incumbent`: a leader's unexpired `lease` is still
|
|
88
|
+
# in force. Honoured, and nothing changed. `lease` is read by its readers
|
|
89
|
+
# and kept as this gem's Lease, validated like one.
|
|
90
|
+
Incumbent = Data.define(:lease) do
|
|
91
|
+
def initialize(lease:) = super(lease: ElectionMachines.__send__(:native_held, lease))
|
|
92
|
+
|
|
93
|
+
def incumbent? = true
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# Sealed: no subclass can skip the checks above by overriding `initialize`,
|
|
97
|
+
# and no bare `allocate` builds a value that never ran them. Ruby still
|
|
98
|
+
# binds a subclass constant before `inherited` raises; the native side
|
|
99
|
+
# refuses its instances.
|
|
100
|
+
[FencingToken, Lease, Checkpoint, Elected, Incumbent].each do |value|
|
|
101
|
+
value.singleton_class.undef_method(:allocate)
|
|
102
|
+
value.define_singleton_method(:inherited) { |_| raise TypeError, "#{value} cannot be subclassed" }
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Native is required: no algorithm fallback. It resolves the classes above
|
|
107
|
+
# once, here.
|
|
3
108
|
require 'election_machines_native/election_machines_native'
|
|
109
|
+
|
|
110
|
+
module ElectionMachines
|
|
111
|
+
class << self
|
|
112
|
+
private :native_raw, :native_token_scope, :native_token_order, :native_token_newer, :native_lease,
|
|
113
|
+
:native_held, :native_checkpoint
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# A lease as the native side answers it, `[owner, raw, expires_at]`.
|
|
117
|
+
def self.lease_of(row) = Lease.new(row[0], FencingToken.new(row[1]), row[2])
|
|
118
|
+
private_class_method :lease_of
|
|
119
|
+
|
|
120
|
+
# The core's `Election`: one resource, one token scope. `elect` answers
|
|
121
|
+
# Elected or Incumbent when honoured, `heartbeat` and `resign` a Lease, and
|
|
122
|
+
# each a refusal Symbol otherwise. A refusal changes nothing.
|
|
123
|
+
class Election
|
|
124
|
+
class << self
|
|
125
|
+
# A fresh token namespace in scope zero.
|
|
126
|
+
def new = with_scope(0)
|
|
127
|
+
|
|
128
|
+
# A fresh token namespace whose tokens carry `scope`, an Integer in
|
|
129
|
+
# 0..65_535. Give each election its own.
|
|
130
|
+
def with_scope(scope) = native_with_scope(scope)
|
|
131
|
+
|
|
132
|
+
# The newest committed checkpoint of `scope`, with the clock policy
|
|
133
|
+
# stated again. RangeError when the checkpoint is of another scope.
|
|
134
|
+
def restored(scope, checkpoint, clock_policy)
|
|
135
|
+
native_restored(scope, checkpoint, clock_policy)
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
private :native_with_scope, :native_restored
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# :reject or :clamp. The core's builder consumes the election; here it
|
|
142
|
+
# changes this one and answers it.
|
|
143
|
+
def with_clock_policy(clock_policy)
|
|
144
|
+
native_with_clock_policy(clock_policy)
|
|
145
|
+
self
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# The last leadership granted (it may have expired), nil after a resignation.
|
|
149
|
+
def lease
|
|
150
|
+
held = native_lease
|
|
151
|
+
held && ElectionMachines.__send__(:lease_of, held)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def checkpoint
|
|
155
|
+
scope, issued, held, observed = native_checkpoint
|
|
156
|
+
Checkpoint.new(scope, issued, held && ElectionMachines.__send__(:lease_of, held), observed)
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# Every decision decides on a copy of the election, builds the answer
|
|
160
|
+
# (its `new` runs), then keeps the copy only if this election is still
|
|
161
|
+
# unfrozen (FrozenError) and unchanged (RuntimeError: a re-entrant call
|
|
162
|
+
# changed it). Either way, a raise means nothing was applied.
|
|
163
|
+
#
|
|
164
|
+
# `candidates` is an Array of owner Integers, of any length.
|
|
165
|
+
def elect(candidates, now, ttl) = native_elect(candidates, now, ttl)
|
|
166
|
+
|
|
167
|
+
def heartbeat(owner, token, now, ttl) = native_heartbeat(owner, token, now, ttl)
|
|
168
|
+
|
|
169
|
+
def resign(owner, token, now) = native_resign(owner, token, now)
|
|
170
|
+
end
|
|
171
|
+
end
|
data/sig/election_machines.rbs
CHANGED
|
@@ -1,15 +1,168 @@
|
|
|
1
1
|
module ElectionMachines
|
|
2
2
|
VERSION: String
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
REFUSALS: Array[Symbol]
|
|
4
|
+
CLOCK_POLICIES: Array[Symbol]
|
|
5
|
+
|
|
6
|
+
# Integer nanoseconds on one monotonic clock, for instants (now, expires_at,
|
|
7
|
+
# observed) and spans (ttl) alike:
|
|
8
|
+
# Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond). A non-Integer
|
|
9
|
+
# raises TypeError; a negative value, or one past 2**64 seconds, RangeError.
|
|
10
|
+
type nanoseconds = Integer
|
|
11
|
+
# An Integer in 0..65_535; TypeError for a non-Integer, RangeError outside.
|
|
12
|
+
type scope = Integer
|
|
13
|
+
# An Integer in 0..2**64-1, the caller's own number for a candidate.
|
|
14
|
+
type owner = Integer
|
|
15
|
+
type clock_policy = :reject | :clamp
|
|
16
|
+
# Every symbol that means "this call was not honoured and changed nothing",
|
|
17
|
+
# and exactly REFUSALS: no catch-all, and none an election cannot answer.
|
|
18
|
+
# :no_candidates is the core's `Refusal::NoCandidates`. The rest are the
|
|
19
|
+
# core's `Refusal::Lease(reason)`, answered as the lease core's own symbol
|
|
20
|
+
# for `reason`. The lease core's :occupied and :held never arrive (a live
|
|
21
|
+
# leader is the honoured Incumbent), nor do :fenced and :out_of_phase (the
|
|
22
|
+
# lease holder's). Each method below lists exactly the ones it can answer.
|
|
23
|
+
type refusal = :no_candidates | :no_lease | :wrong_owner | :stale_token | :unknown | :expired
|
|
24
|
+
| :clock_regressed | :invalid_ttl | :exhausted
|
|
25
|
+
# What heartbeat and resign can answer for the owner, token and clock.
|
|
26
|
+
# :unknown is a token this election never issued, which includes every token
|
|
27
|
+
# of another scope; :stale_token is one it issued that is no longer in force.
|
|
28
|
+
type held_refusal = :unknown | :clock_regressed | :no_lease | :wrong_owner | :stale_token | :expired
|
|
29
|
+
# The core's `Leadership`: both are honoured, Incumbent changed nothing.
|
|
30
|
+
type leadership = Elected | Incumbent
|
|
31
|
+
|
|
32
|
+
# Anything read as a fencing token: this gem's FencingToken, or the
|
|
33
|
+
# `lease_machines` gem's. A bare Integer is not one (TypeError).
|
|
34
|
+
interface _FencingToken
|
|
35
|
+
def raw: () -> Integer
|
|
5
36
|
end
|
|
37
|
+
|
|
38
|
+
# Anything read as a lease: this gem's Lease, or the `lease_machines` gem's.
|
|
39
|
+
interface _Lease
|
|
40
|
+
def owner: () -> owner
|
|
41
|
+
def token: () -> _FencingToken
|
|
42
|
+
def expires_at: () -> nanoseconds
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Anything read as a checkpoint: this gem's, or the `lease_machines` gem's.
|
|
46
|
+
interface _Checkpoint
|
|
47
|
+
def scope: () -> scope
|
|
48
|
+
def issued: () -> Integer
|
|
49
|
+
def lease: () -> _Lease?
|
|
50
|
+
def observed: () -> nanoseconds
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
class FencingToken < Data
|
|
54
|
+
# Scope in the top 16 bits above a sequence number counted from 1.
|
|
55
|
+
attr_reader raw: Integer
|
|
56
|
+
# TypeError for a non-Integer; RangeError outside 1..2**64-1 or when the
|
|
57
|
+
# sequence number is zero.
|
|
58
|
+
def self.new: (Integer raw) -> FencingToken
|
|
59
|
+
| (raw: Integer) -> FencingToken
|
|
60
|
+
def self.from_raw: (Integer raw) -> FencingToken
|
|
61
|
+
def scope: () -> scope
|
|
62
|
+
# nil across scopes: such tokens are not comparable.
|
|
63
|
+
def order: (_FencingToken other) -> (-1 | 0 | 1)?
|
|
64
|
+
# False across scopes.
|
|
65
|
+
def newer_than?: (_FencingToken other) -> bool
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
class Lease < Data
|
|
69
|
+
attr_reader owner: owner
|
|
70
|
+
attr_reader token: FencingToken
|
|
71
|
+
attr_reader expires_at: nanoseconds
|
|
72
|
+
# Validated like a granted one: TypeError for a non-Integer owner or
|
|
73
|
+
# instant or a token without `raw`, RangeError for an owner outside
|
|
74
|
+
# 0..2**64-1, a token `from_raw` rejects or an instant out of range.
|
|
75
|
+
# `token` is read by its readers and kept as this gem's FencingToken.
|
|
76
|
+
def self.new: (owner owner, _FencingToken token, nanoseconds expires_at) -> Lease
|
|
77
|
+
| (owner: owner, token: _FencingToken, expires_at: nanoseconds) -> Lease
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
class Checkpoint < Data
|
|
81
|
+
attr_reader scope: scope
|
|
82
|
+
# Tokens issued so far, resignations included; the next is `issued + 1`.
|
|
83
|
+
attr_reader issued: Integer
|
|
84
|
+
attr_reader lease: Lease?
|
|
85
|
+
attr_reader observed: nanoseconds
|
|
86
|
+
# RangeError when `issued` is past 2**48-1, or `lease` does not carry
|
|
87
|
+
# token number `issued` of `scope`. `lease` is read by its readers and
|
|
88
|
+
# kept as this gem's Lease.
|
|
89
|
+
def self.new: (scope scope, Integer issued, _Lease? lease, nanoseconds observed) -> Checkpoint
|
|
90
|
+
| (scope: scope, issued: Integer, lease: _Lease?, observed: nanoseconds) -> Checkpoint
|
|
91
|
+
def self.from_parts: (scope scope, Integer issued, _Lease? lease, nanoseconds observed) -> Checkpoint
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
class Elected < Data
|
|
95
|
+
attr_reader lease: Lease
|
|
96
|
+
# `lease` is read by its readers, validated like Lease.new and kept as
|
|
97
|
+
# this gem's Lease: TypeError without the readers, RangeError otherwise.
|
|
98
|
+
def self.new: (_Lease lease) -> Elected
|
|
99
|
+
| (lease: _Lease) -> Elected
|
|
100
|
+
def incumbent?: () -> false
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
class Incumbent < Data
|
|
104
|
+
attr_reader lease: Lease
|
|
105
|
+
# Read, validated and kept like Elected's.
|
|
106
|
+
def self.new: (_Lease lease) -> Incumbent
|
|
107
|
+
| (lease: _Lease) -> Incumbent
|
|
108
|
+
def incumbent?: () -> true
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# The core's `Election`. Honoured answers come first in every return type,
|
|
112
|
+
# then the refusals that method can answer. A refusal changes nothing, the
|
|
113
|
+
# observed clock included. Every mutating call raises FrozenError on a
|
|
114
|
+
# frozen election.
|
|
6
115
|
class Election
|
|
116
|
+
# A fresh token namespace in scope zero.
|
|
7
117
|
def self.new: () -> Election
|
|
8
|
-
|
|
9
|
-
def
|
|
10
|
-
|
|
118
|
+
# A fresh token namespace whose tokens carry `scope`.
|
|
119
|
+
def self.with_scope: (scope scope) -> Election
|
|
120
|
+
# RangeError when `checkpoint` is of another scope. TypeError unless
|
|
121
|
+
# `clock_policy` is a Symbol, RangeError unless :reject or :clamp.
|
|
122
|
+
def self.restored: (scope scope, _Checkpoint checkpoint, clock_policy clock_policy) -> Election
|
|
123
|
+
# Changes this election and answers it. TypeError for a non-Symbol,
|
|
124
|
+
# RangeError unless :reject or :clamp.
|
|
125
|
+
def with_clock_policy: (clock_policy clock_policy) -> self
|
|
126
|
+
def clock_policy: () -> clock_policy
|
|
127
|
+
def scope: () -> scope
|
|
128
|
+
def issued: () -> Integer
|
|
129
|
+
# The last leadership granted; it may have expired. nil after a resignation.
|
|
130
|
+
def lease: () -> Lease?
|
|
11
131
|
def checkpoint: () -> Checkpoint
|
|
12
|
-
|
|
13
|
-
|
|
132
|
+
# Elected: the smallest candidate, under a new token. Incumbent: a live
|
|
133
|
+
# leader stays, whoever the candidates were; nothing changed.
|
|
134
|
+
# :no_candidates for an empty Array, checked before the clock.
|
|
135
|
+
def elect: (Array[owner] candidates, nanoseconds now, nanoseconds ttl)
|
|
136
|
+
-> (leadership | :no_candidates | :clock_regressed | :invalid_ttl | :exhausted)
|
|
137
|
+
# The renewed Lease, under the same token. A repeat is honoured and never
|
|
138
|
+
# shortens the lease.
|
|
139
|
+
def heartbeat: (owner owner, _FencingToken token, nanoseconds now, nanoseconds ttl)
|
|
140
|
+
-> (Lease | held_refusal | :invalid_ttl)
|
|
141
|
+
# The Lease that was given up. A repeat is :no_lease.
|
|
142
|
+
def resign: (owner owner, _FencingToken token, nanoseconds now) -> (Lease | held_refusal)
|
|
143
|
+
|
|
144
|
+
private
|
|
145
|
+
|
|
146
|
+
type row = [Integer, Integer, Integer]
|
|
147
|
+
type saved = [Integer, Integer, row?, Integer]
|
|
148
|
+
private def self.native_with_scope: (Integer) -> Election
|
|
149
|
+
private def self.native_restored: (Integer, _Checkpoint, Symbol) -> Election
|
|
150
|
+
def native_with_clock_policy: (Symbol) -> nil
|
|
151
|
+
def native_lease: () -> row?
|
|
152
|
+
def native_checkpoint: () -> saved
|
|
153
|
+
def native_elect: (Array[Integer], Integer, Integer) -> (Elected | Incumbent | refusal)
|
|
154
|
+
def native_heartbeat: (Integer, _FencingToken, Integer, Integer) -> (Lease | refusal)
|
|
155
|
+
def native_resign: (Integer, _FencingToken, Integer) -> (Lease | refusal)
|
|
14
156
|
end
|
|
157
|
+
|
|
158
|
+
private
|
|
159
|
+
|
|
160
|
+
private def self.native_raw: (Integer) -> nil
|
|
161
|
+
private def self.native_token_scope: (_FencingToken) -> Integer
|
|
162
|
+
private def self.native_token_order: (_FencingToken, _FencingToken) -> (-1 | 0 | 1)?
|
|
163
|
+
private def self.native_token_newer: (_FencingToken, _FencingToken) -> bool
|
|
164
|
+
private def self.native_lease: (owner, _FencingToken, nanoseconds) -> FencingToken
|
|
165
|
+
private def self.native_held: (_Lease) -> Lease
|
|
166
|
+
private def self.native_checkpoint: (scope, Integer, _Lease?, nanoseconds) -> Lease?
|
|
167
|
+
private def self.lease_of: ([Integer, Integer, Integer]) -> Lease
|
|
15
168
|
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: election_machines
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.5.2
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Abdelkader Boudih
|
|
@@ -39,6 +39,7 @@ extensions:
|
|
|
39
39
|
extra_rdoc_files: []
|
|
40
40
|
files:
|
|
41
41
|
- CHANGELOG.md
|
|
42
|
+
- Cargo.lock
|
|
42
43
|
- Cargo.toml
|
|
43
44
|
- LICENSE.txt
|
|
44
45
|
- README.md
|
|
@@ -46,11 +47,15 @@ files:
|
|
|
46
47
|
- ext/election_machines_native/core/Cargo.toml
|
|
47
48
|
- ext/election_machines_native/core/README.md
|
|
48
49
|
- ext/election_machines_native/core/src/lib.rs
|
|
50
|
+
- ext/election_machines_native/core/src/refusal.rs
|
|
49
51
|
- ext/election_machines_native/extconf.rb
|
|
50
52
|
- ext/election_machines_native/ffi/Cargo.toml
|
|
51
53
|
- ext/election_machines_native/ffi/extconf.rb
|
|
54
|
+
- ext/election_machines_native/ffi/src/classes.rs
|
|
55
|
+
- ext/election_machines_native/ffi/src/election.rs
|
|
52
56
|
- ext/election_machines_native/ffi/src/init.rs
|
|
53
57
|
- ext/election_machines_native/ffi/src/lib.rs
|
|
58
|
+
- ext/election_machines_native/ffi/src/names.rs
|
|
54
59
|
- ext/election_machines_native/ffi/src/values.rs
|
|
55
60
|
- lib/election_machines.rb
|
|
56
61
|
- lib/election_machines/version.rb
|