standard_circuit 0.6.0 → 0.7.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 195e01d912e93d7bf158cafd091aab7ab27571994e9d4c2953d0a39b76c92d71
4
- data.tar.gz: 880f2b881ada6a92660c8c26c1c2b49abf2ea283411606a7131c9cf1af8bd75f
3
+ metadata.gz: 270a3311b53ff73741fc72db366bd4d383a2eb359247808abf909b7c2c627d0c
4
+ data.tar.gz: 4bead010e042e4afb7a986e9a315061dceb4cfd689b30abf941d5c84615a6c33
5
5
  SHA512:
6
- metadata.gz: 4706259801d563a2b60183691ad7c4ae935face858318e358d4e3bd5459c4b2eee097da52c8cb4748c7726883455f96a1416a23cde8b0123d172207d2f64b373
7
- data.tar.gz: 05f1578d83f4bdbc34d310350570322bf4cd357d24d50e07874bed2e34019d33bb3cf0f396e49cf9a598797700aef34d3182b98c730d4a25e737f3f083ad6e80
6
+ metadata.gz: 5542bc0284e2c7e873ddb6f919a5008c7988be91c5eb3bdc8b73d713e31669e7c2cd50a55dd21f2350bb955888e45af87dfc771385412b4a8c0f14bbfebfd642
7
+ data.tar.gz: 28dfe0ac926df96d4cb6d961d97aeca58f55b20c19339a4ce8dcc625456814a5cda0bce30a59f0dcdddfab23c539a2e9425d550bdf375447c47bc43a3b2d4bba
data/CHANGELOG.md CHANGED
@@ -7,6 +7,87 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.7.0] - 2026-11-23
11
+
12
+ First step from circuit breakers towards dependency management: a registry of
13
+ the external services an app depends on, the purposes it calls them for, and
14
+ each one's state and recent call stats. Additive: an app that upgrades and
15
+ changes nothing sees no difference beyond the stoplight 6 notes below.
16
+
17
+ ### Added
18
+
19
+ - **Dependencies and purposes.** `c.dependency :name, criticality:, <breaker options> { |d| d.purpose ... }`
20
+ declares an external service and the reasons the app calls it. Each purpose
21
+ has its own criticality. Purposes share the dependency's breaker unless
22
+ declared `isolate: true`, which gives them a breaker named
23
+ `<dependency>_<purpose>`. `StandardCircuit.run(name, purpose:)` targets one.
24
+ An undeclared purpose raises `UnknownPurpose`. A bare `run` on a dependency
25
+ with several purposes raises `PurposeRequired` unless one is marked
26
+ `default: true`. See the README's "Dependencies and purposes".
27
+ - `StandardCircuit.dependency(name)` and `StandardCircuit.dependencies` return
28
+ read-only handles (name, criticality, purposes, circuit names). An unknown
29
+ name raises `UnknownDependency`, a subclass of `UnknownCircuit`.
30
+ - **State and locks on dependencies.** `dependency(name).open?`, `.status`
31
+ (`:ok | :degraded | :unavailable`, the worst purpose under the
32
+ `health_report` rule), `.circuits`, and `.lock_open!` / `.lock_closed!` /
33
+ `.unlock!`, plus the same per purpose (`dependency(name).purpose(p).open?`).
34
+ `lock_open!` is the supported replacement for
35
+ `runner.light_for(name).lock(Stoplight::Color::RED)`. Forced states count.
36
+ State is per process with the default `Memory` store.
37
+ - **Rolling stats.** A built-in subscriber on `standard_circuit.run.completed`
38
+ keeps a bounded, thread-safe, in-process window of the last
39
+ `config.stats_window_size` calls (default 100) per dependency and per
40
+ purpose. Read it with `dependency(name).stats` / `.purpose(p).stats`: counts
41
+ by status, error rate and p50/p95 latency over attempted calls,
42
+ `last_success_at`, `last_failure_at`, consecutive failures, and calls in
43
+ the window. No calls reads as `calls: 0` with nil rates, never as healthy.
44
+ `reset!` clears it.
45
+ - **`metrics_only: true`** on a dependency, an isolated purpose, or a
46
+ `register` call times and records calls but never blocks one. It doesn't
47
+ trip, and it ignores forced states and locks. `open?` is always false.
48
+ - **`StandardCircuit.dependency_report`**: one row per dependency with status,
49
+ criticality, purposes (criticality, status, stats) and circuits (color,
50
+ locked, forced). `health_report` is unchanged.
51
+ - `register`, `register_prefix` and `register_preset` also create a breaker-only
52
+ dependency with one implicit `:default` purpose, so circuits registered the
53
+ old way show up through the new API. A prefix registration is one dependency
54
+ whose circuits are its sub-circuits. Their behaviour, `health_report` and
55
+ events are otherwise unchanged.
56
+ - `standard_circuit.run.completed` gains `dependency:` and `purpose:` keys.
57
+ Its `criticality` (and `fallback_invoked`'s) is the purpose's, which for a
58
+ `register`ed circuit is the circuit's own, as before.
59
+
60
+ ### Changed
61
+
62
+ - **Requires stoplight 6** (`~> 6.0`, `>= 6.0.1`, was `~> 5.8`). StandardCircuit's
63
+ own API, events and payloads, `health_report` and test helpers are unchanged:
64
+ colors in `health_report` and event payloads stay Strings, `circuit.opened`
65
+ still carries the error only for a GREEN→RED trip, `reset!` still gives fresh
66
+ counters, `configure` can still be re-run with changed settings, and the
67
+ per-process `Memory` store is still the default. Circuits now live in a
68
+ dedicated Stoplight system named `standard_circuit`, separate from the
69
+ process-global one a host sets up with `Stoplight.configure`.
70
+
71
+ ### Upgrade notes
72
+
73
+ What a host can still notice, all from stoplight 6 itself:
74
+
75
+ - `Stoplight::Error::RedLight#message` is now a sentence
76
+ (``Light `stripe` is red - traffic stopped until recovery.``) instead of the
77
+ bare circuit name. That text is also the `error_message` of a
78
+ `run.completed` event with `status: :circuit_open`. Use `#light_name` if you
79
+ need the circuit name.
80
+ - `StandardCircuit.runner.light_for(name)` returns a stoplight 6 light, whose
81
+ `#color` and `#state` are Symbols (`:red`) and whose `#lock` takes only the
82
+ `Stoplight::Color` constants. `lock(Stoplight::Color::RED)` works as before;
83
+ `lock("red")` raises.
84
+ - A fractional `cool_off_time` or `window_size` is rounded up to whole seconds,
85
+ and a `cool_off_time` below 1 becomes 1, because stoplight 6 rejects anything
86
+ else. The registered `CircuitSpec` keeps the value you passed.
87
+ - With `Stoplight::DataStore::Redis`, stoplight 6 needs Redis 7.4+ (or Valkey
88
+ 7.2+), uses a new key schema (every circuit starts green after the deploy),
89
+ and no longer accepts `warn_on_clock_skew:`.
90
+
10
91
  ## [0.6.0] - 2026-10-22
11
92
 
12
93
  ### Fixed
data/README.md CHANGED
@@ -117,6 +117,181 @@ c.register_preset(:s3)
117
117
 
118
118
  There is deliberately no `:stripe` preset — the apps that wrap Stripe disagree on threshold, criticality, and skips, so `ErrorTaxonomies::Stripe.tracked` stays the shared piece.
119
119
 
120
+ ## Dependencies and purposes
121
+
122
+ A **dependency** is one external service the app calls. A **purpose** is a declared reason the app calls it, and each purpose has its own criticality. One upstream is often called for reasons of different weight: Google OAuth for sign-in (critical) and for Calendar linking (standard). Before purposes, that meant either putting the circuit's criticality on its most important use or hand-splitting circuits.
123
+
124
+ ```ruby
125
+ StandardCircuit.configure do |c|
126
+ # One reason to call it: criticality on the dependency, implicit :default purpose.
127
+ c.dependency :stripe, criticality: :critical, threshold: 5, cool_off_time: 30,
128
+ tracked_errors: StandardCircuit::ErrorTaxonomies::Stripe.tracked,
129
+ skipped_errors: StandardCircuit::AdapterErrors::Stripe.caller_errors
130
+
131
+ # One upstream, several reasons. The purposes share one breaker.
132
+ c.dependency :google_oauth, threshold: 3, cool_off_time: 30 do |d|
133
+ d.purpose :sign_in, criticality: :critical
134
+ d.purpose :calendar, criticality: :standard
135
+ end
136
+
137
+ # A purpose whose failures look different gets its own breaker.
138
+ c.dependency :google_maps, criticality: :optional do |d|
139
+ d.purpose :places, default: true
140
+ d.purpose :address, isolate: true, threshold: 2 # breaker :google_maps_address
141
+ end
142
+ end
143
+
144
+ StandardCircuit.run(:google_oauth, purpose: :calendar) { calendar.list_events }
145
+ StandardCircuit.run(:google_maps) { places.search(query) } # the default purpose, :places
146
+ ```
147
+
148
+ The rules:
149
+
150
+ - **Breaker options** are the ones `register` takes (`threshold`, `cool_off_time`, `window_size`, `tracked_errors`, `skipped_errors`), passed flat. `criticality:` on the dependency is the default for each purpose.
151
+ - **Purposes share the dependency's breaker** by default, because the same upstream's failures are correlated. The shared breaker is named after the dependency and takes the worst criticality among its purposes, which is what `health_report` and the transition events use.
152
+ - **`isolate: true`** gives a purpose its own breaker, named `<dependency>_<purpose>`, with the dependency's breaker options plus any passed on the purpose. Breaker options on a purpose that isn't isolated raise `ArgumentError`, because a shared breaker has one set of settings.
153
+ - **Purposes are a closed set.** `run` with an undeclared purpose raises `StandardCircuit::UnknownPurpose`. `run` without `purpose:` uses the implicit purpose, or the one declared `default: true`; with neither, it raises `StandardCircuit::PurposeRequired`. Raising beats guessing which purpose a bare call meant, and `default: true` keeps existing bare `run(:name)` call sites working when you add purposes.
154
+ - **`register`, `register_prefix` and `register_preset` still work unchanged**, and each now also creates a breaker-only dependency with one implicit `:default` purpose. `StandardCircuit.dependency(:stripe)` finds a circuit registered the old way, and a prefix registration is one dependency whose circuits (`s3_uploads`, `s3_avatars`, ...) are its sub-circuits.
155
+ - An isolated purpose's breaker can be run by its own name (`run(:google_maps_address)`), so a hand-split circuit's call sites keep working after you fold it into a purpose. Re-declaring a dependency replaces it; a breaker name another dependency already owns raises `ArgumentError`.
156
+
157
+ Per-call events (`run.completed`, `fallback_invoked`) carry the **purpose's** criticality, plus `dependency:` and `purpose:` on `run.completed`. For a circuit registered with `register`, that criticality is the circuit's own, exactly as before.
158
+
159
+ ```ruby
160
+ dep = StandardCircuit.dependency(:google_maps) # raises StandardCircuit::UnknownDependency (an UnknownCircuit)
161
+ dep.criticality # => :optional (worst purpose)
162
+ dep.purposes.map(&:name) # => [:places, :address]
163
+ dep.purpose(:address).circuit_name # => :google_maps_address
164
+ dep.circuit_names # => [:google_maps, :google_maps_address]
165
+ StandardCircuit.dependencies # every dependency, old-style registrations included
166
+ ```
167
+
168
+ Replace your host code with:
169
+
170
+ ```ruby
171
+ # Before: criticality pinned to the most important use
172
+ c.register(:google_oauth, threshold: 3, criticality: :critical) # "because sign-in depends on it"
173
+ StandardCircuit.run(:google_oauth) { calendar.link! }
174
+
175
+ # After
176
+ c.dependency :google_oauth, threshold: 3 do |d|
177
+ d.purpose :sign_in, criticality: :critical
178
+ d.purpose :calendar, criticality: :standard
179
+ end
180
+ StandardCircuit.run(:google_oauth, purpose: :calendar) { calendar.link! }
181
+ ```
182
+
183
+ ```ruby
184
+ # Before: a second circuit only because one use fails differently
185
+ c.register(:google_maps, criticality: :optional)
186
+ c.register(:google_maps_address, threshold: 2, criticality: :optional)
187
+
188
+ # After: same breaker names, so metrics, health entries and call sites carry over
189
+ c.dependency :google_maps, criticality: :optional do |d|
190
+ d.purpose :places, default: true
191
+ d.purpose :address, isolate: true, threshold: 2
192
+ end
193
+ ```
194
+
195
+ ### State and locks
196
+
197
+ ```ruby
198
+ dep = StandardCircuit.dependency(:myinfo)
199
+ dep.open? # true while its breaker is open (red, or force_open); half-open (yellow) is not open
200
+ dep.status # :ok | :degraded | :unavailable
201
+ dep.circuits # [{ name: :myinfo, color: "red", locked: false, forced: nil }]
202
+ dep.lock_open! # every call raises RedLight (or returns its fallback) until unlock!
203
+ dep.lock_closed! # every call goes through, failures never trip it
204
+ dep.unlock!
205
+
206
+ dep = StandardCircuit.dependency(:google_maps)
207
+ dep.purpose(:address).open? # an isolated purpose has its own breaker
208
+ dep.purpose(:address).status
209
+ dep.purpose(:address).lock_open! # locks only :google_maps_address
210
+ ```
211
+
212
+ - `status` takes the worst purpose. Each purpose applies the `health_report` rule to its own criticality and breaker color: critical + red is `:unavailable`; critical + yellow or standard + red is `:degraded`; optional never elevates. A red shared breaker therefore makes `:google_oauth` unavailable through `:sign_in`, even though `:calendar` alone would only be degraded. Error rate and latency don't affect `status`.
213
+ - A dependency is `open?` when no purpose can be served, meaning every purpose's breaker is open. For the usual one-breaker dependency that is simply "its breaker is open". `force_open` / `force_closed` count, as they do for `run`. `circuits` shows the light's own `color` and the `forced` override side by side.
214
+ - Locking through a purpose that shares the dependency's breaker locks that breaker for every purpose sharing it. A prefix dependency (`register_prefix(:s3)`) locks the `s3_*` sub-circuits used so far in the process, and is `open?` only when all of them are open.
215
+ - State is **per process** with the default `Memory` store, like everything else here (see `data_store` below). With a Redis store, locks are shared by every process, which makes `lock_open!` a fleet-wide switch.
216
+
217
+ Replace your host code with:
218
+
219
+ ```ruby
220
+ # Before: reaching into the runner
221
+ StandardCircuit.runner.light_for(:stripe).lock(Stoplight::Color::RED)
222
+ StandardCircuit.runner.light_for(:stripe).unlock
223
+ StandardCircuit.runner.light_for(:myinfo).color == Stoplight::Color::RED
224
+
225
+ # After
226
+ StandardCircuit.dependency(:stripe).lock_open!
227
+ StandardCircuit.dependency(:stripe).unlock!
228
+ StandardCircuit.dependency(:myinfo).open?
229
+ ```
230
+
231
+ ### Rolling stats
232
+
233
+ Every `run` already emits `standard_circuit.run.completed`. A built-in subscriber keeps a rolling window of those calls per dependency and per purpose:
234
+
235
+ ```ruby
236
+ StandardCircuit.dependency(:google_oauth).stats
237
+ StandardCircuit.dependency(:google_oauth).purpose(:sign_in).stats
238
+ # => {
239
+ # calls: 42, # calls in the window
240
+ # window_size: 100,
241
+ # counts: { success: 40, failure: 1, circuit_open: 1 },
242
+ # error_rate: 0.0244, # failure / (success + failure)
243
+ # latency_ms: { p50: 81.2, p95: 240.5 },
244
+ # last_success_at: 2026-11-23 12:00:03 UTC,
245
+ # last_failure_at: 2026-11-23 11:58:41 UTC,
246
+ # consecutive_failures: 0
247
+ # }
248
+ ```
249
+
250
+ - **No calls is not healthy.** A dependency or purpose with nothing recorded reports `calls: 0`, `error_rate: nil` and `latency_ms: nil`, so a critical purpose with no evidence can be told apart from one that is working.
251
+ - `error_rate` and latency count **attempted** calls only. A `circuit_open` call never reached the upstream, so it is counted but is no evidence either way. A failure that a fallback absorbed is reported by `run.completed`, and so counted here, as `:success`, as it always has been.
252
+ - The window is the last `stats_window_size` calls (default 100), kept in a fixed ring per dependency and per purpose, so memory stays bounded however much traffic flows. `last_success_at`, `last_failure_at` and `consecutive_failures` outlive the ring.
253
+ - **In-process only**: every worker has its own numbers, as with the default `Memory` store. `StandardCircuit.reset!` clears them. Recording never raises into the wrapped call.
254
+ - The subscriber is wired with the others, by the engine at boot or by `configure`. A host test suite using `require "standard_circuit/rspec"` tears subscribers down before each example, so call `StandardCircuit.subscribers.setup!` in an example that reads stats.
255
+
256
+ ```ruby
257
+ StandardCircuit.configure do |c|
258
+ c.stats_window_size = 200
259
+ end
260
+ ```
261
+
262
+ ### Observing before enforcing (`metrics_only`)
263
+
264
+ ```ruby
265
+ c.dependency :new_upstream, criticality: :standard, metrics_only: true
266
+ c.dependency :google_maps do |d|
267
+ d.purpose :places, default: true
268
+ d.purpose :address, isolate: true, metrics_only: true # only this purpose is observed
269
+ end
270
+ c.register(:legacy_api, metrics_only: true) # register takes it too
271
+ ```
272
+
273
+ A metrics-only breaker times and records every call, and `run.completed` and the request metrics flow exactly as before, but it **never blocks a call by any route**: it doesn't trip, and it ignores `force_open` / `force_closed` and locks. `open?` is always `false`, and its purpose's status is `:ok`. Towards a fallback it behaves like a closed breaker: a tracked error goes to the fallback, anything else is raised. On a purpose it needs `isolate: true`, because a shared breaker either enforces or doesn't. Use it to watch an uncovered dependency's real error rate and latency before choosing a threshold.
274
+
275
+ ### `dependency_report`
276
+
277
+ ```ruby
278
+ StandardCircuit.dependency_report
279
+ # => [
280
+ # { name: :google_oauth, status: :unavailable, criticality: :critical, open: true, metrics_only: false,
281
+ # stats: { calls: 12, ... },
282
+ # purposes: [
283
+ # { name: :sign_in, criticality: :critical, status: :unavailable, open: true, isolated: false,
284
+ # metrics_only: false, circuits: [:google_oauth], stats: { calls: 0, error_rate: nil, ... } },
285
+ # { name: :calendar, criticality: :standard, status: :degraded, open: true, isolated: false,
286
+ # metrics_only: false, circuits: [:google_oauth], stats: { calls: 12, ... } }
287
+ # ],
288
+ # circuits: [{ name: :google_oauth, color: "red", locked: false, forced: nil }] },
289
+ # ...
290
+ # ]
291
+ ```
292
+
293
+ One row per dependency, including every `register` / `register_prefix` circuit. `StandardCircuit.health_report` is unchanged and stays what `standard_health` reads; a later release will contribute `dependency_report` there.
294
+
120
295
  ## Circuit state storage (`data_store`)
121
296
 
122
297
  Circuit state (failure counts, colors, locks) lives in a Stoplight data store. StandardCircuit defaults to `Stoplight::DataStore::Memory.new`, which is **per-process**: each Puma worker, Sidekiq/SolidQueue worker, and console gets its own independent view of every circuit.
@@ -139,6 +314,8 @@ StandardCircuit.configure do |c|
139
314
  end
140
315
  ```
141
316
 
317
+ StandardCircuit keeps its circuits in its own Stoplight system, named `standard_circuit`, separate from the process-global one a host configures with `Stoplight.configure`. So `Stoplight.light("stripe")` does not find a StandardCircuit circuit, and a host's own `Stoplight.configure` does not change StandardCircuit's store or notifiers. With Redis, keys are namespaced `stoplight:v6:<standard_circuit system id>:...`; stoplight 6 needs Redis 7.4+ (or Valkey 7.2+).
318
+
142
319
  ## Sentry reporting
143
320
 
144
321
  The built-in Sentry subscriber is on by default (`c.sentry_enabled = true`) and reports every circuit-open transition at a flat `:warning`, with the circuit name, colors, and error in `extra`.
@@ -169,10 +346,10 @@ Every circuit lifecycle moment is emitted as a Rails event. On Rails 8.1+ the ca
169
346
  | `standard_circuit.circuit.closed` | GREEN transition (recovered) | `circuit:, from_color:, to_color:, criticality:` |
170
347
  | `standard_circuit.circuit.degraded` | YELLOW transition (half-open probe) | `circuit:, from_color:, to_color:, criticality:` |
171
348
  | `standard_circuit.circuit.fallback_invoked` | Runner returned a fallback instead of raising RedLight | `circuit:, reason: (:circuit_open\|:forced_open), criticality:` |
172
- | `standard_circuit.circuit.registered` | `Config#register` / `register_prefix` was called (see note below) | `circuit:, criticality:, scope: (:name\|:prefix)` |
173
- | `standard_circuit.run.completed` | Every wrapped `StandardCircuit.run` call (success, failure, or circuit_open) | `circuit:, status: (:success\|:failure\|:circuit_open), duration_ms:, criticality:, error_class:, error_message:` |
349
+ | `standard_circuit.circuit.registered` | `Config#register` / `register_prefix` was called, or once per breaker a `Config#dependency` declares (see note below) | `circuit:, criticality:, scope: (:name\|:prefix)` |
350
+ | `standard_circuit.run.completed` | Every wrapped `StandardCircuit.run` call (success, failure, or circuit_open) | `circuit:, status: (:success\|:failure\|:circuit_open), duration_ms:, criticality:, error_class:, error_message:, dependency:, purpose:` |
174
351
 
175
- > **Note on `standard_circuit.run.completed`:** the per-call event for cost / latency / success-rate dashboards. Fires on every `Runner#execute` invocation and on `force_open` runs; **not** emitted for `force_closed` runs (which intentionally bypass the runner). All payload keys are always present — `error_class` and `error_message` are `nil` on `:success`. Payload duration uses `duration_ms` (numeric), not `event.duration`, so subscribers work identically on the `Rails.event` and `ActiveSupport::Notifications` backends.
352
+ > **Note on `standard_circuit.run.completed`:** the per-call event for cost / latency / success-rate dashboards. Fires on every `Runner#execute` invocation and on `force_open` runs; **not** emitted for `force_closed` runs (which intentionally bypass the runner). All payload keys are always present — `error_class` and `error_message` are `nil` on `:success`, and `dependency` / `purpose` are `nil` only for a forced name that was never registered. `criticality` is the purpose's (see [Dependencies and purposes](#dependencies-and-purposes)). Payload duration uses `duration_ms` (numeric), not `event.duration`, so subscribers work identically on the `Rails.event` and `ActiveSupport::Notifications` backends.
176
353
 
177
354
  > **Note on `standard_circuit.circuit.registered`:** subscribers are wired up *after* the `StandardCircuit.configure` block yields, so any `c.register` calls inside that block fire before any subscriber can hear them. This event is reliable only for post-boot, dynamic `register` / `register_prefix` calls — do not rely on it for a boot-time circuit inventory.
178
355
 
@@ -354,6 +531,7 @@ These are supported public API for host test suites, not internals:
354
531
  | `StandardCircuit.force_open(name) { ... }` | Treat `name` as open for the block (or until `reset_force!` without a block): `run` raises `Stoplight::Error::RedLight`, or returns the fallback. Emits the same `run.completed` / `fallback_invoked` events as a real open circuit. |
355
532
  | `StandardCircuit.force_closed(name) { ... }` | Bypass the circuit for the block — `run` just yields. No events. |
356
533
  | `StandardCircuit.reset_force!` | Clear every forced state. |
534
+ | `StandardCircuit.dependency(name).lock_open!` / `lock_closed!` / `unlock!` | Lock every breaker behind a dependency (or `.purpose(p).lock_open!` for one purpose's breaker) in the data store. Unlike `force_open`, the circuit really is locked red, so `health_report` shows it `locked: true`. `reset!` clears it with the `Memory` store. |
357
535
  | `StandardCircuit.reset!` | Clear the light cache and forced states, and swap in a fresh `Memory` data store (left alone when the store is Redis). |
358
536
  | `require "standard_circuit/rspec"` | Adds a `before(:each)` that runs `reset!` and tears down subscribers. Circuit registrations are kept. |
359
537
 
@@ -17,6 +17,7 @@ module StandardCircuit
17
17
  :tracked_errors,
18
18
  :skipped_errors,
19
19
  :criticality,
20
+ :metrics_only,
20
21
  keyword_init: true
21
22
  ) do
22
23
  def self.build(**opts)
@@ -37,13 +38,22 @@ module StandardCircuit
37
38
  # default only kicks in when the key is absent. See
38
39
  # ErrorTaxonomies.default_skipped_for for why AWS needs one.
39
40
  skipped_errors: opts.fetch(:skipped_errors) { ErrorTaxonomies.default_skipped_for(tracked_errors) },
40
- criticality: criticality
41
+ criticality: criticality,
42
+ # Time and record calls, but never open: see Runner#execute_metrics_only.
43
+ metrics_only: opts.fetch(:metrics_only, false) ? true : false
41
44
  )
