rogue_machines 0.1.2 → 0.5.0

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.
@@ -1,288 +0,0 @@
1
- //! `RogueMachines::Rogue`: the experiments a process is running, by name.
2
-
3
- use std::cell::{Cell, RefCell};
4
- use std::collections::HashMap;
5
-
6
- use magnus::scan_args::{get_kwargs, scan_args};
7
- use magnus::{Error, RArray, RHash, RModule, Ruby, Value, function, method, prelude::*};
8
- use rogue_machines::{Decision, EXPERIMENTS, Experiment, Fault, Rogue, Slot};
9
-
10
- use crate::injection::injection;
11
- use crate::{LONGEST_DELAY, LONGEST_EXPERIMENT, counted, draw, duration, error, reading, share};
12
-
13
- /// The core registry, and the names standing in for its slot indices.
14
- #[magnus::wrap(class = "RogueMachines::Rogue", free_immediately, size)]
15
- struct Wrapper {
16
- rogue: RefCell<Rogue>,
17
- slots: RefCell<HashMap<String, Slot>>,
18
- /// Which clock the armed expiries were computed against.
19
- ///
20
- /// Every reading is only meaningful for one of these. A caller samples a
21
- /// reading before it synchronises, so a reading that arrives after the
22
- /// clock was replaced would otherwise be compared against expiries it has
23
- /// no relation to, and `sweep` is destructive.
24
- generation: Cell<u32>,
25
- }
26
-
27
- impl Wrapper {
28
- fn new() -> Self {
29
- Self {
30
- rogue: RefCell::new(Rogue::new()),
31
- slots: RefCell::new(HashMap::new()),
32
- generation: Cell::new(0),
33
- }
34
- }
35
-
36
- /// Whether any experiment is armed, which is the whole of the decision a
37
- /// disarmed process takes.
38
- fn any_armed(&self) -> bool {
39
- self.rogue.borrow().any_armed()
40
- }
41
-
42
- const fn generation(&self) -> u32 {
43
- self.generation.get()
44
- }
45
-
46
- /// Disarms everything and starts a generation, so readings taken against
47
- /// the outgoing clock are refused rather than acted on.
48
- fn invalidate(&self) -> u32 {
49
- self.slots.borrow_mut().clear();
50
- self.rogue.borrow_mut().disarm_all();
51
- let next = self.generation.get().wrapping_add(1);
52
- self.generation.set(next);
53
- next
54
- }
55
-
56
- const fn current(&self, generation: u32) -> bool {
57
- self.generation.get() == generation
58
- }
59
-
60
- fn armed_count(
61
- ruby: &Ruby,
62
- rb_self: &Self,
63
- given_now: Value,
64
- given_age: Value,
65
- ) -> Result<u32, Error> {
66
- let generation = counted(ruby, "generation", given_age)?;
67
- if !rb_self.current(generation) {
68
- return Ok(0);
69
- }
70
- let now_ns = reading(ruby, "now_ns", given_now)?;
71
- let rogue = rb_self.rogue.borrow();
72
- rogue.sweep(now_ns);
73
- Ok(rogue.armed_count())
74
- }
75
-
76
- /// Arms `name`, replacing any experiment already under it.
77
- ///
78
- /// `fault:` is `:raise`, `:delay` or `:garble`, `share:` is the fraction of
79
- /// calls it reaches, and `expires_in:` is how long it runs for from
80
- /// `now_ns:`. A `:delay` also takes `delay:`, in seconds.
81
- fn arm(ruby: &Ruby, rb_self: &Self, args: &[Value]) -> Result<(), Error> {
82
- let args = scan_args::<(String,), (), (), (), RHash, ()>(args)?;
83
- let (name,) = args.required;
84
- let keywords = get_kwargs::<_, (String, f64, f64, Value, Value), (Option<f64>,), ()>(
85
- args.keywords,
86
- &["fault", "share", "expires_in", "now_ns", "generation"],
87
- &["delay"],
88
- )?;
89
- let (named, given_share, expires_in, given_now, given_age) = keywords.required;
90
- let generation = counted(ruby, "generation", given_age)?;
91
- if !rb_self.current(generation) {
92
- return Err(error(
93
- ruby,
94
- "the clock was replaced while arming; nothing was armed".to_owned(),
95
- ));
96
- }
97
- let now_ns = reading(ruby, "now_ns", given_now)?;
98
- let (delay,) = keywords.optional;
99
-
100
- let expires_at_ns = now_ns
101
- .checked_add(duration(
102
- ruby,
103
- "expires_in",
104
- expires_in,
105
- LONGEST_EXPERIMENT,
106
- )?)
107
- .ok_or_else(|| {
108
- Error::new(
109
- ruby.exception_arg_error(),
110
- "expires_in puts the expiry past the end of the clock",
111
- )
112
- })?;
113
- let fraction = share(ruby, given_share)?;
114
- let fault = fault(ruby, &named, delay)?;
115
- let slot = rb_self.slot_for(ruby, name, now_ns)?;
116
-
117
- rb_self
118
- .rogue
119
- .borrow_mut()
120
- .arm(slot, Experiment::new(fault, fraction, expires_at_ns));
121
- Ok(())
122
- }
123
-
124
- /// Disarms `name`, freeing its slot. Reports whether it was still running,
125
- /// which an experiment that expired on its own is not.
126
- fn disarm(
127
- ruby: &Ruby,
128
- rb_self: &Self,
129
- name: String,
130
- given_now: Value,
131
- given_age: Value,
132
- ) -> Result<bool, Error> {
133
- let generation = counted(ruby, "generation", given_age)?;
134
- if !rb_self.current(generation) {
135
- return Ok(false);
136
- }
137
- let now_ns = reading(ruby, "now_ns", given_now)?;
138
- let Some(slot) = rb_self.slots.borrow_mut().remove(&name) else {
139
- return Ok(false);
140
- };
141
- let was_running = rb_self.rogue.borrow().active(slot, now_ns).is_some();
142
- rb_self.rogue.borrow_mut().disarm(slot);
143
- Ok(was_running)
144
- }
145
-
146
- fn disarm_all(&self) {
147
- self.slots.borrow_mut().clear();
148
- self.rogue.borrow_mut().disarm_all();
149
- }
150
-
151
- /// The names still running at `now_ns`, in no particular order.
152
- fn armed(
153
- ruby: &Ruby,
154
- rb_self: &Self,
155
- given_now: Value,
156
- given_age: Value,
157
- ) -> Result<RArray, Error> {
158
- let generation = counted(ruby, "generation", given_age)?;
159
- if !rb_self.current(generation) {
160
- return Ok(ruby.ary_new());
161
- }
162
- let now_ns = reading(ruby, "now_ns", given_now)?;
163
- let running: Vec<String> = {
164
- let rogue = rb_self.rogue.borrow();
165
- rb_self
166
- .slots
167
- .borrow()
168
- .iter()
169
- .filter(|(_, slot)| rogue.active(**slot, now_ns).is_some())
170
- .map(|(name, _)| name.clone())
171
- .collect()
172
- };
173
- Ok(ruby.ary_from_iter(running))
174
- }
175
-
176
- /// The fault to perform for one call, or `nil` to make the real one.
177
- ///
178
- /// `draw` is the caller's, below `PER_MILLION`, and decides which calls an
179
- /// experiment reaches.
180
- fn decide(
181
- ruby: &Ruby,
182
- rb_self: &Self,
183
- name: String,
184
- given_now: Value,
185
- given_draw: Value,
186
- given_age: Value,
187
- ) -> Result<Option<Value>, Error> {
188
- let generation = counted(ruby, "generation", given_age)?;
189
- if !rb_self.current(generation) {
190
- return Ok(None);
191
- }
192
- let now_ns = reading(ruby, "now_ns", given_now)?;
193
- let drawn = draw(ruby, given_draw)?;
194
- let decision = {
195
- let rogue = rb_self.rogue.borrow();
196
- if !rogue.any_armed() {
197
- return Ok(None);
198
- }
199
- rogue.sweep(now_ns);
200
- let Some(slot) = rb_self.slots.borrow().get(&name).copied() else {
201
- return Ok(None);
202
- };
203
- rogue.decide(slot, now_ns, drawn)
204
- };
205
- match decision {
206
- Decision::Pass => Ok(None),
207
- Decision::Inject(fault) => injection(ruby, fault).map(Some),
208
- }
209
- }
210
-
211
- /// The slot already standing for `name`, or the lowest free one.
212
- ///
213
- /// An expired experiment releases its bit in the core but not its name, so
214
- /// the names of everything no longer armed are dropped first; otherwise a
215
- /// run of short experiments exhausts the slots.
216
- fn slot_for(&self, ruby: &Ruby, name: String, now_ns: u64) -> Result<Slot, Error> {
217
- let existing = {
218
- let rogue = self.rogue.borrow();
219
- let mut slots = self.slots.borrow_mut();
220
- slots.retain(|held, slot| *held == name || rogue.active(*slot, now_ns).is_some());
221
- slots.get(&name).copied()
222
- };
223
- if let Some(slot) = existing {
224
- return Ok(slot);
225
- }
226
- let mut slots = self.slots.borrow_mut();
227
- let taken: Vec<usize> = slots.values().map(|slot| slot.index()).collect();
228
- let free = (0..EXPERIMENTS)
229
- .find(|index| !taken.contains(index))
230
- .and_then(Slot::new)
231
- .ok_or_else(|| {
232
- error(
233
- ruby,
234
- format!("all {EXPERIMENTS} experiment slots are taken; disarm one first"),
235
- )
236
- })?;
237
- slots.insert(name, free);
238
- Ok(free)
239
- }
240
-
241
- /// Reports the mask as it stood at the last decision, since `inspect`
242
- /// takes no reading and so cannot retire an expired experiment itself.
243
- fn inspect(&self) -> String {
244
- format!(
245
- "#<RogueMachines::Rogue armed={} of {EXPERIMENTS} at the last decision>",
246
- self.rogue.borrow().armed_count()
247
- )
248
- }
249
- }
250
-
251
- /// The fault a `fault:` keyword names.
252
- fn fault(ruby: &Ruby, named: &str, delay: Option<f64>) -> Result<Fault, Error> {
253
- match named {
254
- "raise" => Ok(Fault::Raise),
255
- "garble" => Ok(Fault::Garble),
256
- "delay" => {
257
- let seconds = delay.ok_or_else(|| {
258
- Error::new(
259
- ruby.exception_arg_error(),
260
- "a :delay fault needs delay: in seconds",
261
- )
262
- })?;
263
- Ok(Fault::Delay {
264
- ns: duration(ruby, "delay", seconds, LONGEST_DELAY)?,
265
- })
266
- }
267
- other => Err(Error::new(
268
- ruby.exception_arg_error(),
269
- format!("fault must be :raise, :delay or :garble, got {other:?}"),
270
- )),
271
- }
272
- }
273
-
274
- pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
275
- let class = module.define_class("Rogue", ruby.class_object())?;
276
- class.define_singleton_method("new", function!(Wrapper::new, 0))?;
277
- class.define_method("any_armed?", method!(Wrapper::any_armed, 0))?;
278
- class.define_method("armed_count", method!(Wrapper::armed_count, 2))?;
279
- class.define_method("arm", method!(Wrapper::arm, -1))?;
280
- class.define_method("disarm", method!(Wrapper::disarm, 3))?;
281
- class.define_method("disarm_all", method!(Wrapper::disarm_all, 0))?;
282
- class.define_method("generation", method!(Wrapper::generation, 0))?;
283
- class.define_method("invalidate", method!(Wrapper::invalidate, 0))?;
284
- class.define_method("armed", method!(Wrapper::armed, 2))?;
285
- class.define_method("decide", method!(Wrapper::decide, 4))?;
286
- class.define_method("inspect", method!(Wrapper::inspect, 0))?;
287
- Ok(())
288
- }