rcb 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 61b7b710d6681c43cbe7b7d538d0eeda7199ee7e7c892e3aa2b0ddd1455a5a08
4
+ data.tar.gz: 18449ecc9021e6dace52a8b07834544564234d1fe06170d81830a0c36aca5021
5
+ SHA512:
6
+ metadata.gz: 263813bdacad4713d2cf411aa6f5caae798166290142e96aabce52c2b1bd95220fd008fbbd46188afd3f59834c58edcacc43d0537865cd0e7e0b90260829966f
7
+ data.tar.gz: 95c4afc987cef799fbf40dbb29bbcaf08a94110d5b7996d076560951430975894bb2f35fa29a69b1cc24a6022ca54ff25f4587ff39e0d7b525cfff055651f67a
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at violethero0820@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in rcb.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "minitest", "~> 5.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 petitviolet
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,95 @@
1
+ # Rcb - Ruby Circuit Breaker
2
+
3
+ [Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html) implementation for/by Ruby.
4
+ CircuitBreaker is a great pattern to build robust system consists of bunch of microservices.
5
+
6
+ - Close
7
+ - A operational state
8
+ - Open
9
+ - A not operational state
10
+ - Half Open
11
+ - On the way of it's state to Close from Open.
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem 'rcb'
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ $ bundle install
24
+
25
+ Or install it yourself as:
26
+
27
+ $ gem install rcb
28
+
29
+ ## Usage
30
+
31
+ ### Import
32
+
33
+ To use rcb, insert this line:
34
+
35
+ ```ruby
36
+ require 'rcb'
37
+ ```
38
+
39
+ ### Configuration
40
+
41
+ Add configuration with specifying `tag` like:
42
+
43
+ ```ruby
44
+ Rcb.configure('fooo.com') do |config|
45
+ config.max_failure_count 1
46
+ config.reset_timeout_msec 100
47
+ end
48
+
49
+ Rcb.configure('hoge.com') do |config|
50
+ config.max_failure_count 3
51
+ config.reset_timeout_msec 300
52
+ end
53
+ ```
54
+
55
+ These configurations are for both 'fooo.com' and 'hoge.com'.
56
+
57
+ - `max_failure_count`: a threshold for execution failures.
58
+ - if the breaker reaches the given `max_failure_count`, enters Open state from Close
59
+ - `reset_timeout_msec`: milliseconds to wait for next try
60
+ - after the given `reset_timeout_msec`, the circuit breaker enters a Half-Open state from Open
61
+
62
+ ### Apply circuit breaker to executions
63
+
64
+ Pass a block to a method `Rcb::Instance#run!` to apply circuit-breaker to a execution.
65
+
66
+ ```ruby
67
+ Rcb.for('example.com').run! do # pass a block
68
+ if rand(2) == 0
69
+ raise 'fail!'
70
+ else
71
+ true
72
+ end
73
+ end
74
+ ```
75
+
76
+ You can see more example in [tests](./test).
77
+
78
+ ## Development
79
+
80
+ 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.
81
+
82
+ 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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
83
+
84
+ ## Contributing
85
+
86
+ Bug reports and pull requests are welcome on GitHub at https://github.com/petitviolet/rcb. 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/petitviolet/rcb/blob/master/CODE_OF_CONDUCT.md).
87
+
88
+
89
+ ## License
90
+
91
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
92
+
93
+ ## Code of Conduct
94
+
95
+ Everyone interacting in the Rcb project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/petitviolet/rcb/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rcb"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,77 @@
1
+ require 'logger'
2
+
3
+ module Rcb
4
+ Config = Struct.new(:tag, :max_failure_count, :reset_timeout_msec)do
5
+ MAX_FAILURE_COUNT = 0.freeze
6
+ RESET_TIMEOUT_MSEC = 0.freeze
7
+
8
+ @logger = Logger.new($stderr)
9
+
10
+ def self.create(tag, max_failure_count: nil, reset_timeout_msec: nil)
11
+ raise 'Rcb tag must not be nil' if tag.nil?
12
+
13
+ if max_failure_count.nil? && reset_timeout_msec.nil?
14
+ @logger.warn("Rcb for '#{tag}' is not configured!")
15
+ end
16
+
17
+ Config.new(
18
+ tag.to_s.to_sym,
19
+ max_failure_count || MAX_FAILURE_COUNT,
20
+ reset_timeout_msec || RESET_TIMEOUT_MSEC
21
+ )
22
+ end
23
+ end
24
+
25
+ class ConfigBuilder
26
+ def initialize(tag)
27
+ @tag = tag
28
+ @max_failure_count = nil
29
+ @reset_timeout_msec = nil
30
+ end
31
+
32
+ def max_failure_count(num)
33
+ @max_failure_count = num
34
+ end
35
+
36
+ def reset_timeout_msec(msec)
37
+ @reset_timeout_msec = msec
38
+ end
39
+
40
+ def build
41
+ Config.create(
42
+ @tag,
43
+ max_failure_count:@max_failure_count,
44
+ reset_timeout_msec: @reset_timeout_msec
45
+ ).freeze
46
+ end
47
+ end
48
+
49
+ def Rcb.configure(tag, &block)
50
+ c = ConfigBuilder.new(tag.to_s.to_sym)
51
+ .tap { |cb| block.call(cb) }
52
+ .build
53
+
54
+ Configurations.add(c)
55
+ end
56
+
57
+ module Configurations
58
+ @configs = {}
59
+
60
+ def self.for(tag, max_failure_count: nil, reset_timeout_msec: nil)
61
+ @configs[tag.to_s.to_sym] || Config.create(tag,
62
+ max_failure_count: max_failure_count,
63
+ reset_timeout_msec: reset_timeout_msec)
64
+ end
65
+
66
+ def self.add(config)
67
+ # return if @configs.include?(config.tag)
68
+ # overwrite
69
+ @configs[config.tag] = config
70
+ end
71
+
72
+ def self.clear
73
+ @configs = {}
74
+ end
75
+ end
76
+
77
+ end
data/lib/rcb/error.rb ADDED
@@ -0,0 +1,7 @@
1
+ module Rcb
2
+ class CircuitBreakerOpenError < RuntimeError
3
+ def initialize(tag, since)
4
+ super(msg = "CircuitBreaker for '#{tag}' is open since #{since}")
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,65 @@
1
+ require 'byebug'
2
+ require 'rstructural'
3
+ require_relative './state'
4
+ require_relative './configuration'
5
+ require_relative './error'
6
+
7
+ module Rcb
8
+ class Instance
9
+ attr_reader :config
10
+
11
+ # @param config [Rcb::Config]
12
+ def initialize(config)
13
+ @config = config
14
+ end
15
+
16
+ def run!(&block)
17
+ result =
18
+ case States.of(config.tag)
19
+ in State::Close => s
20
+ s.run(config, &block)
21
+ in State::Open => s
22
+ s.run(config, &block)
23
+ in s
24
+ raise "Unknown state: #{s}"
25
+ end
26
+
27
+ case result
28
+ in Result::Ok[state, result]
29
+ States.update(config.tag, state)
30
+ return result
31
+ in Result::Ng[state, error]
32
+ States.update(config.tag, state)
33
+ raise error
34
+ end
35
+ end
36
+
37
+ def state
38
+ States.show(config)
39
+ end
40
+
41
+ end
42
+
43
+ private
44
+
45
+ class States
46
+ @states = {}
47
+
48
+ def self.show(config)
49
+ self.of(config.tag).state(config)
50
+ end
51
+
52
+ def self.of(tag)
53
+ @states[tag.to_sym] ||= State::Close.create
54
+ end
55
+
56
+ def self.update(tag, state)
57
+ @states[tag] = state
58
+ end
59
+
60
+ def self.clear
61
+ @states = {}
62
+ end
63
+ end
64
+
65
+ end
data/lib/rcb/result.rb ADDED
@@ -0,0 +1,10 @@
1
+ require 'rstructural'
2
+
3
+ module Rcb
4
+ module Result
5
+ extend ADT
6
+
7
+ Ok = data :new_state, :result
8
+ Ng = data :new_state, :error
9
+ end
10
+ end
data/lib/rcb/state.rb ADDED
@@ -0,0 +1,79 @@
1
+ require 'rstructural'
2
+ require_relative './result'
3
+ require_relative './error'
4
+
5
+ module Rcb::State
6
+ extend ADT
7
+
8
+ Close = data :failure_count do
9
+ def self.create(failure_count = 0)
10
+ new(failure_count)
11
+ end
12
+
13
+ def run(config, &block)
14
+ case try_call(&block)
15
+ in Either::Right[result]
16
+ Rcb::Result::Ok.new(self, result)
17
+ in Either::Left[e]
18
+ if config.max_failure_count > failure_count
19
+ Rcb::Result::Ng.new(Close.create(failure_count + 1), e)
20
+ else
21
+ Rcb::Result::Ng.new(Open.create, e)
22
+ end
23
+ end
24
+ end
25
+ end
26
+
27
+ Open = data :since do
28
+ def self.create
29
+ new(Time.now.utc)
30
+ end
31
+
32
+ def run(config, now: Time.now.utc, &block)
33
+ if half_open?(now, config.reset_timeout_msec)
34
+ HalfOpen.run(&block)
35
+ else
36
+ Rcb::Result::Ng.new(self, Rcb::CircuitBreakerOpenError.new(config.tag, since))
37
+ end
38
+ end
39
+
40
+ def half_open?(now = Time.now.utc, reset_timeout_msec)
41
+ ((now - since) * 1000) >= reset_timeout_msec
42
+ end
43
+ end
44
+
45
+ HalfOpen = const do
46
+ # only executed from Open#run
47
+ def run(&block)
48
+ case try_call(&block)
49
+ in Either::Right[result]
50
+ Rcb::Result::Ok.new(Close.create, result)
51
+ in Either::Left[e]
52
+ Rcb::Result::Ng.new(Open.create, e)
53
+ end
54
+ end
55
+ end
56
+
57
+ interface do
58
+ def state(config)
59
+ case self
60
+ in Open if self.half_open?(config.reset_timeout_msec)
61
+ :half_open
62
+ in Open
63
+ :open
64
+ in Close
65
+ :close
66
+ end
67
+ end
68
+
69
+ private
70
+
71
+ def try_call(&block)
72
+ result = block.call
73
+ Either.right(result)
74
+ rescue => e
75
+ Either.left(e)
76
+ end
77
+ end
78
+ end
79
+
@@ -0,0 +1,3 @@
1
+ module Rcb
2
+ VERSION = "0.1.0"
3
+ end
data/lib/rcb.rb ADDED
@@ -0,0 +1,15 @@
1
+ require_relative "./rcb/instance"
2
+ require_relative "./rcb/configuration"
3
+
4
+ module Rcb
5
+ module ClassMethods
6
+ def for(tag, max_failure_count: nil, reset_timeout_msec: nil)
7
+ config = Rcb::Configurations.for(tag,
8
+ max_failure_count: max_failure_count,
9
+ reset_timeout_msec: reset_timeout_msec)
10
+ Instance.new(config)
11
+ end
12
+ end
13
+
14
+ extend ClassMethods
15
+ end
data/rcb.gemspec ADDED
@@ -0,0 +1,33 @@
1
+ require_relative 'lib/rcb/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "rcb"
5
+ spec.version = Rcb::VERSION
6
+ spec.authors = ["petitviolet"]
7
+ spec.email = ["violethero0820@gmail.com"]
8
+
9
+ spec.summary = %q{Ruby Circuit Breaker}
10
+ spec.description = %q{Ruby Circuit Breaker}
11
+ spec.homepage = "https://github.com/petitviolet/rcb"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.7.0")
14
+
15
+ spec.metadata["homepage_uri"] = spec.homepage
16
+ spec.metadata["source_code_uri"] = "https://github.com/petitviolet/rcb"
17
+ spec.metadata["changelog_uri"] = "https://github.com/petitviolet/rcb"
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+
28
+ spec.add_dependency "rstructural"
29
+
30
+ spec.add_development_dependency "bundler"
31
+ spec.add_development_dependency "rake"
32
+ spec.add_development_dependency "byebug"
33
+ end
metadata ADDED
@@ -0,0 +1,118 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rcb
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - petitviolet
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-02-22 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rstructural
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: byebug
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: Ruby Circuit Breaker
70
+ email:
71
+ - violethero0820@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - CODE_OF_CONDUCT.md
78
+ - Gemfile
79
+ - LICENSE.txt
80
+ - README.md
81
+ - Rakefile
82
+ - bin/console
83
+ - bin/setup
84
+ - lib/rcb.rb
85
+ - lib/rcb/configuration.rb
86
+ - lib/rcb/error.rb
87
+ - lib/rcb/instance.rb
88
+ - lib/rcb/result.rb
89
+ - lib/rcb/state.rb
90
+ - lib/rcb/version.rb
91
+ - rcb.gemspec
92
+ homepage: https://github.com/petitviolet/rcb
93
+ licenses:
94
+ - MIT
95
+ metadata:
96
+ homepage_uri: https://github.com/petitviolet/rcb
97
+ source_code_uri: https://github.com/petitviolet/rcb
98
+ changelog_uri: https://github.com/petitviolet/rcb
99
+ post_install_message:
100
+ rdoc_options: []
101
+ require_paths:
102
+ - lib
103
+ required_ruby_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: 2.7.0
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ requirements: []
114
+ rubygems_version: 3.1.2
115
+ signing_key:
116
+ specification_version: 4
117
+ summary: Ruby Circuit Breaker
118
+ test_files: []