42
45
  end
43
46
  end
44
47
 
48
+ # What a `run` resolves to: the circuit (breaker) that guards the call,
49
+ # plus the dependency and purpose it is made for. +dependency+ and
50
+ # +purpose+ are nil for a name nothing was registered under; the runner
51
+ # then raises UnknownCircuit exactly as before (forced states aside).
52
+ RunTarget = Data.define(:circuit, :dependency, :purpose, :criticality)
53
+
45
54
  attr_accessor :sentry_enabled, :metric_prefix, :data_store, :logger
46
- attr_reader :circuits, :prefixes, :extra_notifiers, :sentry_criticality_levels, :mailer_retry
55
+ attr_reader :circuits, :prefixes, :extra_notifiers, :sentry_criticality_levels, :mailer_retry,
56
+ :stats_window_size
47
57
 
48
58
  def initialize
49
59
  @sentry_enabled = true
@@ -53,9 +63,23 @@ module StandardCircuit
53
63
  @logger = nil
54
64
  @circuits = {}
55
65
  @prefixes = {}
66
+ @dependencies = {}
67
+ @prefix_dependencies = {}
68
+ @circuit_owners = {}
56
69
  @extra_notifiers = []
57
70
  @extra_notifier_keys = []
58
71
  @mailer_retry = nil
