budget_machines 0.4.4
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 +7 -0
- data/CHANGELOG.md +76 -0
- data/Cargo.lock +307 -0
- data/Cargo.toml +27 -0
- data/LICENSE.txt +21 -0
- data/README.md +306 -0
- data/ext/budget_machines_native/core/CHANGELOG.md +55 -0
- data/ext/budget_machines_native/core/Cargo.toml +17 -0
- data/ext/budget_machines_native/core/README.md +82 -0
- data/ext/budget_machines_native/core/src/ledger.rs +251 -0
- data/ext/budget_machines_native/core/src/lib.rs +180 -0
- data/ext/budget_machines_native/core/src/monitor.rs +424 -0
- data/ext/budget_machines_native/extconf.rb +2 -0
- data/ext/budget_machines_native/ffi/Cargo.toml +21 -0
- data/ext/budget_machines_native/ffi/extconf.rb +14 -0
- data/ext/budget_machines_native/ffi/src/classes.rs +50 -0
- data/ext/budget_machines_native/ffi/src/init.rs +50 -0
- data/ext/budget_machines_native/ffi/src/ledger.rs +117 -0
- data/ext/budget_machines_native/ffi/src/lib.rs +117 -0
- data/ext/budget_machines_native/ffi/src/monitor.rs +216 -0
- data/ext/budget_machines_native/ffi/src/values.rs +226 -0
- data/lib/budget_machines/version.rb +5 -0
- data/lib/budget_machines.rb +158 -0
- data/sig/budget_machines.rbs +183 -0
- metadata +89 -0
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
//! Multi-window burn-rate alerting with explicit no-data handling.
|
|
2
|
+
|
|
3
|
+
use core::time::Duration;
|
|
4
|
+
|
|
5
|
+
use crate::{Counts, Objective, Refusal};
|
|
6
|
+
|
|
7
|
+
/// One window's reading.
|
|
8
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
9
|
+
pub enum Sample {
|
|
10
|
+
/// The caller has no reading for this window.
|
|
11
|
+
NoData,
|
|
12
|
+
/// Exact counts. Zero events, or fewer than the monitor's minimum, still
|
|
13
|
+
/// count as no data.
|
|
14
|
+
Counts(Counts),
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/// The long and short window readings one rule is judged on.
|
|
18
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
19
|
+
pub struct Windows {
|
|
20
|
+
/// Long window: is the burn significant?
|
|
21
|
+
pub long: Sample,
|
|
22
|
+
/// Short window: is it still happening?
|
|
23
|
+
pub short: Sample,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// What a rule does when either of its windows has no data.
|
|
27
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
28
|
+
pub enum OnNoData {
|
|
29
|
+
/// Keep the previous state.
|
|
30
|
+
Hold,
|
|
31
|
+
/// Fall back to [`State::NoData`], clearing a firing alert.
|
|
32
|
+
Reset,
|
|
33
|
+
/// Treat silence as an outage and fire.
|
|
34
|
+
Fire,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// A burn-rate rule: fire when both windows burn at `fire_milli` or more, and
|
|
38
|
+
/// once firing stay so until either window drops below `clear_milli`.
|
|
39
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
40
|
+
pub struct Rule {
|
|
41
|
+
fire_milli: u32,
|
|
42
|
+
clear_milli: u32,
|
|
43
|
+
severity: u8,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
impl Rule {
|
|
47
|
+
/// `None` unless `0 < clear_milli <= fire_milli`. Equal thresholds give
|
|
48
|
+
/// the plain stateless rule; a lower clear threshold adds hysteresis.
|
|
49
|
+
#[must_use]
|
|
50
|
+
pub const fn new(fire_milli: u32, clear_milli: u32, severity: u8) -> Option<Self> {
|
|
51
|
+
if clear_milli == 0 || clear_milli > fire_milli {
|
|
52
|
+
return None;
|
|
53
|
+
}
|
|
54
|
+
Some(Self {
|
|
55
|
+
fire_milli,
|
|
56
|
+
clear_milli,
|
|
57
|
+
severity,
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Burn rate in thousandths at which the rule fires.
|
|
62
|
+
#[must_use]
|
|
63
|
+
pub const fn fire_milli(self) -> u32 {
|
|
64
|
+
self.fire_milli
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// Burn rate in thousandths below which a firing rule clears.
|
|
68
|
+
#[must_use]
|
|
69
|
+
pub const fn clear_milli(self) -> u32 {
|
|
70
|
+
self.clear_milli
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// Caller-defined rank; higher wins [`Verdict::worst`].
|
|
74
|
+
#[must_use]
|
|
75
|
+
pub const fn severity(self) -> u8 {
|
|
76
|
+
self.severity
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/// A rule's alert state.
|
|
81
|
+
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
|
82
|
+
pub enum State {
|
|
83
|
+
/// Never measured, or reset by missing data.
|
|
84
|
+
#[default]
|
|
85
|
+
NoData,
|
|
86
|
+
/// Measured and not alerting.
|
|
87
|
+
Quiet,
|
|
88
|
+
/// Alerting.
|
|
89
|
+
Firing,
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/// What an evaluation did to a rule's alert.
|
|
93
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
94
|
+
pub enum Change {
|
|
95
|
+
/// The alert neither started nor stopped.
|
|
96
|
+
None,
|
|
97
|
+
/// The alert started firing.
|
|
98
|
+
Raised,
|
|
99
|
+
/// The alert stopped firing.
|
|
100
|
+
Cleared,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// One rule's outcome for one evaluation.
|
|
104
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
105
|
+
pub struct Decision {
|
|
106
|
+
state: State,
|
|
107
|
+
change: Change,
|
|
108
|
+
long_milli: Option<u64>,
|
|
109
|
+
short_milli: Option<u64>,
|
|
110
|
+
since: Option<Duration>,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
impl Decision {
|
|
114
|
+
/// A decision rebuilt from its fields, or `None` when no evaluation could
|
|
115
|
+
/// have produced it: `Raised` lands in `Firing` and `Cleared` leaves it;
|
|
116
|
+
/// an alert edge has the instant it happened; a decision with both burn
|
|
117
|
+
/// rates was measured, so its state is `Quiet` or `Firing`.
|
|
118
|
+
#[must_use]
|
|
119
|
+
pub const fn new(
|
|
120
|
+
state: State,
|
|
121
|
+
change: Change,
|
|
122
|
+
long_milli: Option<u64>,
|
|
123
|
+
short_milli: Option<u64>,
|
|
124
|
+
since: Option<Duration>,
|
|
125
|
+
) -> Option<Self> {
|
|
126
|
+
let firing = matches!(state, State::Firing);
|
|
127
|
+
let edge = match change {
|
|
128
|
+
Change::None => true,
|
|
129
|
+
Change::Raised => firing && since.is_some(),
|
|
130
|
+
Change::Cleared => !firing && since.is_some(),
|
|
131
|
+
};
|
|
132
|
+
let measured = long_milli.is_some() && short_milli.is_some();
|
|
133
|
+
if !edge || (measured && matches!(state, State::NoData)) {
|
|
134
|
+
return None;
|
|
135
|
+
}
|
|
136
|
+
Some(Self {
|
|
137
|
+
state,
|
|
138
|
+
change,
|
|
139
|
+
long_milli,
|
|
140
|
+
short_milli,
|
|
141
|
+
since,
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// State after the evaluation.
|
|
146
|
+
#[must_use]
|
|
147
|
+
pub const fn state(&self) -> State {
|
|
148
|
+
self.state
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// Alert edge, if any.
|
|
152
|
+
#[must_use]
|
|
153
|
+
pub const fn change(&self) -> Change {
|
|
154
|
+
self.change
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/// Whether both windows had data, so both burn rates are known. `false`
|
|
158
|
+
/// means `state` came from the no-data policy, not from a measurement.
|
|
159
|
+
#[must_use]
|
|
160
|
+
pub const fn measured(&self) -> bool {
|
|
161
|
+
self.long_milli.is_some() && self.short_milli.is_some()
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/// Long-window burn rate in thousandths; `None` without data.
|
|
165
|
+
#[must_use]
|
|
166
|
+
pub const fn long_milli(&self) -> Option<u64> {
|
|
167
|
+
self.long_milli
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/// Short-window burn rate in thousandths; `None` without data.
|
|
171
|
+
#[must_use]
|
|
172
|
+
pub const fn short_milli(&self) -> Option<u64> {
|
|
173
|
+
self.short_milli
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/// Instant the rule entered `state`; `None` if it never left its start.
|
|
177
|
+
#[must_use]
|
|
178
|
+
pub const fn since(&self) -> Option<Duration> {
|
|
179
|
+
self.since
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const UNDECIDED: Decision = Decision {
|
|
184
|
+
state: State::NoData,
|
|
185
|
+
change: Change::None,
|
|
186
|
+
long_milli: None,
|
|
187
|
+
short_milli: None,
|
|
188
|
+
since: None,
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
/// Every rule's decision for one evaluation, in rule order.
|
|
192
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
193
|
+
pub struct Verdict<const R: usize> {
|
|
194
|
+
decisions: [Decision; R],
|
|
195
|
+
len: usize,
|
|
196
|
+
worst: Option<usize>,
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
impl<const R: usize> Verdict<R> {
|
|
200
|
+
/// A verdict rebuilt from its parts, or `None` when no evaluation could
|
|
201
|
+
/// have produced it: more than `R` decisions, or a `worst` that is not
|
|
202
|
+
/// the index of a firing decision, or no `worst` while one fires.
|
|
203
|
+
#[must_use]
|
|
204
|
+
pub fn new(decisions: &[Decision], worst: Option<usize>) -> Option<Self> {
|
|
205
|
+
let mut held = [UNDECIDED; R];
|
|
206
|
+
held.get_mut(..decisions.len())?.copy_from_slice(decisions);
|
|
207
|
+
let firing = decisions
|
|
208
|
+
.iter()
|
|
209
|
+
.any(|decision| decision.state == State::Firing);
|
|
210
|
+
let named = worst.map_or(!firing, |index| {
|
|
211
|
+
decisions
|
|
212
|
+
.get(index)
|
|
213
|
+
.is_some_and(|decision| decision.state == State::Firing)
|
|
214
|
+
});
|
|
215
|
+
named.then_some(Self {
|
|
216
|
+
decisions: held,
|
|
217
|
+
len: decisions.len(),
|
|
218
|
+
worst,
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/// One decision per rule.
|
|
223
|
+
#[must_use]
|
|
224
|
+
pub fn decisions(&self) -> &[Decision] {
|
|
225
|
+
self.decisions.get(..self.len).unwrap_or_else(|| {
|
|
226
|
+
debug_assert!(false, "a verdict holds at most R decisions");
|
|
227
|
+
&[]
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/// Index of the firing rule with the highest severity; the earliest rule
|
|
232
|
+
/// wins a tie. `None` when nothing fires.
|
|
233
|
+
#[must_use]
|
|
234
|
+
pub const fn worst(&self) -> Option<usize> {
|
|
235
|
+
self.worst
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
240
|
+
struct Slot {
|
|
241
|
+
rule: Rule,
|
|
242
|
+
state: State,
|
|
243
|
+
since: Option<Duration>,
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/// Up to `R` burn-rate rules over one objective.
|
|
247
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
248
|
+
pub struct Monitor<const R: usize> {
|
|
249
|
+
objective: Objective,
|
|
250
|
+
policy: OnNoData,
|
|
251
|
+
min_total: u64,
|
|
252
|
+
slots: [Option<Slot>; R],
|
|
253
|
+
len: usize,
|
|
254
|
+
last: Option<Duration>,
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
impl<const R: usize> Monitor<R> {
|
|
258
|
+
/// Monitor with no rules. A window with fewer than `min_total` events (and
|
|
259
|
+
/// always one with none) is treated as no data.
|
|
260
|
+
#[must_use]
|
|
261
|
+
pub const fn new(objective: Objective, policy: OnNoData, min_total: u64) -> Self {
|
|
262
|
+
Self {
|
|
263
|
+
objective,
|
|
264
|
+
policy,
|
|
265
|
+
min_total,
|
|
266
|
+
slots: [None; R],
|
|
267
|
+
len: 0,
|
|
268
|
+
last: None,
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/// Append a rule, starting in [`State::NoData`], and return its index.
|
|
273
|
+
///
|
|
274
|
+
/// # Errors
|
|
275
|
+
/// [`Refusal::Full`] when all `R` slots are taken.
|
|
276
|
+
pub fn add_rule(&mut self, rule: Rule) -> Result<usize, Refusal> {
|
|
277
|
+
let index = self.len;
|
|
278
|
+
let slot = self.slots.get_mut(index).ok_or(Refusal::Full)?;
|
|
279
|
+
*slot = Some(Slot {
|
|
280
|
+
rule,
|
|
281
|
+
state: State::NoData,
|
|
282
|
+
since: None,
|
|
283
|
+
});
|
|
284
|
+
self.len += 1;
|
|
285
|
+
Ok(index)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/// Number of rules.
|
|
289
|
+
#[must_use]
|
|
290
|
+
pub const fn len(&self) -> usize {
|
|
291
|
+
self.len
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/// Whether no rule has been added.
|
|
295
|
+
#[must_use]
|
|
296
|
+
pub const fn is_empty(&self) -> bool {
|
|
297
|
+
self.len == 0
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/// The objective being monitored.
|
|
301
|
+
#[must_use]
|
|
302
|
+
pub const fn objective(&self) -> Objective {
|
|
303
|
+
self.objective
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/// Rule at `index`.
|
|
307
|
+
#[must_use]
|
|
308
|
+
pub fn rule(&self, index: usize) -> Option<Rule> {
|
|
309
|
+
self.slot(index).map(|slot| slot.rule)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/// Current state of the rule at `index`.
|
|
313
|
+
#[must_use]
|
|
314
|
+
pub fn state(&self, index: usize) -> Option<State> {
|
|
315
|
+
self.slot(index).map(|slot| slot.state)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/// Instant of the latest accepted evaluation.
|
|
319
|
+
#[must_use]
|
|
320
|
+
pub const fn last(&self) -> Option<Duration> {
|
|
321
|
+
self.last
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/// Index of the firing rule with the highest severity, earliest on a tie.
|
|
325
|
+
#[must_use]
|
|
326
|
+
pub fn worst(&self) -> Option<usize> {
|
|
327
|
+
let mut worst: Option<(usize, u8)> = None;
|
|
328
|
+
for (index, slot) in self.slots.iter().flatten().enumerate() {
|
|
329
|
+
let outranks = worst.is_none_or(|(_, severity)| slot.rule.severity > severity);
|
|
330
|
+
if slot.state == State::Firing && outranks {
|
|
331
|
+
worst = Some((index, slot.rule.severity));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
worst.map(|(index, _)| index)
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/// Judge every rule on its window pair, `windows[i]` for rule `i`.
|
|
338
|
+
///
|
|
339
|
+
/// `now` is monotonic time since an epoch the caller picks. It orders
|
|
340
|
+
/// evaluations and stamps [`Decision::since`]; the window lengths are the
|
|
341
|
+
/// caller's and never reach the monitor.
|
|
342
|
+
///
|
|
343
|
+
/// # Errors
|
|
344
|
+
/// [`Refusal::TimeRegression`] when `now` precedes the previous evaluation
|
|
345
|
+
/// and [`Refusal::Shape`] when `windows` does not hold one pair per rule.
|
|
346
|
+
/// Neither changes any alert state.
|
|
347
|
+
pub fn evaluate(&mut self, now: Duration, windows: &[Windows]) -> Result<Verdict<R>, Refusal> {
|
|
348
|
+
if self.last.is_some_and(|last| now < last) {
|
|
349
|
+
return Err(Refusal::TimeRegression);
|
|
350
|
+
}
|
|
351
|
+
if windows.len() != self.len {
|
|
352
|
+
return Err(Refusal::Shape);
|
|
353
|
+
}
|
|
354
|
+
let (objective, policy, floor) = (self.objective, self.policy, self.min_total);
|
|
355
|
+
let mut decisions = [UNDECIDED; R];
|
|
356
|
+
let pairs = self.slots.iter_mut().flatten().zip(windows);
|
|
357
|
+
for ((slot, pair), decision) in pairs.zip(decisions.iter_mut()) {
|
|
358
|
+
*decision = judge(objective, policy, floor, slot, *pair, now);
|
|
359
|
+
}
|
|
360
|
+
self.last = Some(now);
|
|
361
|
+
Ok(Verdict {
|
|
362
|
+
decisions,
|
|
363
|
+
len: self.len,
|
|
364
|
+
worst: self.worst(),
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
fn slot(&self, index: usize) -> Option<&Slot> {
|
|
369
|
+
self.slots.get(index).and_then(Option::as_ref)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const fn usable(sample: Sample, floor: u64) -> Option<Counts> {
|
|
374
|
+
match sample {
|
|
375
|
+
Sample::Counts(counts) if counts.total() > 0 && counts.total() >= floor => Some(counts),
|
|
376
|
+
Sample::Counts(_) | Sample::NoData => None,
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
fn judge(
|
|
381
|
+
objective: Objective,
|
|
382
|
+
policy: OnNoData,
|
|
383
|
+
floor: u64,
|
|
384
|
+
slot: &mut Slot,
|
|
385
|
+
pair: Windows,
|
|
386
|
+
now: Duration,
|
|
387
|
+
) -> Decision {
|
|
388
|
+
let (long, short) = (usable(pair.long, floor), usable(pair.short, floor));
|
|
389
|
+
let was_firing = slot.state == State::Firing;
|
|
390
|
+
let state = if let (Some(long), Some(short)) = (long, short) {
|
|
391
|
+
let bar = if was_firing {
|
|
392
|
+
slot.rule.clear_milli
|
|
393
|
+
} else {
|
|
394
|
+
slot.rule.fire_milli
|
|
395
|
+
};
|
|
396
|
+
if objective.burns_at_least(long, bar) && objective.burns_at_least(short, bar) {
|
|
397
|
+
State::Firing
|
|
398
|
+
} else {
|
|
399
|
+
State::Quiet
|
|
400
|
+
}
|
|
401
|
+
} else {
|
|
402
|
+
match policy {
|
|
403
|
+
OnNoData::Hold => slot.state,
|
|
404
|
+
OnNoData::Reset => State::NoData,
|
|
405
|
+
OnNoData::Fire => State::Firing,
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
if state != slot.state {
|
|
409
|
+
slot.state = state;
|
|
410
|
+
slot.since = Some(now);
|
|
411
|
+
}
|
|
412
|
+
let change = match (was_firing, state == State::Firing) {
|
|
413
|
+
(false, true) => Change::Raised,
|
|
414
|
+
(true, false) => Change::Cleared,
|
|
415
|
+
(false, false) | (true, true) => Change::None,
|
|
416
|
+
};
|
|
417
|
+
Decision {
|
|
418
|
+
state,
|
|
419
|
+
change,
|
|
420
|
+
long_milli: long.and_then(|counts| objective.burn_milli(counts)),
|
|
421
|
+
short_milli: short.and_then(|counts| objective.burn_milli(counts)),
|
|
422
|
+
since: slot.since,
|
|
423
|
+
}
|
|
424
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "budget_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
|
+
budget-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('budget_machines_native/budget_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,50 @@
|
|
|
1
|
+
//! The `Data` classes, resolved once at load and pinned.
|
|
2
|
+
//!
|
|
3
|
+
//! A value read back must be an instance of exactly the gem's class
|
|
4
|
+
//! (`matryona_machines::ruby::exact_struct`): a subclass constant leaks past
|
|
5
|
+
//! the seal and `Data#initialize` can be bound directly, so `is_a?` is not
|
|
6
|
+
//! enough. Its fields are read straight from the struct (no reader runs) and
|
|
7
|
+
//! rebuilt through the core constructor, which `Marshal.load` skipped.
|
|
8
|
+
use magnus::{Error, RModule, Ruby, prelude::*};
|
|
9
|
+
use matryona_machines::ruby::Class;
|
|
10
|
+
|
|
11
|
+
/// Every `Data` class the binding checks or builds.
|
|
12
|
+
pub struct Classes {
|
|
13
|
+
pub counts: Class,
|
|
14
|
+
pub objective: Class,
|
|
15
|
+
pub within: Class,
|
|
16
|
+
pub exhausted: Class,
|
|
17
|
+
pub account: Class,
|
|
18
|
+
pub sample: Class,
|
|
19
|
+
pub windows: Class,
|
|
20
|
+
pub rule: Class,
|
|
21
|
+
pub decision: Class,
|
|
22
|
+
pub verdict: Class,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
matryona_machines::registry! {
|
|
26
|
+
static CLASSES: Classes = "budget_machines";
|
|
27
|
+
/// The classes resolved at load.
|
|
28
|
+
pub fn classes;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// Resolve the classes `budget_machines.rb` defined before requiring the
|
|
32
|
+
/// extension.
|
|
33
|
+
pub fn resolve(ruby: &Ruby, module: RModule) -> Result<(), Error> {
|
|
34
|
+
let standing: RModule = module.const_get("Standing")?;
|
|
35
|
+
let sample: RModule = module.const_get("Sample")?;
|
|
36
|
+
let class = |scope, name| Class::resolve(ruby, scope, name);
|
|
37
|
+
let classes = Classes {
|
|
38
|
+
counts: class(module, "Counts")?,
|
|
39
|
+
objective: class(module, "Objective")?,
|
|
40
|
+
within: class(standing, "Within")?,
|
|
41
|
+
exhausted: class(standing, "Exhausted")?,
|
|
42
|
+
account: class(module, "Account")?,
|
|
43
|
+
sample: class(sample, "Counts")?,
|
|
44
|
+
windows: class(module, "Windows")?,
|
|
45
|
+
rule: class(module, "Rule")?,
|
|
46
|
+
decision: class(module, "Decision")?,
|
|
47
|
+
verdict: class(module, "Verdict")?,
|
|
48
|
+
};
|
|
49
|
+
CLASSES.set(ruby, classes).map(drop)
|
|
50
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
//! Private native entry point.
|
|
2
|
+
use crate::{
|
|
3
|
+
CAPACITY, allowance, burn_milli, burn_milli_of, burns_at_least, classes, ledger::Ledger,
|
|
4
|
+
monitor::Monitor, values,
|
|
5
|
+
};
|
|
6
|
+
use magnus::{Error, Ruby, function, method, prelude::*};
|
|
7
|
+
use matryona_machines::ruby::Class;
|
|
8
|
+
|
|
9
|
+
#[magnus::init]
|
|
10
|
+
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
11
|
+
let module = ruby.define_module("BudgetMachines")?;
|
|
12
|
+
module.const_set("CAPACITY", CAPACITY)?;
|
|
13
|
+
module.const_set("MILLI", budget_machines::MILLI)?;
|
|
14
|
+
module.define_singleton_method("__allowance", function!(allowance, 2))?;
|
|
15
|
+
module.define_singleton_method("__burn_milli_of", function!(burn_milli_of, 3))?;
|
|
16
|
+
module.define_singleton_method("__burn_milli", function!(burn_milli, 2))?;
|
|
17
|
+
module.define_singleton_method("__burns_at_least", function!(burns_at_least, 3))?;
|
|
18
|
+
values::define(ruby)?;
|
|
19
|
+
classes::resolve(ruby, module)?;
|
|
20
|
+
|
|
21
|
+
let class = module.define_class("Ledger", ruby.class_object())?;
|
|
22
|
+
class.undef_default_alloc_func();
|
|
23
|
+
class.define_singleton_method("new", function!(Ledger::new, 2))?;
|
|
24
|
+
class.define_method("period", method!(Ledger::period, 0))?;
|
|
25
|
+
class.define_method("objective", method!(Ledger::objective, 0))?;
|
|
26
|
+
class.define_method("counts", method!(Ledger::counts, 0))?;
|
|
27
|
+
class.define_method("record", method!(Ledger::record, 2))?;
|
|
28
|
+
class.define_method("replace", method!(Ledger::replace, 2))?;
|
|
29
|
+
class.define_method("roll", method!(Ledger::roll, 1))?;
|
|
30
|
+
class.define_method("account", method!(Ledger::account, 0))?;
|
|
31
|
+
class.define_method("account_against", method!(Ledger::account_against, 1))?;
|
|
32
|
+
// `new` answers a Ledger: fix its class now, so building one runs no Ruby.
|
|
33
|
+
Class::pin_wrapped::<Ledger>(ruby, class)?;
|
|
34
|
+
|
|
35
|
+
let class = module.define_class("Monitor", ruby.class_object())?;
|
|
36
|
+
class.undef_default_alloc_func();
|
|
37
|
+
class.define_singleton_method("new", function!(Monitor::new, 3))?;
|
|
38
|
+
class.define_method("add_rule", method!(Monitor::add_rule, 1))?;
|
|
39
|
+
class.define_method("objective", method!(Monitor::objective, 0))?;
|
|
40
|
+
class.define_method("rule", method!(Monitor::rule, 1))?;
|
|
41
|
+
class.define_method("state", method!(Monitor::state, 1))?;
|
|
42
|
+
class.define_method("empty?", method!(Monitor::is_empty, 0))?;
|
|
43
|
+
class.define_method("evaluate", method!(Monitor::evaluate, 2))?;
|
|
44
|
+
class.define_method("worst", method!(Monitor::worst, 0))?;
|
|
45
|
+
class.define_method("last", method!(Monitor::last, 0))?;
|
|
46
|
+
class.define_method("size", method!(Monitor::size, 0))?;
|
|
47
|
+
class.define_method("capacity", function!(Monitor::capacity, 0))?;
|
|
48
|
+
// Likewise for Monitor.
|
|
49
|
+
Class::pin_wrapped::<Monitor>(ruby, class).map(drop)
|
|
50
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
//! `BudgetMachines::Ledger`.
|
|
2
|
+
use std::cell::RefCell;
|
|
3
|
+
|
|
4
|
+
use budget_machines::{Account, Standing};
|
|
5
|
+
use magnus::{Error, Ruby, Value, prelude::*, typed_data::Obj};
|
|
6
|
+
use matryona_machines::ruby::{SymbolNames, integer, keep};
|
|
7
|
+
|
|
8
|
+
use crate::classes::classes;
|
|
9
|
+
use crate::values::Standings;
|
|
10
|
+
use crate::{counts, counts_value, done, objective, objective_value, refusal};
|
|
11
|
+
|
|
12
|
+
#[magnus::wrap(class = "BudgetMachines::Ledger", free_immediately, size)]
|
|
13
|
+
pub struct Ledger {
|
|
14
|
+
core: RefCell<budget_machines::Ledger>,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/// A `BudgetMachines::Account` built from a core account, through `new`.
|
|
18
|
+
fn account(ruby: &Ruby, account: Account) -> Result<Value, Error> {
|
|
19
|
+
let classes = classes(ruby)?;
|
|
20
|
+
let standing = match account.standing() {
|
|
21
|
+
Standing::NoData => Standings::symbol(ruby, &Standing::NoData).as_value(),
|
|
22
|
+
Standing::Within { remaining } => classes.within.get(ruby).funcall("new", (remaining,))?,
|
|
23
|
+
Standing::Exhausted { overspent } => {
|
|
24
|
+
classes.exhausted.get(ruby).funcall("new", (overspent,))?
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
classes.account.get(ruby).funcall(
|
|
28
|
+
"new",
|
|
29
|
+
(
|
|
30
|
+
account.period(),
|
|
31
|
+
counts_value(ruby, account.counts())?,
|
|
32
|
+
account.base(),
|
|
33
|
+
account.allowance(),
|
|
34
|
+
standing,
|
|
35
|
+
account.consumed_milli(),
|
|
36
|
+
),
|
|
37
|
+
)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
impl Ledger {
|
|
41
|
+
pub fn new(ruby: &Ruby, target: Value, period: Value) -> Result<Self, Error> {
|
|
42
|
+
let period = integer(period, "period")?;
|
|
43
|
+
let core = budget_machines::Ledger::new(objective(ruby, target)?, period);
|
|
44
|
+
Ok(Self {
|
|
45
|
+
core: RefCell::new(core),
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
pub fn period(&self) -> u64 {
|
|
50
|
+
self.core.borrow().period()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
pub fn objective(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
|
|
54
|
+
let held = this.core.borrow().objective();
|
|
55
|
+
objective_value(ruby, held)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
pub fn counts(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
|
|
59
|
+
let held = this.core.borrow().counts();
|
|
60
|
+
counts_value(ruby, held)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
pub fn record(
|
|
64
|
+
ruby: &Ruby,
|
|
65
|
+
this: Obj<Self>,
|
|
66
|
+
period: Value,
|
|
67
|
+
window: Value,
|
|
68
|
+
) -> Result<Value, Error> {
|
|
69
|
+
this.check_frozen()?;
|
|
70
|
+
let period = integer(period, "period")?;
|
|
71
|
+
let counts = counts(ruby, window)?;
|
|
72
|
+
let outcome = this.core.borrow_mut().record(period, counts);
|
|
73
|
+
Ok(done(ruby, outcome))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
pub fn replace(
|
|
77
|
+
ruby: &Ruby,
|
|
78
|
+
this: Obj<Self>,
|
|
79
|
+
period: Value,
|
|
80
|
+
reading: Value,
|
|
81
|
+
) -> Result<Value, Error> {
|
|
82
|
+
this.check_frozen()?;
|
|
83
|
+
let period = integer(period, "period")?;
|
|
84
|
+
let counts = counts(ruby, reading)?;
|
|
85
|
+
let outcome = this.core.borrow_mut().replace(period, counts);
|
|
86
|
+
Ok(done(ruby, outcome))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
pub fn roll(ruby: &Ruby, this: Obj<Self>, period: Value) -> Result<Value, Error> {
|
|
90
|
+
this.check_frozen()?;
|
|
91
|
+
let period = integer(period, "period")?;
|
|
92
|
+
keep(
|
|
93
|
+
ruby,
|
|
94
|
+
this,
|
|
95
|
+
&this.core,
|
|
96
|
+
|core| core.roll(period),
|
|
97
|
+
|outcome| match outcome {
|
|
98
|
+
Ok(closed) => account(ruby, closed),
|
|
99
|
+
Err(refused) => Ok(refusal(ruby, refused)),
|
|
100
|
+
},
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
pub fn account(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
|
|
105
|
+
let current = this.core.borrow().account();
|
|
106
|
+
account(ruby, current)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
pub fn account_against(ruby: &Ruby, this: &Self, planned: Value) -> Result<Value, Error> {
|
|
110
|
+
let planned = integer(planned, "planned")?;
|
|
111
|
+
let outcome = this.core.borrow().account_against(planned);
|
|
112
|
+
match outcome {
|
|
113
|
+
Ok(planned) => account(ruby, planned),
|
|
114
|
+
Err(refused) => Ok(refusal(ruby, refused)),
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|