minimalist_circuit_breaker 0.1.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 +7 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +114 -0
- data/Rakefile +12 -0
- data/lib/minimalist_circuit_breaker/circuit_breaker.rb +174 -0
- data/lib/minimalist_circuit_breaker/circuit_errors.rb +9 -0
- data/lib/minimalist_circuit_breaker/version.rb +5 -0
- data/lib/minimalist_circuit_breaker.rb +7 -0
- data/sig/simple_circuit_breaker.rbs +4 -0
- metadata +54 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 7b39c4d9661b458a36db6d8780996d50e24a9bfb69a4b54ff6404d7b517a2476
|
|
4
|
+
data.tar.gz: ac5527ffe453c20f3336f1a519fb71860a8a7201b91836d24b3335b7c4316a2e
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 61e25c691e33da9cb82b953aaad5426347765cc62481c0c59be03e6a2d9955ba5f2f495f566cc0730975e0124794c1c6b5adb4323a1dec773fd5446bce51acf2
|
|
7
|
+
data.tar.gz: bcde292ccf30b65934f74576e53ce20d69c7840d358d7cfd866303083f3b1e2a8ea6eff1475eec8fa30ab8137779954cf751b60c88bf64c801c66f143bad286e
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
|
2
|
+
|
|
3
|
+
## Our Pledge
|
|
4
|
+
|
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
|
10
|
+
identity and orientation.
|
|
11
|
+
|
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
13
|
+
diverse, inclusive, and healthy community.
|
|
14
|
+
|
|
15
|
+
## Our Standards
|
|
16
|
+
|
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
|
18
|
+
community include:
|
|
19
|
+
|
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
|
24
|
+
and learning from the experience
|
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
|
26
|
+
community
|
|
27
|
+
|
|
28
|
+
Examples of unacceptable behavior include:
|
|
29
|
+
|
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
|
31
|
+
any kind
|
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
33
|
+
* Public or private harassment
|
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
|
35
|
+
without their explicit permission
|
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
|
37
|
+
professional setting
|
|
38
|
+
|
|
39
|
+
## Enforcement Responsibilities
|
|
40
|
+
|
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
44
|
+
or harmful.
|
|
45
|
+
|
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
49
|
+
decisions when appropriate.
|
|
50
|
+
|
|
51
|
+
## Scope
|
|
52
|
+
|
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
|
54
|
+
an individual is officially representing the community in public spaces.
|
|
55
|
+
Examples of representing our community include using an official email address,
|
|
56
|
+
posting via an official social media account, or acting as an appointed
|
|
57
|
+
representative at an online or offline event.
|
|
58
|
+
|
|
59
|
+
## Enforcement
|
|
60
|
+
|
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
62
|
+
reported to the community leaders responsible for enforcement at
|
|
63
|
+
[INSERT CONTACT METHOD].
|
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
|
65
|
+
|
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
|
67
|
+
reporter of any incident.
|
|
68
|
+
|
|
69
|
+
## Enforcement Guidelines
|
|
70
|
+
|
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
|
73
|
+
|
|
74
|
+
### 1. Correction
|
|
75
|
+
|
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
77
|
+
unprofessional or unwelcome in the community.
|
|
78
|
+
|
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
|
82
|
+
|
|
83
|
+
### 2. Warning
|
|
84
|
+
|
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
|
86
|
+
actions.
|
|
87
|
+
|
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
|
93
|
+
ban.
|
|
94
|
+
|
|
95
|
+
### 3. Temporary Ban
|
|
96
|
+
|
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
|
98
|
+
sustained inappropriate behavior.
|
|
99
|
+
|
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
|
101
|
+
communication with the community for a specified period of time. No public or
|
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
|
104
|
+
Violating these terms may lead to a permanent ban.
|
|
105
|
+
|
|
106
|
+
### 4. Permanent Ban
|
|
107
|
+
|
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
|
111
|
+
|
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
|
113
|
+
community.
|
|
114
|
+
|
|
115
|
+
## Attribution
|
|
116
|
+
|
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
118
|
+
version 2.1, available at
|
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
|
120
|
+
|
|
121
|
+
Community Impact Guidelines were inspired by
|
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
|
123
|
+
|
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
|
127
|
+
|
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Aria Diniz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# MinimalistCircuitBreaker
|
|
2
|
+
|
|
3
|
+
A lightweight, thread-safe implementation of the Circuit Breaker pattern for Ruby.
|
|
4
|
+
|
|
5
|
+
`MinimalistCircuitBreaker` protects your system from cascading failures by wrapping external service calls (like HTTP requests or database queries). It monitors success/failure rates and temporarily "opens the circuit" (blocking execution) when failures exceed a configured threshold, allowing the failing service time to recover.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
Install the gem and add to the application's Gemfile by executing:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bundle add minimalist_circuit_breaker
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
If bundler is not being used to manage dependencies, install the gem by executing:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
gem install minimalist_circuit_breaker
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
### Basic Usage
|
|
24
|
+
|
|
25
|
+
Instantiate the circuit breaker and wrap your risky calls inside the `call` block. The block *must* return a `[status, result]` tuple, where `status` is an Integer (like an HTTP status code) or `nil`.
|
|
26
|
+
|
|
27
|
+
```ruby
|
|
28
|
+
require 'minimalist_circuit_breaker'
|
|
29
|
+
|
|
30
|
+
# 1. Initialize with default settings
|
|
31
|
+
cb = MinimalistCircuitBreaker::CircuitBreaker.new
|
|
32
|
+
|
|
33
|
+
# 2. Wrap your external calls
|
|
34
|
+
begin
|
|
35
|
+
status, body = cb.call do
|
|
36
|
+
# Perform your external request here
|
|
37
|
+
response = Net::HTTP.get_response(URI('[http://example.com](http://example.com)'))
|
|
38
|
+
|
|
39
|
+
# Return [Integer Status, Object Result]
|
|
40
|
+
[response.code.to_i, response.body]
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
puts "Success: #{status}"
|
|
44
|
+
|
|
45
|
+
rescue MinimalistCircuitBreaker::OpenCircuitError
|
|
46
|
+
# Circuit is open; fallback logic goes here
|
|
47
|
+
puts "Service unavailable (Circuit Open)"
|
|
48
|
+
rescue MinimalistCircuitBreaker::HalfOpenCircuitError
|
|
49
|
+
# Circuit is testing the connection; handle gracefully
|
|
50
|
+
puts "Service unavailable (Throttled)"
|
|
51
|
+
end
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Configuration
|
|
55
|
+
|
|
56
|
+
You can customize the failure thresholds, timeouts, and ignored errors when initializing the breaker.
|
|
57
|
+
|
|
58
|
+
```ruby
|
|
59
|
+
cb = MinimalistCircuitBreaker::CircuitBreaker.new(
|
|
60
|
+
min_failures_before_open: 5, # Minimum failures before checking percentage (default: 10)
|
|
61
|
+
failures_pct: 0.2, # Open if > 20% fail (default: 0.5)
|
|
62
|
+
time_window: 60, # Rolling stats window in seconds (default: 30)
|
|
63
|
+
timeout: 10, # Seconds to wait before testing Half-Open (default: 30)
|
|
64
|
+
codes_to_ignore: [404, 422], # Treat these HTTP codes as "Success"
|
|
65
|
+
window_size: 100 # Max requests to keep in memory (default: 50)
|
|
66
|
+
)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Custom Error Messages
|
|
70
|
+
|
|
71
|
+
You can override the default exceptions and messages. This is useful if you want to integrate with your application's specific error handling classes.
|
|
72
|
+
|
|
73
|
+
```ruby
|
|
74
|
+
cb = MinimalistCircuitBreaker::CircuitBreaker.new(
|
|
75
|
+
open_error: MyCustomError,
|
|
76
|
+
open_message: "External payment gateway is down",
|
|
77
|
+
half_open_error: MyCustomError,
|
|
78
|
+
half_open_message: "Gateway is recovering, please wait"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### How it Works
|
|
84
|
+
|
|
85
|
+
1. **Closed State:** Requests flow normally. Successes and failures are recorded in a sliding window.
|
|
86
|
+
2. **Open State:** If the failure rate exceeds `failures_pct` (and `min_failures_before_open` is met), the circuit opens. All subsequent calls immediately raise `MinimalistCircuitBreaker::OpenCircuitError` without executing the block.
|
|
87
|
+
3. **Half-Open State:** After `timeout` seconds, the circuit transitions to Half-Open. It allows **one** request to pass through:
|
|
88
|
+
* **Success:** Circuit closes and resets stats.
|
|
89
|
+
* **Failure:** Circuit opens again and resets the timeout timer.
|
|
90
|
+
|
|
91
|
+
### Thread Safety
|
|
92
|
+
|
|
93
|
+
This gem is thread-safe.
|
|
94
|
+
|
|
95
|
+
* **I/O is Non-Blocking:** The potentially slow block execution happens *outside* the mutex lock. Multiple threads can make HTTP requests simultaneously.
|
|
96
|
+
* **State is Consistent:** State transitions and registry updates are strictly synchronized.
|
|
97
|
+
|
|
98
|
+
## Development
|
|
99
|
+
|
|
100
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
|
101
|
+
|
|
102
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
|
103
|
+
|
|
104
|
+
## Contributing
|
|
105
|
+
|
|
106
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/ariasdiniz/minimalist_circuit_breaker. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/ariasdiniz/minimalist_circuit_breaker/blob/main/CODE_OF_CONDUCT.md).
|
|
107
|
+
|
|
108
|
+
## License
|
|
109
|
+
|
|
110
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
|
111
|
+
|
|
112
|
+
## Code of Conduct
|
|
113
|
+
|
|
114
|
+
Everyone interacting in the MinimalistCircuitBreaker project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ariasdiniz/minimalist_circuit_breaker/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative 'circuit_errors'
|
|
4
|
+
|
|
5
|
+
module MinimalistCircuitBreaker; end
|
|
6
|
+
|
|
7
|
+
# A thread-safe implementation of the Circuit Breaker pattern.
|
|
8
|
+
#
|
|
9
|
+
# This class protects your system from cascading failures by wrapping external service calls.
|
|
10
|
+
# It monitors the success/failure rates of these calls and temporarily stops execution ("opens the circuit")
|
|
11
|
+
# when the failure rate exceeds a configured threshold.
|
|
12
|
+
#
|
|
13
|
+
# The circuit breaker cycles through three states:
|
|
14
|
+
# * **:closed** - Normal operation. Requests are executed.
|
|
15
|
+
# * **:open** - Failure threshold reached. Requests raise {OpenCircuitError} immediately without execution.
|
|
16
|
+
# * **:half_open** - Timeout period elapsed. A single "test" request is allowed through.
|
|
17
|
+
# * If successful, the circuit returns to **:closed**.
|
|
18
|
+
# * If it fails, the circuit returns to **:open**.
|
|
19
|
+
#
|
|
20
|
+
# @example Basic Usage
|
|
21
|
+
# cb = MinimalistCircuitBreaker::CircuitBreaker.new(
|
|
22
|
+
# min_failures_before_open: 5,
|
|
23
|
+
# failures_pct: 0.5,
|
|
24
|
+
# timeout: 60
|
|
25
|
+
# )
|
|
26
|
+
#
|
|
27
|
+
# result = cb.call do
|
|
28
|
+
# Net::HTTP.get(URI('http://example.com'))
|
|
29
|
+
# end
|
|
30
|
+
#
|
|
31
|
+
class MinimalistCircuitBreaker::CircuitBreaker
|
|
32
|
+
# @return [Symbol] The current state of the circuit breaker (:closed, :open, or :half_open).
|
|
33
|
+
attr_reader :state
|
|
34
|
+
|
|
35
|
+
# Initializes a new CircuitBreaker instance.
|
|
36
|
+
#
|
|
37
|
+
# @param min_failures_before_open [Integer] The minimum number of failed requests required before the circuit can trip.
|
|
38
|
+
# This prevents the circuit from opening on a single failure if the volume is low. Default is 10.
|
|
39
|
+
# @param failures_pct [Float] The failure rate threshold (0.0 to 1.0) required to trip the circuit.
|
|
40
|
+
# For example, 0.5 means 50% failures. Default is 0.5.
|
|
41
|
+
# @param time_window [Integer] The rolling time window in seconds. Failures older than this window
|
|
42
|
+
# are discarded from the statistics calculation. Default is 30 seconds.
|
|
43
|
+
# @param timeout [Integer] The duration in seconds the circuit remains **:open** before transitioning
|
|
44
|
+
# to **:half_open** to test the connection. Default is 30 seconds.
|
|
45
|
+
# @param codes_to_ignore [Array<Integer>] A list of HTTP status codes (or integer return values)
|
|
46
|
+
# that should be treated as successes (e.g., 404 Not Found might be a valid business result).
|
|
47
|
+
# @param customize [Hash] specific error classes and messages.
|
|
48
|
+
# @option customize [Class] :half_open_error The exception class to raise when the circuit is half-open.
|
|
49
|
+
# @option customize [String] :half_open_message The error message for half-open exceptions.
|
|
50
|
+
# @option customize [Class] :open_error The exception class to raise when the circuit is open.
|
|
51
|
+
# @option customize [String] :open_message The error message for open exceptions.
|
|
52
|
+
# @option customize [Integer] :window_size The maximum number of request results to keep in the registry
|
|
53
|
+
# before dropping the oldest (Sliding Window size). Default is 50.
|
|
54
|
+
def initialize(
|
|
55
|
+
min_failures_before_open: 10,
|
|
56
|
+
failures_pct: 0.5,
|
|
57
|
+
time_window: 30,
|
|
58
|
+
timeout: 30,
|
|
59
|
+
codes_to_ignore: [],
|
|
60
|
+
**customize
|
|
61
|
+
)
|
|
62
|
+
@state = :closed
|
|
63
|
+
@time_window = time_window
|
|
64
|
+
@failures_before_open = min_failures_before_open
|
|
65
|
+
@failures_pct = failures_pct
|
|
66
|
+
@ignored_codes = codes_to_ignore
|
|
67
|
+
@registry = []
|
|
68
|
+
@state_mutex = Mutex.new
|
|
69
|
+
@timeout = timeout
|
|
70
|
+
@last_timeout = nil
|
|
71
|
+
@half_open_error = customize[:half_open_error] || MinimalistCircuitBreaker::HalfOpenCircuitError
|
|
72
|
+
@half_open_message = customize[:half_open_message] || 'Circuit is half open and handling another request'
|
|
73
|
+
@open_error = customize[:open_error] || MinimalistCircuitBreaker::OpenCircuitError
|
|
74
|
+
@open_message = customize[:open_message] || 'Circuit is open'
|
|
75
|
+
@window_size = customize[:window_size] || 50
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Executes the provided block within the protection of the circuit breaker.
|
|
79
|
+
#
|
|
80
|
+
# If the circuit is **:closed**, the block is executed.
|
|
81
|
+
# If the circuit is **:open**, an {OpenCircuitError} is raised immediately.
|
|
82
|
+
# If the circuit is **:half_open**, only one thread is allowed to execute the block as a test probe.
|
|
83
|
+
#
|
|
84
|
+
# The method captures exceptions raised within the block to update the internal circuit health metrics,
|
|
85
|
+
# then re-raises the original exception to the caller.
|
|
86
|
+
#
|
|
87
|
+
# @yieldparam args [Array] Any arguments passed to #call are forwarded to the block.
|
|
88
|
+
# @yieldreturn [Array<Integer, Object>] The block is expected to return a tuple of `[status, response]`,
|
|
89
|
+
# where `status` is an Integer (e.g., HTTP status code) used to determine success/failure.
|
|
90
|
+
#
|
|
91
|
+
# @return [Array<Integer, Object>] The result returned by the block.
|
|
92
|
+
#
|
|
93
|
+
# @raise [MinimalistCircuitBreaker::OpenCircuitError] If the circuit is currently open.
|
|
94
|
+
# @raise [MinimalistCircuitBreaker::HalfOpenCircuitError] If the circuit is half-open and handling another request.
|
|
95
|
+
# @raise [StandardError] Re-raises any exception that occurs during the block execution.
|
|
96
|
+
def call(*args)
|
|
97
|
+
return nil unless block_given?
|
|
98
|
+
|
|
99
|
+
call_status_check
|
|
100
|
+
|
|
101
|
+
begin
|
|
102
|
+
status, response = yield(*args)
|
|
103
|
+
rescue StandardError => e
|
|
104
|
+
execution_error = e
|
|
105
|
+
status = nil
|
|
106
|
+
response = nil
|
|
107
|
+
ensure
|
|
108
|
+
update_state(status)
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
raise execution_error if execution_error
|
|
112
|
+
|
|
113
|
+
[status, response]
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
private
|
|
117
|
+
|
|
118
|
+
def call_status_check
|
|
119
|
+
@state_mutex.synchronize do
|
|
120
|
+
raise @half_open_error, @half_open_message if check_state == :half_open
|
|
121
|
+
raise @open_error, @open_message if check_state == :open && Time.now - check_last_timeout < @timeout
|
|
122
|
+
|
|
123
|
+
set_state(state: :half_open) if check_state == :open
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def update_state(status)
|
|
128
|
+
@state_mutex.synchronize do
|
|
129
|
+
if (!status.nil? && status.to_i < 400) || @ignored_codes.include?(status.to_i)
|
|
130
|
+
set_state(state: :closed)
|
|
131
|
+
register_call
|
|
132
|
+
else
|
|
133
|
+
register_call(success: false)
|
|
134
|
+
evaluate_state
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def register_call(success: true)
|
|
140
|
+
@registry.push({ success: success, tstamp: Time.now })
|
|
141
|
+
@registry.shift if @registry.length > @window_size
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def evaluate_state
|
|
145
|
+
if check_state == :half_open
|
|
146
|
+
set_state(state: :open, update_timeout: true)
|
|
147
|
+
return
|
|
148
|
+
end
|
|
149
|
+
return if check_state == :open
|
|
150
|
+
|
|
151
|
+
success_count, len = filter_registry
|
|
152
|
+
should_open = success_count.to_f / len < 1 - @failures_pct && len - success_count > @failures_before_open
|
|
153
|
+
return unless should_open
|
|
154
|
+
|
|
155
|
+
set_state(state: :open, update_timeout: true)
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def check_last_timeout = @last_timeout
|
|
159
|
+
|
|
160
|
+
def check_state = @state
|
|
161
|
+
|
|
162
|
+
def set_state(state: :closed, update_timeout: false)
|
|
163
|
+
@state = state
|
|
164
|
+
@last_timeout = Time.now if update_timeout
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def filter_registry
|
|
168
|
+
now = Time.now
|
|
169
|
+
@registry.filter! { |r| now - r[:tstamp] < @time_window }
|
|
170
|
+
success_count = @registry.filter { |r| r[:success] }.length
|
|
171
|
+
len = @registry.length
|
|
172
|
+
[success_count, len]
|
|
173
|
+
end
|
|
174
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: minimalist_circuit_breaker
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Aria Diniz
|
|
8
|
+
bindir: exe
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: This gem is a very minimalist circuit breaker for Ruby, designed just
|
|
13
|
+
as a test side project.
|
|
14
|
+
email:
|
|
15
|
+
- aria.diniz.dev@gmail.com
|
|
16
|
+
executables: []
|
|
17
|
+
extensions: []
|
|
18
|
+
extra_rdoc_files: []
|
|
19
|
+
files:
|
|
20
|
+
- CHANGELOG.md
|
|
21
|
+
- CODE_OF_CONDUCT.md
|
|
22
|
+
- LICENSE.txt
|
|
23
|
+
- README.md
|
|
24
|
+
- Rakefile
|
|
25
|
+
- lib/minimalist_circuit_breaker.rb
|
|
26
|
+
- lib/minimalist_circuit_breaker/circuit_breaker.rb
|
|
27
|
+
- lib/minimalist_circuit_breaker/circuit_errors.rb
|
|
28
|
+
- lib/minimalist_circuit_breaker/version.rb
|
|
29
|
+
- sig/simple_circuit_breaker.rbs
|
|
30
|
+
homepage: https://github.com/ariasdiniz/minimalist_circuit_breaker
|
|
31
|
+
licenses:
|
|
32
|
+
- MIT
|
|
33
|
+
metadata:
|
|
34
|
+
homepage_uri: https://github.com/ariasdiniz/minimalist_circuit_breaker
|
|
35
|
+
source_code_uri: https://github.com/ariasdiniz/minimalist_circuit_breaker
|
|
36
|
+
changelog_uri: https://github.com/ariasdiniz/minimalist_circuit_breaker
|
|
37
|
+
rdoc_options: []
|
|
38
|
+
require_paths:
|
|
39
|
+
- lib
|
|
40
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
41
|
+
requirements:
|
|
42
|
+
- - ">="
|
|
43
|
+
- !ruby/object:Gem::Version
|
|
44
|
+
version: 3.2.0
|
|
45
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
46
|
+
requirements:
|
|
47
|
+
- - ">="
|
|
48
|
+
- !ruby/object:Gem::Version
|
|
49
|
+
version: '0'
|
|
50
|
+
requirements: []
|
|
51
|
+
rubygems_version: 3.7.2
|
|
52
|
+
specification_version: 4
|
|
53
|
+
summary: A Minimalist Circuit Breaker for Ruby
|
|
54
|
+
test_files: []
|