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,86 +1,212 @@
|
|
|
1
1
|
#![no_std]
|
|
2
|
+
#![cfg_attr(not(test), deny(clippy::indexing_slicing))]
|
|
2
3
|
#![doc = include_str!("../README.md")]
|
|
4
|
+
|
|
5
|
+
mod refusal;
|
|
6
|
+
|
|
3
7
|
use core::time::Duration;
|
|
4
|
-
use lease_machines::{
|
|
5
|
-
Checkpoint, Decision, FencingToken, Lease, LeaseAuthority, OwnerId, Rejection,
|
|
6
|
-
};
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
use lease_machines::LeaseAuthority;
|
|
10
|
+
pub use lease_machines::Refusal as LeaseRefusal;
|
|
11
|
+
pub use lease_machines::{Checkpoint, ClockPolicy, FencingToken, Lease, OwnerId};
|
|
12
|
+
pub use refusal::Refusal;
|
|
13
|
+
|
|
14
|
+
/// Honoured outcome of [`Election::elect`]: who leads, and whether this call
|
|
15
|
+
/// made them leader.
|
|
9
16
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
10
|
-
#[non_exhaustive]
|
|
11
17
|
pub enum Leadership {
|
|
12
|
-
///
|
|
18
|
+
/// The smallest candidate was elected under a new, greater token.
|
|
13
19
|
Elected(Lease),
|
|
14
|
-
///
|
|
20
|
+
/// A leader's unexpired lease is still in force, whoever the candidates
|
|
21
|
+
/// were. Nothing changed, not even the observed clock.
|
|
15
22
|
Incumbent(Lease),
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
impl Leadership {
|
|
26
|
+
/// The leadership in force after the call.
|
|
27
|
+
#[must_use]
|
|
28
|
+
pub const fn lease(self) -> Lease {
|
|
29
|
+
match self {
|
|
30
|
+
Self::Elected(lease) | Self::Incumbent(lease) => lease,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/// Whether the call found a live leader and changed nothing.
|
|
35
|
+
#[must_use]
|
|
36
|
+
pub const fn is_incumbent(self) -> bool {
|
|
37
|
+
match self {
|
|
38
|
+
Self::Elected(_) => false,
|
|
39
|
+
Self::Incumbent(_) => true,
|
|
40
|
+
}
|
|
41
|
+
}
|
|
20
42
|
}
|
|
21
43
|
|
|
22
44
|
/// Deterministic nomination plus a single resource's lease authority.
|
|
23
|
-
|
|
45
|
+
///
|
|
46
|
+
/// The election issues no ids of its own: leadership tokens come from the
|
|
47
|
+
/// embedded authority's sequence, and carry its scope. Cloning an election
|
|
48
|
+
/// does not create a second one: two instances serving one scope issue the
|
|
49
|
+
/// same tokens.
|
|
50
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
24
51
|
pub struct Election {
|
|
25
52
|
authority: LeaseAuthority,
|
|
26
53
|
}
|
|
27
54
|
|
|
55
|
+
impl Default for Election {
|
|
56
|
+
fn default() -> Self {
|
|
57
|
+
Self::new()
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
28
61
|
impl Election {
|
|
29
|
-
///
|
|
62
|
+
/// Start a **fresh** token namespace in scope zero. Never use this to
|
|
63
|
+
/// recover an old one: it issues the same tokens again.
|
|
64
|
+
#[must_use]
|
|
65
|
+
pub const fn new() -> Self {
|
|
66
|
+
Self::with_scope(0)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// Start a **fresh** token namespace whose tokens carry `scope`.
|
|
70
|
+
///
|
|
71
|
+
/// Give every election whose tokens could meet its own scope; a token of
|
|
72
|
+
/// another scope is then [`LeaseRefusal::Unknown`]. Keeping scopes distinct
|
|
73
|
+
/// is the caller's job.
|
|
30
74
|
#[must_use]
|
|
31
|
-
pub const fn
|
|
75
|
+
pub const fn with_scope(scope: u16) -> Self {
|
|
32
76
|
Self {
|
|
33
|
-
authority: LeaseAuthority::
|
|
77
|
+
authority: LeaseAuthority::with_scope(scope),
|
|
34
78
|
}
|
|
35
79
|
}
|
|
36
80
|
|
|
37
|
-
///
|
|
81
|
+
/// Restore the newest committed checkpoint of `scope`, under the same
|
|
82
|
+
/// clock origin, with the clock policy stated again.
|
|
83
|
+
///
|
|
84
|
+
/// The scope is the caller's, never read out of the checkpoint: `None`
|
|
85
|
+
/// when the checkpoint is of another scope. The caller must prevent
|
|
86
|
+
/// simultaneous serving by the previous election.
|
|
38
87
|
#[must_use]
|
|
39
|
-
pub fn
|
|
40
|
-
|
|
41
|
-
|
|
88
|
+
pub const fn restored(scope: u16, checkpoint: Checkpoint, clock: ClockPolicy) -> Option<Self> {
|
|
89
|
+
match LeaseAuthority::restored(scope, checkpoint, clock) {
|
|
90
|
+
Some(authority) => Some(Self { authority }),
|
|
91
|
+
None => None,
|
|
42
92
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
self.authority.checkpoint().lease().map_or(
|
|
51
|
-
Leadership::Rejected(Rejection::NoLease),
|
|
52
|
-
Leadership::Incumbent,
|
|
53
|
-
)
|
|
54
|
-
}
|
|
55
|
-
Decision::Rejected(reason) => Leadership::Rejected(reason),
|
|
56
|
-
_ => Leadership::Rejected(Rejection::NoLease),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Choose how earlier-than-observed clocks are handled; `Reject` by default.
|
|
96
|
+
#[must_use]
|
|
97
|
+
pub const fn with_clock_policy(self, clock: ClockPolicy) -> Self {
|
|
98
|
+
Self {
|
|
99
|
+
authority: self.authority.with_clock_policy(clock),
|
|
57
100
|
}
|
|
58
101
|
}
|
|
59
102
|
|
|
60
|
-
///
|
|
103
|
+
/// Policy applied to regressing observations.
|
|
61
104
|
#[must_use]
|
|
62
|
-
pub fn
|
|
63
|
-
|
|
64
|
-
owner: OwnerId,
|
|
65
|
-
token: FencingToken,
|
|
66
|
-
now: Duration,
|
|
67
|
-
ttl: Duration,
|
|
68
|
-
) -> Decision {
|
|
69
|
-
self.authority.renew(owner, token, now, ttl)
|
|
105
|
+
pub const fn clock_policy(&self) -> ClockPolicy {
|
|
106
|
+
self.authority.clock_policy()
|
|
70
107
|
}
|
|
71
108
|
|
|
72
|
-
///
|
|
109
|
+
/// The scope carried by every token this election issues.
|
|
73
110
|
#[must_use]
|
|
74
|
-
pub fn
|
|
75
|
-
self.authority.
|
|
111
|
+
pub const fn scope(&self) -> u16 {
|
|
112
|
+
self.authority.scope()
|
|
76
113
|
}
|
|
77
114
|
|
|
78
|
-
///
|
|
115
|
+
/// How many tokens have been issued; also the sequence number of the last.
|
|
116
|
+
#[must_use]
|
|
117
|
+
pub const fn issued(&self) -> u64 {
|
|
118
|
+
self.authority.issued()
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// The last leadership granted; it may already be expired, and it is
|
|
122
|
+
/// `None` after a resignation.
|
|
123
|
+
#[must_use]
|
|
124
|
+
pub const fn lease(&self) -> Option<Lease> {
|
|
125
|
+
self.authority.checkpoint().lease()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/// Capture state for the runtime's durable commit. Persist it before
|
|
129
|
+
/// exposing the decision that produced it.
|
|
79
130
|
#[must_use]
|
|
80
131
|
pub const fn checkpoint(&self) -> Checkpoint {
|
|
81
132
|
self.authority.checkpoint()
|
|
82
133
|
}
|
|
134
|
+
|
|
135
|
+
/// Nominate the smallest candidate, respecting a live incumbent.
|
|
136
|
+
///
|
|
137
|
+
/// A leader whose lease has not expired stays leader even when it is not
|
|
138
|
+
/// among `candidates`, and even when it is the smallest of them: the call
|
|
139
|
+
/// answers [`Leadership::Incumbent`] with the lease in force and changes
|
|
140
|
+
/// nothing. Otherwise the smallest candidate is elected under a new token.
|
|
141
|
+
///
|
|
142
|
+
/// The election asks the authority for the live grant first
|
|
143
|
+
/// ([`LeaseAuthority::incumbent`]) and acquires only when there is none,
|
|
144
|
+
/// so the authority never has a live grant to refuse.
|
|
145
|
+
///
|
|
146
|
+
/// # Errors
|
|
147
|
+
/// `NoCandidates` (checked first, whatever the clock), or the authority's
|
|
148
|
+
/// refusal, carried whole: `Lease(ClockRegressed)` or `Lease(InvalidTtl)`
|
|
149
|
+
/// (checked before the incumbent, as `acquire` checks them), then
|
|
150
|
+
/// `Lease(Exhausted)` for the grant.
|
|
151
|
+
pub fn elect(
|
|
152
|
+
&mut self,
|
|
153
|
+
candidates: &[OwnerId],
|
|
154
|
+
now: Duration,
|
|
155
|
+
ttl: Duration,
|
|
156
|
+
) -> Result<Leadership, Refusal> {
|
|
157
|
+
let nominee = candidates.iter().copied().min();
|
|
158
|
+
let nominee = nominee.ok_or(Refusal::NoCandidates)?;
|
|
159
|
+
// A query records nothing, so the incumbent answer records nothing.
|
|
160
|
+
if let Some(lease) = self.authority.incumbent(now, ttl)? {
|
|
161
|
+
return Ok(Leadership::Incumbent(lease));
|
|
162
|
+
}
|
|
163
|
+
let granted = self.authority.acquire(nominee, now, ttl);
|
|
164
|
+
granted.map(Leadership::Elected).map_err(Refusal::Lease)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/// Renew leadership only for the matching owner and live fencing token,
|
|
168
|
+
/// retaining the token.
|
|
169
|
+
///
|
|
170
|
+
/// A shorter requested TTL does not shorten the previous expiration, so a
|
|
171
|
+
/// repeated or reordered heartbeat is honoured and never loses time.
|
|
172
|
+
///
|
|
173
|
+
/// # Errors
|
|
174
|
+
/// The authority's refusal of the renewal, carried whole: `Lease(Unknown)`,
|
|
175
|
+
/// `Lease(ClockRegressed)`, `Lease(NoLease)`, `Lease(WrongOwner)`,
|
|
176
|
+
/// `Lease(StaleToken)`, `Lease(Expired)` or `Lease(InvalidTtl)`.
|
|
177
|
+
pub fn heartbeat(
|
|
178
|
+
&mut self,
|
|
179
|
+
owner: OwnerId,
|
|
180
|
+
token: FencingToken,
|
|
181
|
+
now: Duration,
|
|
182
|
+
ttl: Duration,
|
|
183
|
+
) -> Result<Lease, Refusal> {
|
|
184
|
+
let renewed = self.authority.renew(owner, token, now, ttl);
|
|
185
|
+
renewed.map_err(Refusal::Lease)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/// Relinquish unexpired leadership, answering the lease that was given
|
|
189
|
+
/// up. The token count is retained: the next token is still greater.
|
|
190
|
+
///
|
|
191
|
+
/// A repeat is `Lease(NoLease)`, not an honoured duplicate: the election keeps
|
|
192
|
+
/// no record of who resigned what, so it cannot prove the caller's claim.
|
|
193
|
+
///
|
|
194
|
+
/// # Errors
|
|
195
|
+
/// The authority's refusal of the release, carried whole: `Lease(Unknown)`,
|
|
196
|
+
/// `Lease(ClockRegressed)`, `Lease(NoLease)`, `Lease(WrongOwner)`,
|
|
197
|
+
/// `Lease(StaleToken)` or `Lease(Expired)`.
|
|
198
|
+
pub fn resign(
|
|
199
|
+
&mut self,
|
|
200
|
+
owner: OwnerId,
|
|
201
|
+
token: FencingToken,
|
|
202
|
+
now: Duration,
|
|
203
|
+
) -> Result<Lease, Refusal> {
|
|
204
|
+
let released = self.authority.release(owner, token, now);
|
|
205
|
+
released.map_err(Refusal::Lease)
|
|
206
|
+
}
|
|
83
207
|
}
|
|
84
208
|
|
|
209
|
+
#[cfg(test)]
|
|
210
|
+
extern crate std;
|
|
85
211
|
#[cfg(test)]
|
|
86
212
|
mod tests;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
//! The one answer for every call that was not honoured.
|
|
2
|
+
use core::fmt;
|
|
3
|
+
|
|
4
|
+
use lease_machines::Refusal as LeaseRefusal;
|
|
5
|
+
|
|
6
|
+
/// Why a call was not honoured. Every refusal leaves the election exactly as
|
|
7
|
+
/// it was: no grant, no token, no observed clock moves.
|
|
8
|
+
///
|
|
9
|
+
/// [`Refusal::NoCandidates`] is the election's own reason. Every other one is
|
|
10
|
+
/// the embedded [`LeaseAuthority`](lease_machines::LeaseAuthority)'s, carried
|
|
11
|
+
/// whole in [`Refusal::Lease`]: the election copies none of the lease core's
|
|
12
|
+
/// names, so it has no variant it can never answer. Each method documents
|
|
13
|
+
/// which lease refusals can arrive from it.
|
|
14
|
+
///
|
|
15
|
+
/// A nomination under a live incumbent is not a refusal: see
|
|
16
|
+
/// [`Leadership::Incumbent`](crate::Leadership).
|
|
17
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
18
|
+
pub enum Refusal {
|
|
19
|
+
/// The candidate list is empty: there is nobody to nominate.
|
|
20
|
+
NoCandidates,
|
|
21
|
+
/// The lease authority refused, for the reason it gives.
|
|
22
|
+
Lease(LeaseRefusal),
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
impl From<LeaseRefusal> for Refusal {
|
|
26
|
+
fn from(refusal: LeaseRefusal) -> Self {
|
|
27
|
+
Self::Lease(refusal)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
impl fmt::Display for Refusal {
|
|
32
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
33
|
+
f.write_str(match self {
|
|
34
|
+
Self::NoCandidates => "the candidate list is empty",
|
|
35
|
+
Self::Lease(_) => "the lease authority refused",
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// [`Refusal::Lease`] chains to the lease refusal it carries: the message
|
|
41
|
+
/// says the authority refused, the source says why, so an error chain prints
|
|
42
|
+
/// each reason once.
|
|
43
|
+
impl core::error::Error for Refusal {
|
|
44
|
+
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
|
|
45
|
+
match self {
|
|
46
|
+
Self::NoCandidates => None,
|
|
47
|
+
Self::Lease(refusal) => Some(refusal),
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "election_machines_native"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.7"
|
|
4
4
|
edition.workspace = true
|
|
5
5
|
rust-version.workspace = true
|
|
6
6
|
license.workspace = true
|
|
@@ -13,9 +13,9 @@ doctest = false
|
|
|
13
13
|
|
|
14
14
|
[dependencies]
|
|
15
15
|
election-machines.workspace = true
|
|
16
|
-
lease-machines.workspace = true
|
|
17
16
|
magnus.workspace = true
|
|
18
17
|
rb-sys.workspace = true
|
|
18
|
+
matryona-machines = { workspace = true, features = ["ruby"] }
|
|
19
19
|
|
|
20
20
|
[lints]
|
|
21
21
|
workspace = true
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//! The `Data` classes, resolved once at load and pinned. The exact-class
|
|
2
|
+
//! check, the own-or-sibling read (see `values`) and clone-then-keep are
|
|
3
|
+
//! `matryona_machines::ruby`'s.
|
|
4
|
+
use magnus::{Error, RModule, Ruby};
|
|
5
|
+
use matryona_machines::ruby::Class;
|
|
6
|
+
|
|
7
|
+
/// Every `Data` class the binding checks or builds.
|
|
8
|
+
pub struct Classes {
|
|
9
|
+
pub token: Class,
|
|
10
|
+
pub lease: Class,
|
|
11
|
+
pub checkpoint: Class,
|
|
12
|
+
pub elected: Class,
|
|
13
|
+
pub incumbent: Class,
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
matryona_machines::registry! {
|
|
17
|
+
static CLASSES: Classes = "election_machines";
|
|
18
|
+
/// The classes resolved at load.
|
|
19
|
+
pub fn classes;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/// Resolve the classes `election_machines.rb` defined before requiring the
|
|
23
|
+
/// extension. Called once, from init; never by name again.
|
|
24
|
+
pub fn resolve(ruby: &Ruby, module: RModule) -> Result<(), Error> {
|
|
25
|
+
let class = |name| Class::resolve(ruby, module, name);
|
|
26
|
+
let classes = Classes {
|
|
27
|
+
token: class("FencingToken")?,
|
|
28
|
+
lease: class("Lease")?,
|
|
29
|
+
checkpoint: class("Checkpoint")?,
|
|
30
|
+
elected: class("Elected")?,
|
|
31
|
+
incumbent: class("Incumbent")?,
|
|
32
|
+
};
|
|
33
|
+
CLASSES.set(ruby, classes).map(drop)
|
|
34
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
//! `ElectionMachines::Election`.
|
|
2
|
+
use std::cell::RefCell;
|
|
3
|
+
|
|
4
|
+
use election_machines::{Leadership, Lease, OwnerId, Refusal};
|
|
5
|
+
use magnus::{Error, Ruby, Value, prelude::*, typed_data::Obj};
|
|
6
|
+
use matryona_machines::ruby::{
|
|
7
|
+
SymbolNames, Symbols, exact_array,
|
|
8
|
+
fencing::{self, checkpoint, checkpoint_row, lease_object, lease_row},
|
|
9
|
+
instant, integer, keep,
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
use crate::classes::classes;
|
|
13
|
+
use crate::names;
|
|
14
|
+
use crate::values::Family;
|
|
15
|
+
|
|
16
|
+
fn owner(value: Value) -> Result<OwnerId, Error> {
|
|
17
|
+
integer(value, "owner").map(OwnerId::new)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type Core = election_machines::Election;
|
|
21
|
+
|
|
22
|
+
#[magnus::wrap(class = "ElectionMachines::Election", free_immediately, size)]
|
|
23
|
+
pub struct Election(RefCell<Core>);
|
|
24
|
+
|
|
25
|
+
impl Election {
|
|
26
|
+
pub fn with_scope(scope: Value) -> Result<Self, Error> {
|
|
27
|
+
Ok(Self(RefCell::new(Core::with_scope(integer(
|
|
28
|
+
scope, "scope",
|
|
29
|
+
)?))))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
pub fn restored(ruby: &Ruby, scope: Value, saved: Value, clock: Value) -> Result<Self, Error> {
|
|
33
|
+
let (scope, saved) = (integer(scope, "scope")?, checkpoint::<Family>(ruby, saved)?);
|
|
34
|
+
Core::restored(scope, saved, names::ClockPolicies::parse(ruby, clock)?)
|
|
35
|
+
.map(|core| Self(RefCell::new(core)))
|
|
36
|
+
.ok_or_else(|| {
|
|
37
|
+
Error::new(
|
|
38
|
+
ruby.exception_range_error(),
|
|
39
|
+
"the checkpoint is of another scope",
|
|
40
|
+
)
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
pub fn with_clock_policy(ruby: &Ruby, this: Obj<Self>, clock: Value) -> Result<(), Error> {
|
|
45
|
+
this.check_frozen()?;
|
|
46
|
+
let clock = names::ClockPolicies::parse(ruby, clock)?;
|
|
47
|
+
let mut core = this.0.borrow_mut();
|
|
48
|
+
*core = core.clone().with_clock_policy(clock);
|
|
49
|
+
Ok(())
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
pub fn clock_policy(ruby: &Ruby, this: &Self) -> magnus::Symbol {
|
|
53
|
+
names::ClockPolicies::symbol(ruby, this.0.borrow().clock_policy())
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
pub fn scope(&self) -> u16 {
|
|
57
|
+
self.0.borrow().scope()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
pub fn issued(&self) -> u64 {
|
|
61
|
+
self.0.borrow().issued()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
pub fn lease(ruby: &Ruby, this: &Self) -> Option<Value> {
|
|
65
|
+
this.0
|
|
66
|
+
.borrow()
|
|
67
|
+
.lease()
|
|
68
|
+
.map(|held| lease_row::<Family>(ruby, held))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
pub fn checkpoint(ruby: &Ruby, this: &Self) -> Value {
|
|
72
|
+
checkpoint_row::<Family>(ruby, &this.0.borrow().checkpoint())
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
fn refused(ruby: &Ruby, refusal: Refusal) -> Value {
|
|
76
|
+
names::Refusals::symbol(ruby, &refusal).as_value()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// An `Elected` or `Incumbent` when honoured, or the refusal symbol.
|
|
80
|
+
/// Every candidate is converted before the core is called. The answer is
|
|
81
|
+
/// built while the decision is held on a copy, kept only once it exists
|
|
82
|
+
/// (clone-then-keep).
|
|
83
|
+
pub fn elect(
|
|
84
|
+
ruby: &Ruby,
|
|
85
|
+
this: Obj<Self>,
|
|
86
|
+
candidates: Value,
|
|
87
|
+
now: Value,
|
|
88
|
+
ttl: Value,
|
|
89
|
+
) -> Result<Value, Error> {
|
|
90
|
+
this.check_frozen()?;
|
|
91
|
+
let message = "candidates must be an Array of Integers";
|
|
92
|
+
let candidates = exact_array(ruby, candidates, message)?;
|
|
93
|
+
let mut owners = Vec::with_capacity(candidates.len());
|
|
94
|
+
for candidate in candidates {
|
|
95
|
+
owners.push(OwnerId::new(integer(candidate, "candidate")?));
|
|
96
|
+
}
|
|
97
|
+
let (now, ttl) = (instant(now, "now")?, instant(ttl, "ttl")?);
|
|
98
|
+
let classes = classes(ruby)?;
|
|
99
|
+
let decide = |core: &mut Core| core.elect(&owners, now, ttl);
|
|
100
|
+
keep(ruby, this, &this.0, decide, |outcome| {
|
|
101
|
+
let (class, lease) = match outcome {
|
|
102
|
+
Ok(Leadership::Elected(lease)) => (classes.elected, lease),
|
|
103
|
+
Ok(Leadership::Incumbent(lease)) => (classes.incumbent, lease),
|
|
104
|
+
Err(refusal) => return Ok(Self::refused(ruby, refusal)),
|
|
105
|
+
};
|
|
106
|
+
class
|
|
107
|
+
.get(ruby)
|
|
108
|
+
.funcall("new", (lease_object::<Family>(ruby, lease)?,))
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// A `Lease` when honoured, or the refusal symbol. Everything that can
|
|
113
|
+
/// raise happens before the core is called; the `Lease` is built while
|
|
114
|
+
/// the decision is held on a copy (clone-then-keep).
|
|
115
|
+
fn decide(
|
|
116
|
+
ruby: &Ruby,
|
|
117
|
+
this: Obj<Self>,
|
|
118
|
+
call: impl FnOnce(&mut Core) -> Result<Lease, Refusal>,
|
|
119
|
+
) -> Result<Value, Error> {
|
|
120
|
+
keep(ruby, this, &this.0, call, |decision| match decision {
|
|
121
|
+
Ok(lease) => lease_object::<Family>(ruby, lease),
|
|
122
|
+
Err(refusal) => Ok(Self::refused(ruby, refusal)),
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
pub fn heartbeat(
|
|
127
|
+
ruby: &Ruby,
|
|
128
|
+
this: Obj<Self>,
|
|
129
|
+
owner: Value,
|
|
130
|
+
token: Value,
|
|
131
|
+
now: Value,
|
|
132
|
+
ttl: Value,
|
|
133
|
+
) -> Result<Value, Error> {
|
|
134
|
+
this.check_frozen()?;
|
|
135
|
+
let (owner, token) = (self::owner(owner)?, fencing::token::<Family>(ruby, token)?);
|
|
136
|
+
let (now, ttl) = (instant(now, "now")?, instant(ttl, "ttl")?);
|
|
137
|
+
Self::decide(ruby, this, |core| core.heartbeat(owner, token, now, ttl))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
pub fn resign(
|
|
141
|
+
ruby: &Ruby,
|
|
142
|
+
this: Obj<Self>,
|
|
143
|
+
owner: Value,
|
|
144
|
+
token: Value,
|
|
145
|
+
now: Value,
|
|
146
|
+
) -> Result<Value, Error> {
|
|
147
|
+
this.check_frozen()?;
|
|
148
|
+
let (owner, token) = (self::owner(owner)?, fencing::token::<Family>(ruby, token)?);
|
|
149
|
+
let now = instant(now, "now")?;
|
|
150
|
+
Self::decide(ruby, this, |core| core.resign(owner, token, now))
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -1,18 +1,53 @@
|
|
|
1
|
-
//! Private
|
|
1
|
+
//! Private native entry point.
|
|
2
2
|
use magnus::{Error, Ruby, function, method, prelude::*};
|
|
3
|
+
use matryona_machines::ruby::{Class, Symbols, fencing, symbol};
|
|
4
|
+
|
|
5
|
+
use crate::election::Election;
|
|
6
|
+
use crate::values::Family;
|
|
7
|
+
use crate::{classes, names};
|
|
8
|
+
|
|
3
9
|
#[magnus::init]
|
|
4
10
|
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
5
11
|
let module = ruby.define_module("ElectionMachines")?;
|
|
6
|
-
module
|
|
7
|
-
|
|
8
|
-
.
|
|
12
|
+
classes::resolve(ruby, module)?;
|
|
13
|
+
let symbols = |names: &[&str]| {
|
|
14
|
+
let list = ruby.ary_from_iter(names.iter().map(|name| symbol(ruby, name)));
|
|
15
|
+
list.freeze();
|
|
16
|
+
list
|
|
17
|
+
};
|
|
18
|
+
module.const_set("REFUSALS", symbols(&names::REFUSALS))?;
|
|
19
|
+
module.const_set("CLOCK_POLICIES", names::ClockPolicies::every(ruby))?;
|
|
20
|
+
let scope = function!(fencing::token_scope::<Family>, 1);
|
|
21
|
+
module.define_singleton_method("native_token_scope", scope)?;
|
|
22
|
+
let order = function!(fencing::token_order::<Family>, 2);
|
|
23
|
+
module.define_singleton_method("native_token_order", order)?;
|
|
24
|
+
let newer = function!(fencing::token_newer::<Family>, 2);
|
|
25
|
+
module.define_singleton_method("native_token_newer", newer)?;
|
|
26
|
+
let raw = function!(fencing::validate_raw::<Family>, 1);
|
|
27
|
+
module.define_singleton_method("native_raw", raw)?;
|
|
28
|
+
let lease = function!(fencing::validate_lease::<Family>, 3);
|
|
29
|
+
module.define_singleton_method("native_lease", lease)?;
|
|
30
|
+
let held = function!(fencing::own_lease::<Family>, 1);
|
|
31
|
+
module.define_singleton_method("native_held", held)?;
|
|
32
|
+
let checkpoint = function!(fencing::validate_checkpoint::<Family>, 4);
|
|
33
|
+
module.define_singleton_method("native_checkpoint", checkpoint)?;
|
|
34
|
+
|
|
9
35
|
let class = module.define_class("Election", ruby.class_object())?;
|
|
10
36
|
class.undef_default_alloc_func();
|
|
11
|
-
class.define_singleton_method("
|
|
12
|
-
class.
|
|
13
|
-
class.define_method("
|
|
14
|
-
class.define_method("
|
|
15
|
-
class.define_method("
|
|
16
|
-
class.
|
|
17
|
-
|
|
37
|
+
class.define_singleton_method("native_with_scope", function!(Election::with_scope, 1))?;
|
|
38
|
+
class.define_singleton_method("native_restored", function!(Election::restored, 3))?;
|
|
39
|
+
class.define_method("scope", method!(Election::scope, 0))?;
|
|
40
|
+
class.define_method("issued", method!(Election::issued, 0))?;
|
|
41
|
+
class.define_method("clock_policy", method!(Election::clock_policy, 0))?;
|
|
42
|
+
class.define_private_method(
|
|
43
|
+
"native_with_clock_policy",
|
|
44
|
+
method!(Election::with_clock_policy, 1),
|
|
45
|
+
)?;
|
|
46
|
+
class.define_private_method("native_lease", method!(Election::lease, 0))?;
|
|
47
|
+
class.define_private_method("native_checkpoint", method!(Election::checkpoint, 0))?;
|
|
48
|
+
class.define_private_method("native_elect", method!(Election::elect, 3))?;
|
|
49
|
+
class.define_private_method("native_heartbeat", method!(Election::heartbeat, 4))?;
|
|
50
|
+
class.define_private_method("native_resign", method!(Election::resign, 3))?;
|
|
51
|
+
// Fix magnus's class for Election now: building one later runs no Ruby.
|
|
52
|
+
Class::pin_wrapped::<Election>(ruby, class).map(drop)
|
|
18
53
|
}
|