72
+ @stats_window_size = Stats::DEFAULT_WINDOW_SIZE
73
+ end
74
+
75
+ # How many recent calls each dependency's and purpose's rolling stats
76
+ # keep (see Stats). Applied on `configure`; changing it drops the windows.
77
+ def stats_window_size=(size)
78
+ unless size.is_a?(Integer) && size.positive?
79
+ raise ArgumentError, "stats_window_size must be a positive Integer; got #{size.inspect}"
80
+ end
81
+
82
+ @stats_window_size = size
59
83
  end
60
84
 
61
85
  # Opt in to retrying ActionMailer::MailDeliveryJob on
@@ -91,13 +115,18 @@ module StandardCircuit
91
115
  def reset_registry!
92
116
  @circuits.clear
93
117
  @prefixes.clear
118
+ @dependencies.clear
119
+ @prefix_dependencies.clear
120
+ @circuit_owners.clear
94
121
  @extra_notifiers.clear
95
122
  @extra_notifier_keys.clear
96
123
  end
97
124
 
125
+ # Registers circuit +name+, and with it a breaker-only dependency of the
126
+ # same name with one implicit purpose (see DependencySpec).
98
127
  def register(name, **opts)
99
128
  spec = CircuitSpec.build(**opts)
100
- @circuits[name.to_sym] = spec
129
+ install_dependency(DependencySpec.for_circuit(name, spec))
101
130
  EventEmitter.emit("standard_circuit.circuit.registered",
102
131
  circuit: name.to_s,
103
132
  criticality: spec.criticality,
@@ -105,9 +134,12 @@ module StandardCircuit
105
134
  spec
106
135
  end
107
136
 
137
+ # Registers every circuit named `<prefix>_<anything>`. They are the
138
+ # sub-circuits of one dependency named +prefix+.
108
139
  def register_prefix(prefix, **opts)
109
140
  spec = CircuitSpec.build(**opts)
110
141
  @prefixes[prefix.to_s] = spec
142
+ @prefix_dependencies[prefix.to_sym] = DependencySpec.for_prefix(prefix, spec)
111
143
  EventEmitter.emit("standard_circuit.circuit.registered",
112
144
  circuit: prefix.to_s,
113
145
  criticality: spec.criticality,
@@ -128,6 +160,72 @@ module StandardCircuit
128
160
  scope == :prefix ? register_prefix(name, **opts) : register(name, **opts)
129
161
  end
130
162
 
163
+ # Declare an external service the app depends on, with the reasons
164
+ # (purposes) it calls it:
165
+ #
166
+ # c.dependency :stripe, criticality: :critical, threshold: 5,
167
+ # tracked_errors: ErrorTaxonomies::Stripe.tracked
168
+ #
169
+ # c.dependency :google_oauth, threshold: 3 do |d|
170
+ # d.purpose :sign_in, criticality: :critical
171
+ # d.purpose :calendar, criticality: :standard
172
+ # end
173
+ #
174
+ # c.dependency :google_maps, criticality: :optional do |d|
175
+ # d.purpose :places, default: true
176
+ # d.purpose :address, isolate: true, threshold: 2 # breaker :google_maps_address
177
+ # end
178
+ #
179
+ # Breaker options are the ones `register` takes. +criticality:+ is the
180
+ # default for each purpose. See DependencySpec for the rules. Re-declaring
181
+ # a dependency replaces it; a breaker name already owned by another
182
+ # dependency raises ArgumentError.
183
+ def dependency(name, **opts, &block)
184
+ spec = DependencySpec.define(name, **opts, &block)
185
+ install_dependency(spec)
186
+ spec.circuits.each do |circuit, circuit_spec|
187
+ EventEmitter.emit("standard_circuit.circuit.registered",
188
+ circuit: circuit.to_s,
189
+ criticality: circuit_spec.criticality,
190
+ scope: :name)
191
+ end
192
+ spec
193
+ end
194
+
195
+ # Every dependency, named ones first, then one per prefix registration.
196
+ def dependency_specs
197
+ @dependencies.values + @prefix_dependencies.values
198
+ end
199
+
200
+ # A named dependency wins over a prefix dependency of the same name.
201
+ def dependency_spec(name)
202
+ key = name.to_sym
203
+ @dependencies[key] || @prefix_dependencies[key] or
204
+ raise UnknownDependency, "no dependency registered for #{key.inspect}"
205
+ end
206
+
207
+ # Resolve what `run(name, purpose:)` guards. +name+ is a dependency, or a
208
+ # circuit: a prefix-matched one (`:s3_uploads`) or an isolated purpose's
209
+ # own breaker (`:google_maps_address`).
210
+ def run_target(name, purpose = nil)
211
+ key = name.to_sym
212
+ if (dependency = @dependencies[key])
213
+ target_for(dependency, dependency.resolve_purpose(purpose))
214
+ elsif (owner = @circuit_owners[key])
215
+ dependency = @dependencies.fetch(owner)
216
+ resolved = dependency.purposes.find { |p| p.circuit == key }
217
+ check_purpose!(dependency, resolved, purpose)
218
+ target_for(dependency, resolved)
219
+ elsif (dependency = prefix_dependency_for(key))
220
+ resolved = dependency.resolve_purpose(purpose)
221
+ RunTarget.new(circuit: key, dependency: dependency.name, purpose: resolved.name, criticality: resolved.criticality)
222
+ else
223
+ raise UnknownCircuit, "no circuit registered for #{key.inspect}" unless purpose.nil?
224
+
225
+ RunTarget.new(circuit: key, dependency: nil, purpose: nil, criticality: spec_for(key)&.criticality)
226
+ end
227
+ end
228
+
131
229
  # Register a host-supplied subscriber. Subscribers must respond to
132
230
  # `call(event_name, payload)` — Stoplight-shaped 4-arg notifiers from the
133
231
  # 0.1.x API are no longer accepted as extras (Logger / Sentry / Metrics
@@ -170,6 +268,68 @@ module StandardCircuit
170
268
 
171
269
  private
172
270
 
271
+ # Swap in +spec+ for the dependency of the same name: drop the breakers the
272
+ # previous definition registered, then register the new ones. Breakers
273
+ # the new definition keeps are overwritten in place rather than deleted
274
+ # and re-added, so `circuits` (and so `health_report`) keeps its order.
275
+ # Every conflict is checked before anything changes, so a rejected
276
+ # definition leaves the registry exactly as it was.
277
+ def install_dependency(spec)
278
+ check_names!(spec)
279
+
280
+ stale = @circuit_owners.select { |circuit, owner| owner == spec.name && !spec.circuits.key?(circuit) }
281
+ stale.each_key do |circuit|
282
+ @circuits.delete(circuit)
283
+ @circuit_owners.delete(circuit)
284
+ end
285
+
286
+ spec.circuits.each do |circuit, circuit_spec|
287
+ @circuits[circuit] = circuit_spec
288
+ @circuit_owners[circuit] = spec.name
289
+ end
290
+ @dependencies[spec.name] = spec
291
+ end
292
+
293
+ # `run(name)` resolves a dependency name before a breaker name, so the two
294
+ # share one namespace across dependencies: a breaker may not take another
295
+ # dependency's name or another dependency's breaker, and a dependency may
296
+ # not take another dependency's breaker name.
297
+ def check_names!(spec)
298
+ spec.circuits.each_key do |circuit|
299
+ owner = @circuit_owners[circuit]
300
+ owner = circuit if owner.nil? && @dependencies.key?(circuit)
301
+ next if owner.nil? || owner == spec.name
302
+
303
+ raise ArgumentError,
304
+ "circuit #{circuit.inspect} of dependency #{spec.name.inspect} is already registered by dependency #{owner.inspect}"
305
+ end
306
+
307
+ owner = @circuit_owners[spec.name]
308
+ return if owner.nil? || owner == spec.name
309
+
310
+ raise ArgumentError,
311
+ "dependency #{spec.name.inspect} has the name of a circuit already registered by dependency #{owner.inspect}"
312
+ end
313
+
314
+ def target_for(dependency, purpose)
315
+ RunTarget.new(circuit: purpose.circuit, dependency: dependency.name, purpose: purpose.name,
316
+ criticality: purpose.criticality)
317
+ end
318
+
319
+ def check_purpose!(dependency, resolved, requested)
320
+ return if requested.nil? || requested.to_sym == resolved.name
321
+
322
+ raise UnknownPurpose,
323
+ "circuit #{resolved.circuit.inspect} is the breaker of purpose #{resolved.name.inspect} of dependency " \
324
+ "#{dependency.name.inspect}, not #{requested.inspect}"
325
+ end
326
+
327
+ def prefix_dependency_for(name)
328
+ key = name.to_s
329
+ _prefix, dependency = @prefix_dependencies.find { |prefix, _| key.start_with?("#{prefix}_") }
330
+ dependency
331
+ end
332
+
173
333
  def normalize_sentry_criticality_levels(value)
174
334
  case value
175
335
  when nil, false then nil