standard_circuit 0.8.0 → 0.8.1
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 +54 -0
- data/README.md +74 -2
- data/lib/standard_circuit/config.rb +15 -0
- data/lib/standard_circuit/controller_support.rb +15 -0
- data/lib/standard_circuit/dependency.rb +50 -19
- data/lib/standard_circuit/retry_wait.rb +43 -0
- data/lib/standard_circuit/runner.rb +87 -4
- data/lib/standard_circuit/version.rb +1 -1
- data/lib/standard_circuit.rb +22 -0
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 4ea24010174027849002f237343e10c8955c781f36dcc43b2e927bb67c681167
|
|
4
|
+
data.tar.gz: 2a25e69c7079d7dd38d45b8988333d03d6b28c0ae9f4a648fae0ffcedb6c15d4
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: e575c7d20e5636744f93b020ddfb7a56f948378027c6292d8b8b71d501bc109c507b834ed07a77cd5ca9c651c10336e4a9fafe846f73d35f6ad10b9c65670e83
|
|
7
|
+
data.tar.gz: 55cd4b6f5ad45b99ca19c6d09e9b3d4a6ceed80189461e1093656f16ef509ed77eb3fb9644b8b4dc997d4f15110495c5f57a3ec09f37b1f11da33ea300ef391d
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.8.1] - 2026-11-25
|
|
11
|
+
|
|
12
|
+
Small additions and one fix, found while aligning the five apps on 0.8. A
|
|
13
|
+
job helper that retries an open circuit after its cool-off; `json:` bodies
|
|
14
|
+
for API clients that don't send a JSON Accept header; and lock ergonomics
|
|
15
|
+
for test suites. **No host code changes are needed.** Each app can now
|
|
16
|
+
delete some code it carries (see the README's "Replace your host code with"
|
|
17
|
+
snippets).
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- **`StandardCircuit.retry_wait(*names, jitter: nil)`**, the `wait:` for a
|
|
22
|
+
job's `retry_on Stoplight::Error::RedLight`. Polynomial backoff
|
|
23
|
+
(`executions**4 + 2`) floored at the longest `cool_off_time` behind the
|
|
24
|
+
names (read at retry time, rounded up to whole seconds as the breaker
|
|
25
|
+
rounds it), plus jitter on top of the floor (ActiveJob adds
|
|
26
|
+
none to a Proc `wait`; defaults to `ActiveJob::Base.retry_jitter`). Takes
|
|
27
|
+
circuits, dependencies (every breaker, isolated purposes included) and
|
|
28
|
+
prefixes. Replaces the waits jumpdrive-web, luminality-web and
|
|
29
|
+
nutripod-web hand-rolled. See "Jobs: retrying on an open circuit" in the
|
|
30
|
+
README.
|
|
31
|
+
- **`StandardCircuit.reset_locks!`** unlocks every circuit locked through
|
|
32
|
+
`dependency(name).lock_open!` / `lock_closed!` (or a purpose's) in this
|
|
33
|
+
process. Breaker state, forced states and the data store are left alone.
|
|
34
|
+
For suites that don't load `standard_circuit/rspec`:
|
|
35
|
+
`config.after { StandardCircuit.reset_locks! }`.
|
|
36
|
+
- **Block form of `lock_open!` / `lock_closed!`**, on a dependency and on a
|
|
37
|
+
purpose: `dep.lock_open! { ... }` locks only for the block, then puts each
|
|
38
|
+
breaker back as it was (an enclosing lock stays), even if the block
|
|
39
|
+
raises, and returns the block's value. Without a block they still
|
|
40
|
+
return the handle.
|
|
41
|
+
- **`purposes:` on `Dependency#lock_open!` / `lock_closed!` / `unlock!`.**
|
|
42
|
+
The default, `:all`, is unchanged: every breaker behind the dependency,
|
|
43
|
+
isolated purposes' own included, so `open?` is true afterwards
|
|
44
|
+
(luminality-web's specs rely on this). A purpose name or an Array of them
|
|
45
|
+
locks only those purposes' breakers.
|
|
46
|
+
- **A warning when a lock leaks between examples.** When a call reaches a
|
|
47
|
+
circuit that a different RSpec example locked and nothing has cleared it,
|
|
48
|
+
StandardCircuit warns once per process, naming the circuit, the example
|
|
49
|
+
that locked it, and the three ways to clear locks. jumpdrive-web hit this
|
|
50
|
+
leak before it loaded the RSpec helper.
|
|
51
|
+
|
|
52
|
+
### Fixed
|
|
53
|
+
|
|
54
|
+
- **`ControllerSupport` gives API clients the `json:` body.** Before, the
|
|
55
|
+
`json:` lambda ran only when `request.format.json?`, so an API client
|
|
56
|
+
sending `Accept: */*`, or no Accept header, got `html:` or a bodiless
|
|
57
|
+
`head`. Now `json:` also answers every request to an
|
|
58
|
+
`ActionController::API` controller and any request that doesn't accept
|
|
59
|
+
HTML. `ActionController::Base` controllers keep answering browsers,
|
|
60
|
+
`Accept: */*` and a missing Accept header with `html:`. A streaming
|
|
61
|
+
controller still prefers `stream:` unless the request asked for JSON. The
|
|
62
|
+
0.8 `Retry-After` header is unchanged.
|
|
63
|
+
|
|
10
64
|
## [0.8.0] - 2026-11-25
|
|
11
65
|
|
|
12
66
|
Every dependency now reports to StandardHealth (0.10+) as a row with a
|
data/README.md
CHANGED
|
@@ -217,10 +217,15 @@ dep = StandardCircuit.dependency(:google_maps)
|
|
|
217
217
|
dep.purpose(:address).open? # an isolated purpose has its own breaker
|
|
218
218
|
dep.purpose(:address).status
|
|
219
219
|
dep.purpose(:address).lock_open! # locks only :google_maps_address
|
|
220
|
+
|
|
221
|
+
dep.lock_open! # every breaker: :google_maps and :google_maps_address
|
|
222
|
+
dep.lock_open!(purposes: :places) # only the breaker :places uses (0.8.1)
|
|
223
|
+
dep.lock_open! { checkout! } # only for the block; returns its value (0.8.1)
|
|
220
224
|
```
|
|
221
225
|
|
|
222
226
|
- `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`.
|
|
223
227
|
- 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.
|
|
228
|
+
- `Dependency#lock_open!` / `lock_closed!` / `unlock!` cover **every** breaker behind the dependency by default, isolated purposes' own included, so `open?` is true after `lock_open!`. Pass `purposes:` (a purpose name, or an Array) to lock only those purposes' breakers, e.g. to test that an isolated fallback still serves while the primary is open. `purposes: :all` is the default, spelled out.
|
|
224
229
|
- 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.
|
|
225
230
|
- 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.
|
|
226
231
|
|
|
@@ -531,9 +536,28 @@ end
|
|
|
531
536
|
```
|
|
532
537
|
|
|
533
538
|
- `json:` and `html:` run in the controller. Since 0.8 they may take the `RedLight` (`->(error) { ... }`); zero-arity lambdas and blocks keep working.
|
|
539
|
+
- **Which body a request gets** (0.8.1): `json:` when the request asks for JSON (`Accept: application/json`, `.json`); then `stream:` in an `ActionController::Live` controller; then `json:` again for an API-shaped request, which is every request to an `ActionController::API` controller and any request that doesn't accept HTML (`Accept: text/plain`, or only unregistered types); then `html:`; then a bare `head`. `Accept: */*` and a missing Accept header both accept HTML, so an `ActionController::Base` controller still answers them with `html:`. An API controller answers them with `json:`, so it no longer needs an `html:` that repeats the JSON body.
|
|
534
540
|
- **Every circuit-open response carries `Retry-After`** (0.8), in whole seconds and never less than 1: the time until the breaker's recovery probe when stoplight knows it, otherwise the circuit's `cool_off_time` (a breaker locked or forced open has no recovery time), otherwise no header. It is set before your lambda runs, so `render` and `head` both send it.
|
|
535
541
|
- Declare `circuit_open_fallback` after any `rescue_from StandardError`, so the `RedLight` handler stays last.
|
|
536
542
|
|
|
543
|
+
Replace your host code with:
|
|
544
|
+
|
|
545
|
+
```ruby
|
|
546
|
+
# Before: an API controller repeating its JSON body in html:, because Accept */*
|
|
547
|
+
# (or no Accept header) skipped json:
|
|
548
|
+
class Api::BaseController < ActionController::API
|
|
549
|
+
include StandardCircuit::ControllerSupport
|
|
550
|
+
circuit_open_fallback json: -> { render_api_error(:SVC_001) },
|
|
551
|
+
html: -> { render_api_error(:SVC_001) }
|
|
552
|
+
end
|
|
553
|
+
|
|
554
|
+
# After
|
|
555
|
+
class Api::BaseController < ActionController::API
|
|
556
|
+
include StandardCircuit::ControllerSupport
|
|
557
|
+
circuit_open_fallback json: -> { render_api_error(:SVC_001) }
|
|
558
|
+
end
|
|
559
|
+
```
|
|
560
|
+
|
|
537
561
|
## Streaming and non-controller contexts
|
|
538
562
|
|
|
539
563
|
`ControllerSupport.circuit_open_fallback` only works for non-streaming responses — once a `Live` controller has flushed any output, Rails can't render an error template over the wire. For a streaming controller, catch `Stoplight::Error::RedLight` *inside* the streaming proc and write a degraded payload before the stream closes:
|
|
@@ -563,7 +587,39 @@ class Api::MessagesController < ApplicationController
|
|
|
563
587
|
end
|
|
564
588
|
```
|
|
565
589
|
|
|
566
|
-
Same pattern applies in background jobs (where `circuit_open_fallback` doesn't help): wrap the work in `StandardCircuit.run` and rescue `Stoplight::Error::RedLight` to either `discard_on` (avoid thundering retries) or `retry_on` with backoff (defer until cool-off), depending on whether eventual delivery is required.
|
|
590
|
+
Same pattern applies in background jobs (where `circuit_open_fallback` doesn't help): wrap the work in `StandardCircuit.run` and rescue `Stoplight::Error::RedLight` to either `discard_on` (avoid thundering retries) or `retry_on` with backoff (defer until cool-off, see below), depending on whether eventual delivery is required.
|
|
591
|
+
|
|
592
|
+
## Jobs: retrying on an open circuit (`retry_wait`)
|
|
593
|
+
|
|
594
|
+
`StandardCircuit.retry_wait` (0.8.1) is the `wait:` for a `retry_on Stoplight::Error::RedLight`:
|
|
595
|
+
|
|
596
|
+
```ruby
|
|
597
|
+
class ChargeJob < ApplicationJob
|
|
598
|
+
retry_on Stoplight::Error::RedLight, wait: StandardCircuit.retry_wait(:stripe), attempts: 5
|
|
599
|
+
end
|
|
600
|
+
```
|
|
601
|
+
|
|
602
|
+
- The wait is `:polynomially_longer`'s `executions**4 + 2` seconds, but never less than the circuit's `cool_off_time` (rounded up to whole seconds, as the breaker rounds it). A retry that lands while the breaker is still cooling off fails fast and burns an attempt, which is what `:polynomially_longer` alone does on its first two retries (~3s, ~18s).
|
|
603
|
+
- The cool-off is read from the registration at retry time, so a `cool_off_time` change carries over.
|
|
604
|
+
- Jitter is kept. ActiveJob adds no jitter to a Proc `wait`, so `retry_wait` adds it on top of the floor (never below it). It defaults to `ActiveJob::Base.retry_jitter` (0.15); pass `jitter:` to change it, e.g. `jitter: retry_jitter` in a job with its own, or `jitter: 0`.
|
|
605
|
+
- Pass several names when a job's `RedLight` can come from several circuits: `StandardCircuit.retry_wait(:node_runner, :nomad, :broker)` floors at the longest cool-off. A dependency name covers all of its breakers, isolated purposes included; a prefix (`:s3`) or one of its circuits (`:s3_uploads`) works too.
|
|
606
|
+
- A name nothing registered raises `StandardCircuit::UnknownCircuit` when the retry is scheduled, so a typo fails the job loudly rather than retrying blind.
|
|
607
|
+
|
|
608
|
+
Replace your host code with:
|
|
609
|
+
|
|
610
|
+
```ruby
|
|
611
|
+
# Before: hand-rolled in each app
|
|
612
|
+
def self.circuit_retry_wait(circuit)
|
|
613
|
+
lambda do |executions|
|
|
614
|
+
delay = [ StandardCircuit.config.spec_for(circuit).cool_off_time, (executions**4) + 2 ].max
|
|
615
|
+
delay + (Kernel.rand * delay * retry_jitter)
|
|
616
|
+
end
|
|
617
|
+
end
|
|
618
|
+
retry_on Stoplight::Error::RedLight, wait: circuit_retry_wait(:ruby_llm), attempts: 5
|
|
619
|
+
|
|
620
|
+
# After
|
|
621
|
+
retry_on Stoplight::Error::RedLight, wait: StandardCircuit.retry_wait(:ruby_llm), attempts: 5
|
|
622
|
+
```
|
|
567
623
|
|
|
568
624
|
|
|
569
625
|
## Health endpoint
|
|
@@ -610,12 +666,28 @@ These are supported public API for host test suites, not internals:
|
|
|
610
666
|
| `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. |
|
|
611
667
|
| `StandardCircuit.force_closed(name) { ... }` | Bypass the circuit for the block — `run` just yields. No events. |
|
|
612
668
|
| `StandardCircuit.reset_force!` | Clear every forced state. |
|
|
613
|
-
| `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`. `
|
|
669
|
+
| `StandardCircuit.dependency(name).lock_open!` / `lock_closed!` / `unlock!` | Lock every breaker behind a dependency (`purposes:` narrows it; 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`. With a block, the lock lasts only for the block, after which each breaker goes back to how it was (an enclosing lock is kept). Otherwise it stays until `unlock!`, `reset_locks!` or `reset!` (with the `Memory` store). |
|
|
670
|
+
| `StandardCircuit.reset_locks!` | Unlock every circuit locked through the lock API in this process (0.8.1). Leaves breaker state, forced states and the data store alone. |
|
|
614
671
|
| `StandardCircuit.reset!` | Clear forced states and breaker state, so every circuit is green with no failures, and swap in a fresh `Memory` data store (left alone when the store is Redis). Once a circuit has been used, the next call builds a new system generation (see `data_store`). |
|
|
615
672
|
| `require "standard_circuit/rspec"` | Adds a `before(:each)` that runs `reset!`, frees the stoplight systems earlier examples left behind (below), and tears down subscribers. Circuit registrations are kept. |
|
|
616
673
|
|
|
617
674
|
All of these are **process-local**. They are test and console tools, not an operational kill switch (see `data_store` above).
|
|
618
675
|
|
|
676
|
+
**Locks outlive the example that made them.** A lock lives in the data store, so it is still there in the next example unless something clears it. Pick one:
|
|
677
|
+
|
|
678
|
+
```ruby
|
|
679
|
+
# spec/rails_helper.rb: resets everything before each example (recommended)
|
|
680
|
+
require "standard_circuit/rspec"
|
|
681
|
+
|
|
682
|
+
# or, without the helper: clear locks after each example
|
|
683
|
+
RSpec.configure { |config| config.after { StandardCircuit.reset_locks! } }
|
|
684
|
+
|
|
685
|
+
# or lock only for the code under test
|
|
686
|
+
StandardCircuit.dependency(:stripe).lock_open! { post checkout_path }
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
When a call reaches a circuit that a different RSpec example locked, StandardCircuit prints one warning per process naming the circuit and the example that locked it (0.8.1). The next example to fail then shows its real cause.
|
|
690
|
+
|
|
619
691
|
**What the RSpec helper does to stoplight.** Each `reset!` after a circuit was used starts a new stoplight system generation, and stoplight keeps every superseded system for the life of the process: some 20–35 KB per example that used a circuit. To keep a suite flat, the helper calls stoplight's own test reset, `Stoplight.__stoplight__reset!`, before each example. That frees them, and the runner starts again at the system name `standard_circuit`. That method is not part of stoplight's public API, so only the helper calls it; `StandardCircuit.reset!` on its own never does.
|
|
620
692
|
|
|
621
693
|
- It clears **all** stoplight state in the process between examples, not only StandardCircuit's: lights and systems a host registered with `Stoplight` directly, and the default configuration from `Stoplight.configure`, are reset too. A host spec that relies on its own stoplight setup surviving from one example to the next has to set it up again in a `before`.
|
|
@@ -269,6 +269,21 @@ module StandardCircuit
|
|
|
269
269
|
@circuits[name.to_sym] || spec_for_prefix(name)
|
|
270
270
|
end
|
|
271
271
|
|
|
272
|
+
# The longest cool-off behind +name+: every breaker of a dependency
|
|
273
|
+
# (shared and isolated), a named circuit (an isolated purpose's own
|
|
274
|
+
# included), a prefix, or a prefix-matched circuit, in that order, so an
|
|
275
|
+
# exact prefix wins over a broader one that also matches it. Rounded up
|
|
276
|
+
# to whole seconds as the light's is (see Runner#light_settings). Raises
|
|
277
|
+
# UnknownCircuit. See RetryWait.
|
|
278
|
+
def cool_off_time_for(name)
|
|
279
|
+
key = name.to_sym
|
|
280
|
+
spec = @dependencies[key]&.circuits&.values&.max_by(&:cool_off_time) ||
|
|
281
|
+
@circuits[key] || @prefixes[key.to_s] || spec_for_prefix(key)
|
|
282
|
+
raise UnknownCircuit, "no circuit or dependency registered for #{key.inspect}" unless spec
|
|
283
|
+
|
|
284
|
+
[ spec.cool_off_time.ceil, 1 ].max
|
|
285
|
+
end
|
|
286
|
+
|
|
272
287
|
private
|
|
273
288
|
|
|
274
289
|
# Swap in +spec+ for the dependency of the same name: drop the breakers the
|
|
@@ -60,11 +60,26 @@ module StandardCircuit
|
|
|
60
60
|
|
|
61
61
|
return call_circuit_open_fallback(fallback[:json], error) if request.format.json? && fallback[:json]
|
|
62
62
|
return instance_exec(response, &fallback[:stream]) if streaming_controller? && fallback[:stream]
|
|
63
|
+
return call_circuit_open_fallback(fallback[:json], error) if fallback[:json] && circuit_open_api_request?
|
|
63
64
|
return call_circuit_open_fallback(fallback[:html], error) if fallback[:html]
|
|
64
65
|
|
|
65
66
|
head(fallback[:status] || :service_unavailable)
|
|
66
67
|
end
|
|
67
68
|
|
|
69
|
+
# An API client gets the `json:` body even when it didn't ask for JSON
|
|
70
|
+
# by name (0.8.1): every request to an ActionController::API controller,
|
|
71
|
+
# and any request that doesn't accept HTML. `Accept: */*` and a missing
|
|
72
|
+
# Accept header both accept HTML (Rails reads them as `*/*` and `html`),
|
|
73
|
+
# so an ActionController::Base controller keeps answering them with
|
|
74
|
+
# `html:`, as before.
|
|
75
|
+
def circuit_open_api_request?
|
|
76
|
+
return true if defined?(::ActionController::API) && self.class <= ::ActionController::API
|
|
77
|
+
|
|
78
|
+
# A parsed `*/*` is a symbol-less Mime::Type, not Mime::ALL, and answers
|
|
79
|
+
# html? false, so match the wildcard by its ref.
|
|
80
|
+
request.formats.none? { |format| format.html? || format.ref == "*/*" }
|
|
81
|
+
end
|
|
82
|
+
|
|
68
83
|
# `json:` / `html:` lambdas may take the RedLight (to name the circuit, or
|
|
69
84
|
# echo the retry delay); the zero-arity lambdas written before 0.8 still
|
|
70
85
|
# work unchanged.
|
|
@@ -129,22 +129,31 @@ module StandardCircuit
|
|
|
129
129
|
purposes.map(&:status).max_by { |status| STATUS_RANK.fetch(status) }
|
|
130
130
|
end
|
|
131
131
|
|
|
132
|
-
# Lock
|
|
133
|
-
#
|
|
134
|
-
#
|
|
135
|
-
#
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
132
|
+
# Lock the dependency's breakers open (calls raise RedLight, or return
|
|
133
|
+
# their fallback) or closed (calls always go through) until #unlock!.
|
|
134
|
+
#
|
|
135
|
+
# +purposes:+ picks which breakers. +:all+ (the default) is every breaker
|
|
136
|
+
# behind the dependency, isolated purposes' own included, so `open?` is
|
|
137
|
+
# true afterwards. A purpose name, or an Array of them, locks only those
|
|
138
|
+
# purposes' breakers; a purpose sharing the dependency's breaker locks it
|
|
139
|
+
# for every purpose that shares it. For a prefix dependency the breakers
|
|
140
|
+
# are the sub-circuits used so far in this process.
|
|
141
|
+
#
|
|
142
|
+
# With a block, the lock lasts only for the block: afterwards, even if it
|
|
143
|
+
# raises, each breaker goes back as it was (an enclosing lock stays), and
|
|
144
|
+
# the block's value is returned. Without one, the
|
|
145
|
+
# lock stays until #unlock!, StandardCircuit.reset_locks! or
|
|
146
|
+
# StandardCircuit.reset!, and the dependency is returned.
|
|
147
|
+
def lock_open!(purposes: :all, &block)
|
|
148
|
+
apply_lock(:open, purposes, &block)
|
|
139
149
|
end
|
|
140
150
|
|
|
141
|
-
def lock_closed!
|
|
142
|
-
|
|
143
|
-
self
|
|
151
|
+
def lock_closed!(purposes: :all, &block)
|
|
152
|
+
apply_lock(:closed, purposes, &block)
|
|
144
153
|
end
|
|
145
154
|
|
|
146
|
-
def unlock!
|
|
147
|
-
|
|
155
|
+
def unlock!(purposes: :all)
|
|
156
|
+
circuits_for(purposes).each { |circuit| @runner.unlock(circuit) }
|
|
148
157
|
self
|
|
149
158
|
end
|
|
150
159
|
|
|
@@ -239,15 +248,14 @@ module StandardCircuit
|
|
|
239
248
|
end
|
|
240
249
|
|
|
241
250
|
# Locks this purpose's breaker. A purpose that shares the dependency's
|
|
242
|
-
# breaker locks it for every purpose sharing it.
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
251
|
+
# breaker locks it for every purpose sharing it. With a block, only for
|
|
252
|
+
# the block (see Dependency#lock_open!).
|
|
253
|
+
def lock_open!(&block)
|
|
254
|
+
apply_lock(:open, &block)
|
|
246
255
|
end
|
|
247
256
|
|
|
248
|
-
def lock_closed!
|
|
249
|
-
|
|
250
|
-
self
|
|
257
|
+
def lock_closed!(&block)
|
|
258
|
+
apply_lock(:closed, &block)
|
|
251
259
|
end
|
|
252
260
|
|
|
253
261
|
def unlock!
|
|
@@ -261,6 +269,13 @@ module StandardCircuit
|
|
|
261
269
|
|
|
262
270
|
private
|
|
263
271
|
|
|
272
|
+
def apply_lock(state, &block)
|
|
273
|
+
return dependency.runner.with_locks(circuit_names, state, &block) if block
|
|
274
|
+
|
|
275
|
+
dependency.runner.with_locks(circuit_names, state)
|
|
276
|
+
self
|
|
277
|
+
end
|
|
278
|
+
|
|
264
279
|
def color_for(states)
|
|
265
280
|
metrics_only? ? "green" : Dependency.worst_color(states)
|
|
266
281
|
end
|
|
@@ -275,5 +290,21 @@ module StandardCircuit
|
|
|
275
290
|
Health.severity(criticality, color_for(states))
|
|
276
291
|
end
|
|
277
292
|
end
|
|
293
|
+
|
|
294
|
+
private
|
|
295
|
+
|
|
296
|
+
def apply_lock(state, purposes, &block)
|
|
297
|
+
circuits = circuits_for(purposes)
|
|
298
|
+
return @runner.with_locks(circuits, state, &block) if block
|
|
299
|
+
|
|
300
|
+
@runner.with_locks(circuits, state)
|
|
301
|
+
self
|
|
302
|
+
end
|
|
303
|
+
|
|
304
|
+
def circuits_for(purposes)
|
|
305
|
+
return circuit_names if purposes == :all
|
|
306
|
+
|
|
307
|
+
Array(purposes).flat_map { |purpose_name| purpose(purpose_name).circuit_names }.uniq
|
|
308
|
+
end
|
|
278
309
|
end
|
|
279
310
|
end
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
module StandardCircuit
|
|
2
|
+
# The `wait:` for a job's `retry_on Stoplight::Error::RedLight` (see
|
|
3
|
+
# StandardCircuit.retry_wait). `:polynomially_longer` alone retries after
|
|
4
|
+
# ~3s and ~18s, while the breaker is still cooling off, so those attempts
|
|
5
|
+
# land on an open circuit and are wasted. This keeps the polynomial backoff
|
|
6
|
+
# (`executions**4 + 2` seconds) but never waits less than the longest
|
|
7
|
+
# cool-off behind the names given, read from the registration at retry
|
|
8
|
+
# time so a cool_off_time change carries over.
|
|
9
|
+
#
|
|
10
|
+
# ActiveJob calls a Proc `wait` with the execution count alone and adds no
|
|
11
|
+
# jitter of its own, so the jitter is added here, on top of the floor: jobs
|
|
12
|
+
# an outage queued up don't all retry at the same instant, and none retries
|
|
13
|
+
# before the cool-off.
|
|
14
|
+
module RetryWait
|
|
15
|
+
# ActiveJob's own default `retry_jitter`, for when ActiveJob isn't loaded.
|
|
16
|
+
DEFAULT_JITTER = 0.15
|
|
17
|
+
|
|
18
|
+
class << self
|
|
19
|
+
# +names+ are circuits or dependencies (see Config#cool_off_time_for).
|
|
20
|
+
# +jitter+ is a fraction of the delay, like `retry_on`'s; nil reads
|
|
21
|
+
# ActiveJob::Base.retry_jitter at retry time.
|
|
22
|
+
def build(names, jitter: nil)
|
|
23
|
+
raise ArgumentError, "retry_wait needs at least one circuit or dependency name" if names.empty?
|
|
24
|
+
unless jitter.nil? || (jitter.is_a?(Numeric) && jitter >= 0)
|
|
25
|
+
raise ArgumentError, "jitter must be nil or a non-negative Numeric; got #{jitter.inspect}"
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
names = names.map(&:to_sym).freeze
|
|
29
|
+
lambda do |executions|
|
|
30
|
+
cool_off = names.map { |name| StandardCircuit.config.cool_off_time_for(name) }.max
|
|
31
|
+
delay = [ (executions**4) + 2, cool_off ].max
|
|
32
|
+
delay + (Kernel.rand * delay * (jitter || default_jitter))
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
private
|
|
37
|
+
|
|
38
|
+
def default_jitter
|
|
39
|
+
defined?(::ActiveJob::Base) ? ::ActiveJob::Base.retry_jitter.to_f : DEFAULT_JITTER
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
@@ -30,6 +30,11 @@ module StandardCircuit
|
|
|
30
30
|
SystemEntry = Data.define(:name, :system, :data_store, :config)
|
|
31
31
|
private_constant :SystemEntry
|
|
32
32
|
|
|
33
|
+
# A lock made through #lock: its state (:open / :closed) and the RSpec
|
|
34
|
+
# example that made it (nil outside one).
|
|
35
|
+
Lock = Data.define(:state, :example)
|
|
36
|
+
private_constant :Lock
|
|
37
|
+
|
|
33
38
|
@generation_mutex = Mutex.new
|
|
34
39
|
@generation = 0
|
|
35
40
|
|
|
@@ -57,6 +62,10 @@ module StandardCircuit
|
|
|
57
62
|
# The settings each cached light was registered with (see #reusable?).
|
|
58
63
|
@light_settings = Concurrent::Map.new
|
|
59
64
|
@forced_states = Concurrent::Map.new
|
|
65
|
+
# Circuits locked through #lock, each with its Lock: what #reset_locks!
|
|
66
|
+
# undoes, what a lock block restores, and what the leaked-lock warning
|
|
67
|
+
# checks (see #warn_if_lock_leaked).
|
|
68
|
+
@locks = Concurrent::Map.new
|
|
60
69
|
@config = config
|
|
61
70
|
@system_mutex = Mutex.new
|
|
62
71
|
@system_entry = nil
|
|
@@ -82,6 +91,7 @@ module StandardCircuit
|
|
|
82
91
|
spec = @config.spec_for(target.circuit)
|
|
83
92
|
return execute_metrics_only(target, spec, fallback, &block) if spec&.metrics_only
|
|
84
93
|
|
|
94
|
+
warn_if_lock_leaked(target.circuit) unless @locks.empty?
|
|
85
95
|
forced = @forced_states[target.circuit]
|
|
86
96
|
return run_forced_open(target, fallback) if forced == :open
|
|
87
97
|
return yield if forced == :closed
|
|
@@ -114,7 +124,10 @@ module StandardCircuit
|
|
|
114
124
|
# a name forever. So a fresh store also means a fresh system (see #system).
|
|
115
125
|
def reset!
|
|
116
126
|
@forced_states.clear
|
|
117
|
-
|
|
127
|
+
if @config.data_store.is_a?(Stoplight::DataStore::Memory)
|
|
128
|
+
@config.data_store = Stoplight::DataStore::Memory.new
|
|
129
|
+
@locks.clear # they lived in the store just dropped
|
|
130
|
+
end
|
|
118
131
|
@system_mutex.synchronize do
|
|
119
132
|
@rebuild_system = true
|
|
120
133
|
@check_system = true
|
|
@@ -163,12 +176,52 @@ module StandardCircuit
|
|
|
163
176
|
# process with Redis.
|
|
164
177
|
# A no-op for a metrics-only circuit, whose light is never consulted.
|
|
165
178
|
def lock(name, state)
|
|
166
|
-
|
|
167
|
-
light_for(name).lock(color) unless metrics_only?(name)
|
|
179
|
+
apply_lock(name.to_sym, Lock.new(state: state, example: current_test_example))
|
|
168
180
|
end
|
|
169
181
|
|
|
182
|
+
# The tracking entry goes only once the store has unlocked the light, so
|
|
183
|
+
# a failed unlock (say, Redis briefly down) can be retried by
|
|
184
|
+
# #reset_locks!.
|
|
170
185
|
def unlock(name)
|
|
171
|
-
|
|
186
|
+
key = name.to_sym
|
|
187
|
+
light_for(key).unlock unless metrics_only?(key)
|
|
188
|
+
@locks.delete(key)
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# Lock +names+ to +state+; with a block, only for the block, then put
|
|
192
|
+
# each one back as it was, even if the block (or locking a later name)
|
|
193
|
+
# raises: relocked as an enclosing lock left it (so nested blocks don't
|
|
194
|
+
# cancel it), else unlocked. Returns the block's value.
|
|
195
|
+
def with_locks(names, state)
|
|
196
|
+
keys = names.map(&:to_sym)
|
|
197
|
+
unless block_given?
|
|
198
|
+
keys.each { |key| lock(key, state) }
|
|
199
|
+
return
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
prior = {}
|
|
203
|
+
begin
|
|
204
|
+
keys.each do |key|
|
|
205
|
+
prior[key] = @locks[key]
|
|
206
|
+
lock(key, state)
|
|
207
|
+
end
|
|
208
|
+
yield
|
|
209
|
+
ensure
|
|
210
|
+
prior.each { |key, lock| lock ? apply_lock(key, lock) : unlock(key) }
|
|
211
|
+
end
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
# Unlock every circuit this runner locked and has not unlocked since.
|
|
215
|
+
# Unlike #reset!, breaker state, forced states and the data store are
|
|
216
|
+
# left alone. With a Redis store, a lock another process made is not
|
|
217
|
+
# this runner's to undo.
|
|
218
|
+
def reset_locks!
|
|
219
|
+
@locks.keys.each { |name| unlock(name) }
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
# Names of the circuits locked through #lock and not yet unlocked.
|
|
223
|
+
def locked_circuits
|
|
224
|
+
@locks.keys
|
|
172
225
|
end
|
|
173
226
|
|
|
174
227
|
# Snapshot Hash of the current cached lights. Used by Health to discover
|
|
@@ -310,6 +363,36 @@ module StandardCircuit
|
|
|
310
363
|
@config.spec_for(name)&.metrics_only
|
|
311
364
|
end
|
|
312
365
|
|
|
366
|
+
def apply_lock(key, lock)
|
|
367
|
+
return if metrics_only?(key)
|
|
368
|
+
|
|
369
|
+
light_for(key).lock({ open: Stoplight::Color::RED, closed: Stoplight::Color::GREEN }.fetch(lock.state))
|
|
370
|
+
@locks[key] = lock
|
|
371
|
+
end
|
|
372
|
+
|
|
373
|
+
# A lock outlives the example that made it unless something clears it:
|
|
374
|
+
# the standard_circuit/rspec helper, StandardCircuit.reset! or
|
|
375
|
+
# reset_locks!, or the block form of lock_open!. Without one, a later
|
|
376
|
+
# example meets a breaker that is still locked, and fails for no reason
|
|
377
|
+
# it can see. Warn once per process when a call reaches a circuit locked
|
|
378
|
+
# by a different RSpec example.
|
|
379
|
+
def warn_if_lock_leaked(circuit)
|
|
380
|
+
return if @warned_leaked_lock
|
|
381
|
+
|
|
382
|
+
owner = @locks[circuit]&.example
|
|
383
|
+
return if owner.nil? || owner.equal?(current_test_example)
|
|
384
|
+
|
|
385
|
+
@warned_leaked_lock = true
|
|
386
|
+
warn "[StandardCircuit] #{circuit.inspect} is still locked by an earlier example " \
|
|
387
|
+
"(#{owner.respond_to?(:location) ? owner.location : owner}). Locks are not cleared between " \
|
|
388
|
+
"examples unless something clears them: require \"standard_circuit/rspec\" in your spec helper, " \
|
|
389
|
+
"call StandardCircuit.reset_locks! in an after hook, or pass lock_open! a block."
|
|
390
|
+
end
|
|
391
|
+
|
|
392
|
+
def current_test_example
|
|
393
|
+
::RSpec.current_example if defined?(::RSpec) && ::RSpec.respond_to?(:current_example)
|
|
394
|
+
end
|
|
395
|
+
|
|
313
396
|
# Stoplight's rule: skipped wins over tracked.
|
|
314
397
|
def tracked_error?(spec, error)
|
|
315
398
|
spec.skipped_errors.none? { |matcher| matcher === error } &&
|
data/lib/standard_circuit.rb
CHANGED
|
@@ -26,6 +26,7 @@ require "standard_circuit/dependency"
|
|
|
26
26
|
require "standard_circuit/health_row"
|
|
27
27
|
require "standard_circuit/health"
|
|
28
28
|
require "standard_circuit/runner"
|
|
29
|
+
require "standard_circuit/retry_wait"
|
|
29
30
|
require "standard_circuit/mailer/circuit_open_error"
|
|
30
31
|
require "standard_circuit/mailer/delivery_method"
|
|
31
32
|
require "standard_circuit/mailer/retry"
|
|
@@ -88,6 +89,16 @@ module StandardCircuit
|
|
|
88
89
|
config.dependency_specs.map { |spec| Dependency.new(spec, runner, config) }
|
|
89
90
|
end
|
|
90
91
|
|
|
92
|
+
# The `wait:` for a job retrying on an open circuit:
|
|
93
|
+
#
|
|
94
|
+
# retry_on Stoplight::Error::RedLight, wait: StandardCircuit.retry_wait(:stripe), attempts: 5
|
|
95
|
+
#
|
|
96
|
+
# Polynomial backoff floored at the longest cool-off behind +names+, plus
|
|
97
|
+
# jitter. See RetryWait.
|
|
98
|
+
def retry_wait(*names, jitter: nil)
|
|
99
|
+
RetryWait.build(names, jitter: jitter)
|
|
100
|
+
end
|
|
101
|
+
|
|
91
102
|
def force_open(name, &block)
|
|
92
103
|
runner.force_open(name, &block)
|
|
93
104
|
end
|
|
@@ -105,6 +116,17 @@ module StandardCircuit
|
|
|
105
116
|
stats.clear!
|
|
106
117
|
end
|
|
107
118
|
|
|
119
|
+
# Unlock every circuit locked through `dependency(name).lock_open!` /
|
|
120
|
+
# `lock_closed!` (or a purpose's) in this process and not unlocked since.
|
|
121
|
+
# For a test suite that doesn't load standard_circuit/rspec:
|
|
122
|
+
#
|
|
123
|
+
# config.after { StandardCircuit.reset_locks! }
|
|
124
|
+
#
|
|
125
|
+
# Breaker state, forced states and the data store are left alone.
|
|
126
|
+
def reset_locks!
|
|
127
|
+
runner.reset_locks!
|
|
128
|
+
end
|
|
129
|
+
|
|
108
130
|
# Breaker colors only, rolled up to :ok | :degraded | :critical. What
|
|
109
131
|
# standard_health < 0.10 folds into its aggregate tier as `circuits`.
|
|
110
132
|
# Superseded by `health_rows`; removed in 1.0 along with that fold-in.
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: standard_circuit
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.8.
|
|
4
|
+
version: 0.8.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Rarebit One
|
|
@@ -186,6 +186,7 @@ files:
|
|
|
186
186
|
- lib/standard_circuit/notifiers/metrics.rb
|
|
187
187
|
- lib/standard_circuit/notifiers/sentry.rb
|
|
188
188
|
- lib/standard_circuit/presets.rb
|
|
189
|
+
- lib/standard_circuit/retry_wait.rb
|
|
189
190
|
- lib/standard_circuit/rspec.rb
|
|
190
191
|
- lib/standard_circuit/runner.rb
|
|
191
192
|
- lib/standard_circuit/stats.rb
|