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.
@@ -0,0 +1,312 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RogueMachines
4
+ # Longest an experiment may run for, in nanoseconds. An experiment is
5
+ # something a person is waiting on, so a day is already generous; past that
6
+ # it is configuration, and it must be re-armed deliberately.
7
+ LONGEST_EXPERIMENT = 24 * 60 * 60 * 1_000_000_000
8
+
9
+ # Longest a single delay may wait, in nanoseconds. Bounds how long a stall
10
+ # can hold a caller that has no deadline of its own.
11
+ LONGEST_DELAY = 5 * 60 * 1_000_000_000
12
+
13
+ # Attempts at a reading taken against the clock still installed once the
14
+ # lock is held, before giving up on a clock replaced faster than that.
15
+ READINGS = 100
16
+
17
+ # The process-wide runtime: one Rogue, the names standing for its slots, and
18
+ # the substitutes the :garble experiments return. Every store is touched only
19
+ # under @lock; `run` reads the Rogue's gate outside it.
20
+ #
21
+ # Invariant: every Slot in @slots holds an experiment in @rogue (expired or
22
+ # not), and @substitutes has keys only from @slots.
23
+ @rogue = Rogue.new
24
+ @slots = {}
25
+ @substitutes = {}
26
+ @lock = Mutex.new
27
+
28
+ class << self
29
+ attr_writer :random
30
+
31
+ # Monotonic Integer nanoseconds. Delegates to deadline_machines rather
32
+ # than memoising it, so replacing that gem's clock moves every expiry
33
+ # with it.
34
+ def clock
35
+ @clock || DeadlineMachines.clock
36
+ end
37
+
38
+ # Installing a clock disarms everything first: every armed expiry was
39
+ # computed against the outgoing clock, and is not an expiry against
40
+ # another one. A reading already taken against the outgoing clock is not
41
+ # acted on: every call that uses a reading checks, under the lock, that
42
+ # the clock it read is still the one installed.
43
+ def clock=(clock)
44
+ @lock.synchronize do
45
+ Thread.handle_interrupt(Object => :never) do
46
+ @clock = clock
47
+ @rogue.disarm_all
48
+ @slots = {}
49
+ @substitutes = {}
50
+ end
51
+ end
52
+ end
53
+
54
+ def random
55
+ @random ||= Random.new
56
+ end
57
+
58
+ # A frozen copy of the runtime's Rogue, taken under the lock, for
59
+ # reading. Not the Rogue itself: disarming that behind the names would
60
+ # leave a name on an empty slot, which the next arm hands to a second
61
+ # name.
62
+ def rogue
63
+ @lock.synchronize { @rogue.dup.freeze }
64
+ end
65
+
66
+ # Arms an experiment under `name`, replacing any already there.
67
+ #
68
+ # RogueMachines.arm(:payments, fault: :raise, share: 0.01, expires_in: 300 * 10**9)
69
+ # RogueMachines.arm(:slow, fault: RogueMachines::Delay.new(2 * 10**9), share: 1, expires_in: 60 * 10**9)
70
+ # RogueMachines.arm(:lies, fault: :garble, garbled: [], share: 0.5, expires_in: 60 * 10**9)
71
+ #
72
+ # `expires_in` is Integer nanoseconds from now and required, so no
73
+ # experiment outlives the person who armed it. Answers what the core's
74
+ # `arm` answered for the slot (:armed, a Replaced, :already_armed), or
75
+ # :full, with nothing changed, when every slot holds a live experiment.
76
+ def arm(name, fault:, share:, expires_in:, garbled: nil)
77
+ key = named(name)
78
+ fraction = fraction_of(share)
79
+ checked_fault(fault)
80
+ span = span_of(expires_in)
81
+ payload = fault == :garble ? garbled : nil
82
+ found = locked_reading { |now| arm_at(key, Experiment.new(fault, fraction, now + span), payload, now) }
83
+ raise Error, "the clock was replaced #{READINGS} times while arming; nothing is armed" unless found
84
+
85
+ found.first
86
+ end
87
+
88
+ # What `name`'s slot held (a Disarmed, expired or not, carrying the
89
+ # substitute it removed), or :not_armed. Takes no reading.
90
+ def disarm(name)
91
+ key = named(name)
92
+ @lock.synchronize do
93
+ Thread.handle_interrupt(Object => :never) do
94
+ slot = @slots.delete(key)
95
+ next :not_armed unless slot
96
+
97
+ removed = @substitutes.delete(key)
98
+ disarmed(@rogue.disarm(slot), removed)
99
+ end
100
+ end
101
+ end
102
+
103
+ # How many experiments were held, expired or not.
104
+ def disarm_all
105
+ @lock.synchronize do
106
+ Thread.handle_interrupt(Object => :never) do
107
+ @slots = {}
108
+ @substitutes = {}
109
+ @rogue.disarm_all
110
+ end
111
+ end
112
+ end
113
+
114
+ # With no name, whether anything at all is live now.
115
+ def armed?(name = nil)
116
+ key = name.nil? ? nil : named(name).to_sym
117
+ names = armed
118
+ key.nil? ? names.any? : names.include?(key)
119
+ end
120
+
121
+ # The experiments live now. Retires the expired ones first, which
122
+ # releases their slots and substitutes; once retired, a clock stepping
123
+ # back cannot revive them.
124
+ def armed
125
+ found = locked_reading do |now|
126
+ retire(now)
127
+ @slots.keys.map(&:to_sym)
128
+ end
129
+ found ? found.first : []
130
+ end
131
+
132
+ # Runs the block, or the fault armed under `name` instead. Makes the real
133
+ # call when the clock was replaced faster than a reading could be taken.
134
+ def run(name)
135
+ legible(name)
136
+ return yield unless @rogue.any_armed?
137
+
138
+ key = named(name)
139
+ drawn = Draw.new(random.rand(PER_MILLION))
140
+ found = locked_reading { |now| decide_at(key, now, drawn) }
141
+ return yield unless found
142
+
143
+ decision, payload = found.first
144
+ return yield if decision == :pass
145
+
146
+ perform(name, decision.fault, payload) { yield }
147
+ end
148
+
149
+ private
150
+
151
+ # Arms under the lock. The room check changes nothing, so :full leaves
152
+ # every store as it was; only then are expired experiments retired.
153
+ #
154
+ # The substitute is part of what is armed: the core's :already_armed
155
+ # stands only when the stored one is equal too. A differing one is a
156
+ # replacement, answered as the core answers a differing experiment. Every
157
+ # Replaced carries the substitute it displaced.
158
+ def arm_at(key, experiment, payload, now)
159
+ return :full unless @slots.key?(key) || @rogue.vacant || @rogue.live_count(now) < @rogue.armed_count
160
+
161
+ Thread.handle_interrupt(Object => :never) do
162
+ retire(now)
163
+ slot = @slots[key] || @rogue.vacant
164
+ # Everything that runs caller code (the substitute's `==`, the answer
165
+ # values' `new`) runs before a store changes; the Rogue's own `arm`
166
+ # applies nothing when it raises.
167
+ previous = @substitutes[key]
168
+ same_payload = previous == payload
169
+ answer = @rogue.arm(slot, experiment)
170
+ @slots[key] = slot
171
+ payload.nil? ? @substitutes.delete(key) : @substitutes[key] = payload
172
+ replaced(answer, experiment, previous, same_payload)
173
+ end
174
+ end
175
+
176
+ # The runtime's answer for the core's disarming `answer`: a Disarmed
177
+ # holding the substitute it removed.
178
+ def disarmed(answer, removed)
179
+ case answer
180
+ when Disarmed then Disarmed.new(answer.experiment, removed)
181
+ else answer
182
+ end
183
+ end
184
+
185
+ # The runtime's answer for the core's `answer`: a Replaced holding the
186
+ # substitute it displaced, and :already_armed only for an equal one.
187
+ def replaced(answer, experiment, previous, same_payload)
188
+ case answer
189
+ when Replaced then Replaced.new(answer.experiment, previous)
190
+ when :already_armed then same_payload ? answer : Replaced.new(experiment, previous)
191
+ else answer
192
+ end
193
+ end
194
+
195
+ # The decision and the payload, read together under the lock. Retires
196
+ # anything expired first, which restores the disarmed fast path.
197
+ def decide_at(key, now, drawn)
198
+ retire(now) if @rogue.live_count(now) < @rogue.armed_count
199
+ slot = @slots[key]
200
+ decision = slot ? @rogue.decide(slot, now, drawn) : :pass
201
+ [decision, decision == :pass ? nil : @substitutes[key]]
202
+ end
203
+
204
+ # Empties the slots of experiments expired by `now` and drops their names
205
+ # and substitutes. Called only under the lock with a reading against the
206
+ # installed clock.
207
+ def retire(now)
208
+ Thread.handle_interrupt(Object => :never) do
209
+ next if @rogue.sweep(now).zero?
210
+
211
+ @slots.select! { |_, slot| @rogue.experiment(slot) }
212
+ @substitutes.select! { |key, _| @slots.key?(key) }
213
+ end
214
+ end
215
+
216
+ # `[block's answer]` for a reading taken outside the lock against the
217
+ # clock still installed once it is held, or nil after READINGS attempts.
218
+ # The caller's clock never runs inside the lock.
219
+ def locked_reading
220
+ READINGS.times do
221
+ source = clock
222
+ now = source.now_ns
223
+ checked_reading(source, now)
224
+ found = @lock.synchronize { [yield(now)] if clock.equal?(source) }
225
+ return found if found
226
+ end
227
+ nil
228
+ end
229
+
230
+ def checked_reading(source, now)
231
+ unless now.is_a?(Integer)
232
+ raise TypeError, "#{source.class} returned #{now.inspect}; a reading is an Integer of nanoseconds"
233
+ end
234
+ raise RangeError, "#{source.class} returned #{now}; a reading is not negative" if now.negative?
235
+ end
236
+
237
+ # Rejects a name the runtime cannot key on, without converting it, so a
238
+ # call site answers the same way whether or not anything is armed and the
239
+ # disarmed `run` allocates nothing.
240
+ def legible(name)
241
+ text = case name
242
+ when Symbol then name.name
243
+ when String then name
244
+ else raise TypeError, "an experiment name is a Symbol or a String, got #{name.class}"
245
+ end
246
+ raise RangeError, 'an experiment needs a name' if text.empty?
247
+ return if text.ascii_only? || (text.encoding == Encoding::UTF_8 && text.valid_encoding?)
248
+
249
+ raise RangeError, 'an experiment name is ASCII or valid UTF-8'
250
+ end
251
+
252
+ # The checked name as a frozen String key. Not `to_s`: a String subclass
253
+ # can override it, which armed one name and reported another.
254
+ def named(name)
255
+ legible(name)
256
+ name.is_a?(Symbol) ? name.name : -String.new(name)
257
+ end
258
+
259
+ # A Fraction as given, or a Numeric share of a whole rounded to
260
+ # millionths. A share too small to express is refused rather than armed
261
+ # as nothing.
262
+ def fraction_of(share)
263
+ return share if share.is_a?(Fraction)
264
+ unless share.is_a?(Numeric) && share.real?
265
+ raise TypeError, "share is a Fraction or a real Numeric, got #{share.class}"
266
+ end
267
+
268
+ raise RangeError, "share is between 0 and 1, got #{share}" unless share.finite? && share.between?(0, 1)
269
+
270
+ millionths = (share * PER_MILLION).round
271
+ raise RangeError, "share of #{share} is below one millionth" if millionths.zero? && share.positive?
272
+
273
+ Fraction.new(millionths)
274
+ end
275
+
276
+ # The fault is read natively, as Experiment.new reads it, never through
277
+ # `Delay#duration` or `===`; only LONGEST_DELAY, this runtime's own bound,
278
+ # is checked here, on the duration that was read.
279
+ def checked_fault(fault)
280
+ delay = RogueMachines.__send__(:__delay_of, fault)
281
+ return if delay.nil? || delay.between?(1, LONGEST_DELAY)
282
+
283
+ raise RangeError, "a delay is 1..#{LONGEST_DELAY} nanoseconds, got #{delay}"
284
+ end
285
+
286
+ def span_of(expires_in)
287
+ raise TypeError, 'expires_in is an Integer of nanoseconds' unless expires_in.is_a?(Integer)
288
+ return expires_in if expires_in.between?(1, LONGEST_EXPERIMENT)
289
+
290
+ raise RangeError, "expires_in is 1..#{LONGEST_EXPERIMENT} nanoseconds, got #{expires_in}"
291
+ end
292
+
293
+ def perform(name, fault, payload)
294
+ case fault
295
+ when :raise then raise Injected, "#{name} is armed to raise"
296
+ when :garble then payload
297
+ when Delay
298
+ stall(fault.duration)
299
+ yield
300
+ end
301
+ end
302
+
303
+ # Spends the delay against the caller's deadline rather than past it, so a
304
+ # slow dependency trips the timeout that was already there.
305
+ def stall(delay_ns)
306
+ DeadlineMachines.check!
307
+ delay_ns = DeadlineMachines.clamp_sleep(delay_ns)
308
+ sleep(delay_ns.fdiv(1_000_000_000)) if delay_ns.positive?
309
+ DeadlineMachines.check!
310
+ end
311
+ end
312
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RogueMachines
4
- VERSION = '0.1.2'
4
+ VERSION = '0.5.0'
5
5
  end