smart_retry 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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c5e73411f89b1989931a962cdb74265dec45dc2a0a0239f9129eb02fb476046a
4
+ data.tar.gz: 89d7614b764e99ffe1da6f11a4ec2c201185f313353d174ab503075167d87368
5
+ SHA512:
6
+ metadata.gz: 4bf95a913511190a7851feed2cc653f8d71f0333e92183732149ce9c3e2040c2a0922ec973b261488f3d1b59aceb3cb213a9b04b5f4b4bab2a22c084811beb7f
7
+ data.tar.gz: 6641c96647266bb667e9293475cbebb3e08beb7d50bacab18dd4e1ccd8e48029aa23ddb2e9c56b47ac0027a418f0b22dff2d4c725a882dbe34b44363fdefda7c
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-01-24
4
+
5
+ - Initial release
@@ -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) 2026 Mohammad Hifzan
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,82 @@
1
+ # SmartRetry
2
+
3
+ SmartRetry provides **robust retry and circuit breaker patterns** for Ruby and Rails applications. It helps your services recover from transient failures, avoid cascading outages, and gracefully handle sustained outages.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```ruby
10
+ gem "smart_retry"
11
+
12
+ base_delay = 2s, backoff = exponential
13
+
14
+ :full jitter → delay randomly chosen from 0..current_delay
15
+ :equal jitter → delay randomly in the second half of the current_delay
16
+
17
+
18
+ circuit_breaker.call do
19
+ retry_policy.call do
20
+ service.call
21
+ end
22
+ end
23
+
24
+
25
+ timeout_policy = SmartRetry::TimeoutPolicy.new(timeout: 5) # seconds
26
+
27
+ circuit_breaker = SmartRetry::CircuitBreaker.new(
28
+ failure_threshold: 3,
29
+ cooldown: 10,
30
+ half_open_requests: 1,
31
+ retry_policy: retry_policy,
32
+ timeout_policy: timeout_policy
33
+ )
34
+
35
+ retry_policy = SmartRetry::RetryPolicy.new(max_attempts: 3, sleep_fn: ->(_) {})
36
+ circuit_breaker = SmartRetry::CircuitBreaker.new(clock: -> { simulated_time })
37
+
38
+ require "smart_retry"
39
+
40
+ retry_policy = SmartRetry::RetryPolicy.new(
41
+ max_attempts: 3,
42
+ base_delay: 0.5,
43
+ jitter: :full
44
+ )
45
+
46
+ circuit_breaker = SmartRetry::CircuitBreaker.new(
47
+ failure_threshold: 2,
48
+ cooldown: 10,
49
+ half_open_requests: 1,
50
+ retry_policy: retry_policy
51
+ )
52
+
53
+ service = -> {
54
+ # simulate service call
55
+ raise "down" if rand < 0.5
56
+ "ok"
57
+ }
58
+
59
+ result = circuit_breaker.call do
60
+ retry_policy.call { service.call }
61
+ end
62
+
63
+ puts result # => "ok"
64
+
65
+ retry_policy = SmartRetry::RetryPolicy.new(max_attempts: 3, sleep_fn: ->(_) {})
66
+ circuit_breaker = SmartRetry::CircuitBreaker.new(clock: -> { simulated_time })
67
+
68
+ ┌───────────────────────────┐
69
+ │ CircuitBreaker │ ← protects the system
70
+ │ ┌───────────────────┐ │
71
+ │ │ RetryPolicy │ │ ← retries transient failures
72
+ │ │ ┌───────────┐ │ │
73
+ │ │ │ Service │ │ │
74
+ │ │ └───────────┘ │ │
75
+ │ └───────────────────┘ │
76
+ └───────────────────────────┘
77
+
78
+ ---
79
+
80
+ ## 8. Simulating a Production Outage
81
+
82
+ You can test SmartRetry behavior under a **sustained outage** scenario, including retries, circuit breaker transitions, and recovery.
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'monitor'
4
+ module SmartRetry
5
+ class CircuitBreaker
6
+ attr_reader :state, :failure_count
7
+
8
+ def initialize(
9
+ failure_threshold:,
10
+ cooldown:,
11
+ half_open_requests:,
12
+ retry_policy: nil,
13
+ timeout_policy: nil,
14
+ clock: -> { Time.now }
15
+ )
16
+ @failure_threshold = failure_threshold
17
+ @cooldown = cooldown
18
+ @half_open_requests = half_open_requests
19
+ @retry_policy = retry_policy
20
+ @timeout_policy = timeout_policy
21
+ @clock = clock
22
+
23
+ @state = :closed
24
+ @failure_count = 0
25
+ @opened_at = nil
26
+ @half_open_attempts = 0
27
+
28
+ @lock = Monitor.new
29
+ end
30
+
31
+ def call(&block)
32
+ # ---------
33
+ # Phase 1: permission + state transition
34
+ # ---------
35
+ @lock.synchronize do
36
+ transition_if_needed
37
+ enforce_call_permission
38
+ end
39
+
40
+ # ---------
41
+ # Phase 2: execute user code (NO LOCK)
42
+ # ---------
43
+ execute(&block)
44
+ end
45
+
46
+ def open? = @state == :open
47
+ def closed? = @state == :closed
48
+ def half_open? = @state == :half_open
49
+
50
+ private
51
+
52
+ # -------------------------
53
+ # State transitions
54
+ # -------------------------
55
+
56
+ def transition_if_needed
57
+ return unless @state == :open
58
+ return unless cooldown_elapsed?
59
+
60
+ @state = :half_open
61
+ @half_open_attempts = 0
62
+ end
63
+
64
+ # -------------------------
65
+ # Permission checks
66
+ # -------------------------
67
+
68
+ def enforce_call_permission
69
+ case @state
70
+ when :open
71
+ raise CircuitOpenError
72
+ when :half_open
73
+ raise CircuitOpenError if @half_open_attempts >= @half_open_requests
74
+
75
+ @half_open_attempts += 1
76
+ end
77
+ end
78
+
79
+ # -------------------------
80
+ # Execution
81
+ # -------------------------
82
+
83
+ def execute(&block)
84
+ wrapped = block
85
+ wrapped = wrap_with_timeout(wrapped)
86
+ wrapped = wrap_with_retry(wrapped)
87
+
88
+ wrapped.call.tap { on_success }
89
+ rescue StandardError => e
90
+ on_failure
91
+ raise e
92
+ end
93
+
94
+ # -------------------------
95
+ # Call results
96
+ # -------------------------
97
+
98
+ def on_success
99
+ @lock.synchronize do
100
+ case @state
101
+ when :half_open
102
+ close_circuit
103
+ when :closed
104
+ @failure_count = 0
105
+ end
106
+ end
107
+ end
108
+
109
+ def on_failure
110
+ @lock.synchronize do
111
+ case @state
112
+ when :closed
113
+ @failure_count += 1
114
+ open_circuit if @failure_count >= @failure_threshold
115
+ when :half_open
116
+ open_circuit
117
+ end
118
+ end
119
+ end
120
+
121
+ # -------------------------
122
+ # Helpers
123
+ # -------------------------
124
+
125
+ def open_circuit
126
+ @state = :open
127
+ @opened_at = @clock.call
128
+ @failure_count = 0
129
+ @half_open_attempts = 0
130
+ end
131
+
132
+ def close_circuit
133
+ @state = :closed
134
+ @opened_at = nil
135
+ @failure_count = 0
136
+ @half_open_attempts = 0
137
+ end
138
+
139
+ def cooldown_elapsed?
140
+ return false unless @opened_at
141
+
142
+ (@clock.call - @opened_at) >= @cooldown
143
+ end
144
+
145
+ def wrap_with_retry(block)
146
+ return block unless @retry_policy
147
+
148
+ -> { @retry_policy.call { block.call } }
149
+ end
150
+
151
+ def wrap_with_timeout(block)
152
+ return block unless @timeout_policy
153
+
154
+ -> { @timeout_policy.call { block.call } }
155
+ end
156
+ end
157
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SmartRetry
4
+ class Config
5
+ attr_accessor :clock
6
+
7
+ def initialize
8
+ @clock = -> { Time.now }
9
+ @services = {}
10
+ end
11
+
12
+ def default(&block)
13
+ service(:default, &block)
14
+ end
15
+
16
+ def service(name, &block)
17
+ @services[name.to_sym] ||= ServiceConfig.new
18
+ block.call(@services[name.to_sym])
19
+ end
20
+
21
+ def fetch(name)
22
+ @services[name.to_sym] || @services[:default]
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SmartRetry
4
+ class Error < StandardError; end
5
+ class CircuitOpenError < Error; end
6
+ class MaxRetriesExceededError < Error; end
7
+ class ConfigurationError < Error; end
8
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SmartRetry
4
+ module Notifier
5
+ @subscribers = []
6
+
7
+ def self.subscribe(&block)
8
+ @subscribers << block
9
+ end
10
+
11
+ def self.publish(event)
12
+ @subscribers.each { |s| s.call(event) }
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SmartRetry
4
+ class RetryPolicy
5
+ def initialize(
6
+ max_attempts:,
7
+ base_delay: 0.1,
8
+ max_delay: 5,
9
+ backoff: :exponential,
10
+ retry_on: [StandardError],
11
+ jitter: :none,
12
+ sleep_fn: ->(seconds) { sleep(seconds) }
13
+ )
14
+ @max_attempts = max_attempts
15
+ @base_delay = base_delay
16
+ @max_delay = max_delay
17
+ @backoff = backoff
18
+ @retry_on = Array(retry_on)
19
+ @jitter = jitter
20
+ @sleep_fn = sleep_fn
21
+ end
22
+
23
+ def call
24
+ attempts = 0
25
+
26
+ begin
27
+ attempts += 1
28
+ yield
29
+ rescue StandardError => e
30
+ raise e unless retryable?(e)
31
+ raise e if attempts >= @max_attempts
32
+
33
+ delay = compute_delay(attempts)
34
+ delay = apply_jitter(delay)
35
+ @sleep_fn.call(delay)
36
+ retry
37
+ end
38
+ end
39
+
40
+ private
41
+
42
+ def retryable?(error)
43
+ @retry_on.any? { |klass| error.is_a?(klass) }
44
+ end
45
+
46
+ def apply_jitter(delay)
47
+ case @jitter
48
+ when :full
49
+ rand(0.0..delay)
50
+ when :equal
51
+ (delay / 2) + rand(0.0..(delay / 2))
52
+ else
53
+ delay
54
+ end
55
+ end
56
+
57
+ def compute_delay(attempt)
58
+ delay =
59
+ case @backoff
60
+ when :exponential
61
+ @base_delay * (2**(attempt - 1))
62
+ when :linear
63
+ @base_delay * attempt
64
+ else
65
+ @base_delay
66
+ end
67
+
68
+ [delay, @max_delay].min
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SmartRetry
4
+ class ServiceRegistry
5
+ def self.fetch(name)
6
+ Service.new(name)
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'timeout'
4
+
5
+ module SmartRetry
6
+ class TimeoutError < StandardError; end
7
+
8
+ class TimeoutPolicy
9
+ def initialize(timeout:)
10
+ @timeout = timeout
11
+ end
12
+
13
+ def call(&block)
14
+ Timeout.timeout(@timeout, TimeoutError, &block)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SmartRetry
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'smart_retry/version'
4
+ require_relative 'smart_retry/config'
5
+ require_relative 'smart_retry/service_registry'
6
+ require_relative 'smart_retry/retry_policy'
7
+ require_relative 'smart_retry/circuit_breaker'
8
+ require_relative 'smart_retry/notifier'
9
+ require_relative 'smart_retry/errors'
10
+
11
+ module SmartRetry
12
+ class << self
13
+ def configure
14
+ yield(config)
15
+ end
16
+
17
+ def config
18
+ @config ||= Config.new
19
+ end
20
+
21
+ def call(service, &block)
22
+ ServiceRegistry.fetch(service).call(&block)
23
+ end
24
+
25
+ def subscribe(&block)
26
+ Notifier.subscribe(&block)
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,4 @@
1
+ module SmartRetry
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,64 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: smart_retry
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mohammad Hifzan
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2026-01-26 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: SmartRetry provides configurable retry policies with exponential backoff
14
+ and a circuit breaker to protect Ruby and Rails applications from unreliable external
15
+ services.
16
+ email:
17
+ - hifzan743@gmail.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - CHANGELOG.md
23
+ - CODE_OF_CONDUCT.md
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - lib/smart_retry.rb
28
+ - lib/smart_retry/circuit_breaker.rb
29
+ - lib/smart_retry/config.rb
30
+ - lib/smart_retry/errors.rb
31
+ - lib/smart_retry/notifier.rb
32
+ - lib/smart_retry/retry_policy.rb
33
+ - lib/smart_retry/service_registry.rb
34
+ - lib/smart_retry/timeout_policy.rb
35
+ - lib/smart_retry/version.rb
36
+ - sig/smart_retry.rbs
37
+ homepage: https://gitlab.com/Hifzan/smart_retry.git
38
+ licenses:
39
+ - MIT
40
+ metadata:
41
+ homepage_uri: https://gitlab.com/Hifzan/smart_retry.git
42
+ source_code_uri: https://gitlab.com/Hifzan/smart_retry.git
43
+ changelog_uri: https://gitlab.com/Hifzan/smart_retry.git/-/blob/main/CHANGELOG.md
44
+ rubygems_mfa_required: 'true'
45
+ post_install_message:
46
+ rdoc_options: []
47
+ require_paths:
48
+ - lib
49
+ required_ruby_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: 3.2.0
54
+ required_rubygems_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: '0'
59
+ requirements: []
60
+ rubygems_version: 3.4.19
61
+ signing_key:
62
+ specification_version: 4
63
+ summary: Smart retry and circuit breaker for Ruby and Rails
64
+ test_files: []