circuit_switch 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: 8e327f0f981b9690cd6115067a3ede6d399d3ea25fb905da56629c58954b7db4
4
+ data.tar.gz: 75b1a01d86987a360a0e898180d382d56358efe14f681156ed3d4f60998bdfea
5
+ SHA512:
6
+ metadata.gz: 403ae1fd2a6e17d2834b07ce745ecf5787342bb6177544ac15c9e53d09d4b1782dbc50311e78519b0298f8a644af2d4b9ff14d4eb976ea90418c0a8c008bd907
7
+ data.tar.gz: fa0a9770084140cdc794b39b15d60f5694a8f1cc98b8146e3ee0a7a6d7eb9c08117206208f3b019ec39c18ce11bfeaaa158fcd9c2d5e9ee0fa9d37d07f2c9b49
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
10
+ .byebug_history
@@ -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 unright@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,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in circuit_switch.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 makicamel
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,172 @@
1
+ # CircuitSwitch
2
+
3
+ CircuitSwitch is a gem for 'difficult' application; for example, few tests, too many meta-programming codes, low aggregation classes and few deploys.
4
+ This switch helps make changes easier and deploy safely.
5
+ You can deploy and check with a short code like following if the change is good or not, and when a problem is found, you can undo it without releasing it.
6
+
7
+ ```ruby
8
+ if CircuitSwitch.report.open?
9
+ # new codes
10
+ else
11
+ # old codes
12
+ end
13
+ ```
14
+
15
+ You can also specify conditions to release testing features.
16
+
17
+ ```ruby
18
+ CircuitSwitch.run(if: -> { current_user.testing_new_feature? }) do
19
+ # testing feature codes
20
+ end
21
+ ```
22
+
23
+ CircuitSwitch depends on ActiveRecord and ActiveJob.
24
+
25
+ ## Installation
26
+
27
+ Add this line to your application's Gemfile and run `bundle install`:
28
+
29
+ ```ruby
30
+ gem 'circuit_switch'
31
+ ```
32
+
33
+ Run generator to create initializer and modify `config/initizlizers/circuit_switch.rb`:
34
+
35
+ ```
36
+ rails generate circuit_switch:install
37
+ ```
38
+
39
+ Generate a migration for ActiveRecord.
40
+ This table saves circuit caller, called count, limit count and so on.
41
+
42
+ ```
43
+ rails generate circuit_switch:migration circuit_switch
44
+ rails db:migrate
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ### `run`
50
+
51
+ When you want to deploy and undo it if something unexpected happens, use `CircuitSwitch.run`.
52
+
53
+ ```ruby
54
+ CircuitSwitch.run do
55
+ # experimental codes
56
+ end
57
+ ```
58
+
59
+ `run` calls received proc, and when conditions are met, closes it's circuit.
60
+ To switch circuit opening and closing, some conditions can be set. By default, the circuit is closed when reached the specified count. The default count is 10. To change this default value, modify `circuit_switches.run_limit_count` default value in the migration file.
61
+ `run` receives optional arguments.
62
+
63
+ - `if`: [Boolean, Proc] Call proc when `if` is truthy (default: true)
64
+ - `close_if`: [Boolean, Proc] Call proc when `close_if` is falsy (default: false)
65
+ - `close_if_reach_limit`: [Boolean] Stop calling proc when run count reaches limit (default: true)
66
+ - `limit_count`: [Integer] Limit count. Use `run_limit_count` default value if it's nil (default: nil)
67
+ Can't be set 0 when `close_if_reach_limit` is true
68
+
69
+ To close the circuit at specific date or when called 1000 times, code goes like:
70
+
71
+ ```ruby
72
+ CircuitSwitch.run(close_if: -> { Date.today >= some_day }, limit_count: 1_000) do
73
+ # testing codes
74
+ end
75
+ ```
76
+
77
+ To run other codes when circuit closes, `run?` is available.
78
+
79
+ ```ruby
80
+ circuit_open = CircuitSwitch.run { ... }.run?
81
+ unless circuit_open
82
+ # other codes
83
+ end
84
+ ```
85
+
86
+ `CircuitSwitch.run.run?` has syntax sugar. `open` doesn't receive proc.
87
+
88
+ ```ruby
89
+ if CircuitSwitch.open?
90
+ # new codes
91
+ else
92
+ # old codes
93
+ end
94
+ ```
95
+
96
+ ### `report`
97
+
98
+ When you just want to report, set your `reporter` to initializer and then call `CircuitSwitch.report`.
99
+
100
+ ```ruby
101
+ CircuitSwitch.report(if: some_condition)
102
+ ```
103
+
104
+ `report` just reports the line of code is called. It doesn't receive proc. It's useful for refactoring or removing dead codes.
105
+ Same as `run`, some conditions can be set. By default, reporting is stopped when reached the specified count. The default count is 10. To change this default value, modify `circuit_switches.report_limit_count` default value in the migration file.
106
+ `report` receives optional arguments.
107
+
108
+ - `if`: [Boolean, Proc] Report when `if` is truthy (default: true)
109
+ - `stop_report_if`: [Boolean, Proc] Report when `close_if` is falsy (default: false)
110
+ - `stop_report_if_reach_limit`: [Boolean] Stop reporting when reported count reaches limit (default: true)
111
+ - `limit_count`: [Integer] Limit count. Use `report_limit_count` default value if it's nil (default: nil)
112
+ Can't be set 0 when `stop_report_if_reach_limit` is true
113
+
114
+ To know about report is executed or not, you can get through `report?`.
115
+ Of course you can chain `report` and `run` or `open?`.
116
+
117
+ #### `with_backtrace`
118
+
119
+ Reporter reports a short message by default like `Watching process is called for 5th. Report until for 10th.`.
120
+ When your reporting tool knows about it's caller and backtrace, this is enough (e.g. Bugsnag).
121
+ When your reporting tool just reports plain message (e.g. Slack), you can set `with_backtrace` true to initializer. Then report has a long message with backtrace like:
122
+
123
+ ```
124
+ Watching process is called for 5th. Report until for 10th.
125
+ called_path: /app/services/greetings_service:21 block in validate
126
+ /app/services/greetings_service:20 validate
127
+ /app/services/greetings_service:5 call
128
+ /app/controllers/greetings_controller.rb:93 create
129
+ ```
130
+
131
+ ## Task
132
+
133
+ When find a problem and you want to terminate running or reporting right now, execute a task with it's caller.
134
+
135
+ ```
136
+ rake circuit_switch:terminate_to_run[/app/services/greetings_service:21 block in validate]
137
+ rake circuit_switch:terminate_to_report[/app/services/greetings_service:21 block in validate]
138
+ ```
139
+
140
+ In case of not Rails applications, add following to your Rakefile:
141
+
142
+ ```ruby
143
+ require 'circuit_switch/tasks'
144
+ ```
145
+
146
+ ## Reminder for cleaning up codes
147
+
148
+ Too many circuits make codes messed up. We want to remove circuits after several days, but already have too many TODO things enough to remember them.
149
+ Let's forget it! Set `due_date_notifier` to initializer and then call `CircuitSwitch::DueDateNotifier` job daily. It will notify the list of currently registered switches.
150
+ By default, due_date is 10 days after today. To modify, set `due_date` to initializer.
151
+
152
+ ## GUI to manage switches
153
+
154
+ Under development :)
155
+
156
+ ## Development
157
+
158
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
159
+
160
+ 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).
161
+
162
+ ## Contributing
163
+
164
+ Bug reports and pull requests are welcome on GitHub at https://github.com/makicamel/circuit_switch. 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/makicamel/circuit_switch/blob/master/CODE_OF_CONDUCT.md).
165
+
166
+ ## License
167
+
168
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
169
+
170
+ ## Code of Conduct
171
+
172
+ Everyone interacting in the CircuitSwitch project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/makicamel/circuit_switch/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "circuit_switch"
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,32 @@
1
+ require_relative 'lib/circuit_switch/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "circuit_switch"
5
+ spec.version = CircuitSwitch::VERSION
6
+ spec.authors = ["makicamel"]
7
+ spec.email = ["unright@gmail.com"]
8
+
9
+ spec.summary = 'Circuit switch with report tools'
10
+ spec.description = 'Circuit switch to help changing source code in safety and easy with report tools'
11
+ spec.homepage = 'https://github.com/makicamel/circuit_switch'
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ spec.metadata["homepage_uri"] = spec.homepage
16
+ spec.metadata["source_code_uri"] = 'https://github.com/makicamel/circuit_switch'
17
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
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.require_paths = ["lib"]
25
+
26
+ spec.add_dependency 'activejob'
27
+ spec.add_dependency 'activerecord'
28
+ spec.add_development_dependency 'byebug'
29
+ spec.add_development_dependency 'sqlite3'
30
+ spec.add_development_dependency 'test-unit'
31
+ spec.add_development_dependency 'test-unit-rr'
32
+ end
@@ -0,0 +1,44 @@
1
+ module CircuitSwitch
2
+ class Configuration
3
+ CIRCUIT_SWITCH = 'circuit_switch'.freeze
4
+
5
+ attr_accessor :reporter, :due_date_notifier
6
+ attr_writer :report_paths, :report_if, :due_date, :with_backtrace, :allowed_backtrace_paths, :strip_paths
7
+
8
+ def report_paths
9
+ @report_paths ||= [Rails.root]
10
+ end
11
+
12
+ def silent_paths=(paths)
13
+ @silent_paths = paths.append(CIRCUIT_SWITCH).uniq
14
+ end
15
+
16
+ def silent_paths
17
+ @silent_paths ||= [CIRCUIT_SWITCH]
18
+ end
19
+
20
+ def report_if
21
+ @report_if ||= Rails.env.production?
22
+ end
23
+
24
+ def enable_report?
25
+ report_if.respond_to?(:call) ? report_if.call : !!report_if
26
+ end
27
+
28
+ def due_date
29
+ @due_date = Date.today + 10
30
+ end
31
+
32
+ def with_backtrace
33
+ @with_backtrace ||= false
34
+ end
35
+
36
+ def allowed_backtrace_paths
37
+ @allowed_backtrace_paths ||= [Dir.pwd]
38
+ end
39
+
40
+ def strip_paths
41
+ @strip_paths ||= [Dir.pwd]
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,84 @@
1
+ module CircuitSwitch
2
+ class Core
3
+ delegate :config, to: ::CircuitSwitch
4
+
5
+ def run(
6
+ if: true,
7
+ close_if: false,
8
+ close_if_reach_limit: true,
9
+ limit_count: nil,
10
+ &block
11
+ )
12
+ if close_if_reach_limit && limit_count == 0
13
+ raise CircuitSwitchError.new('Can\'t set limit_count to 0 when close_if_reach_limit is true')
14
+ end
15
+ return self if evaluate(close_if) || !evaluate(binding.local_variable_get(:if))
16
+ return self if close_if_reach_limit && switch.reached_run_limit?(limit_count)
17
+ return self if switch.run_is_terminated?
18
+
19
+ yield
20
+ RunCountUpdater.perform_later(
21
+ limit_count: limit_count,
22
+ called_path: called_path,
23
+ reported: reported?
24
+ )
25
+ @run = true
26
+ self
27
+ end
28
+
29
+ def report(
30
+ if: true,
31
+ stop_report_if: false,
32
+ stop_report_if_reach_limit: true,
33
+ limit_count: nil
34
+ )
35
+ if config.reporter.nil?
36
+ raise CircuitSwitchError.new('Set config.reporter.')
37
+ end
38
+ if stop_report_if_reach_limit && limit_count == 0
39
+ raise CircuitSwitchError.new('Can\'t set limit_count to 0 when stop_report_if_reach_limit is true')
40
+ end
41
+ return self unless config.enable_report?
42
+ return self if evaluate(stop_report_if) || !evaluate(binding.local_variable_get(:if))
43
+ return self if switch.report_is_terminated?
44
+ return self if stop_report_if_reach_limit && switch.reached_report_limit?(limit_count)
45
+
46
+ Reporter.perform_later(
47
+ limit_count: limit_count,
48
+ called_path: called_path,
49
+ run: run?
50
+ )
51
+ @reported = true
52
+ self
53
+ end
54
+
55
+ # @return [Boolean]
56
+ def run?
57
+ !!@run
58
+ end
59
+
60
+ # @return [Boolean]
61
+ def reported?
62
+ !!@reported
63
+ end
64
+
65
+ private
66
+
67
+ def switch
68
+ @switch ||= CircuitSwitch.find_or_initialize_by(caller: called_path)
69
+ end
70
+
71
+ def called_path
72
+ @called_path ||= caller
73
+ .reject { |path| path.match?(/(#{config.silent_paths.join('|')})/) }
74
+ .detect { |path| path.match?(/(#{config.report_paths.join('|')})/) }
75
+ &.sub(/(#{config.strip_paths.join('|')})/, '')
76
+ &.gsub(/[`']/, '') ||
77
+ "/somewhere/in/library:in #{Date.today}"
78
+ end
79
+
80
+ def evaluate(boolean_or_proc)
81
+ boolean_or_proc.respond_to?(:call) ? boolean_or_proc.call : boolean_or_proc
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,19 @@
1
+ require 'circuit_switch/stacktrace_modifier'
2
+
3
+ module CircuitSwitch
4
+ class CircuitSwitchError < RuntimeError
5
+ end
6
+
7
+ class CircuitSwitchNotification < RuntimeError
8
+ end
9
+
10
+ class CalledNotification < CircuitSwitchNotification
11
+ def to_message(called_path:)
12
+ if ::CircuitSwitch.config.with_backtrace
13
+ "#{message}\ncalled_path: #{called_path}\n#{StacktraceModifier.call(backtrace: backtrace)}"
14
+ else
15
+ message
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,47 @@
1
+ module CircuitSwitch
2
+ class CircuitSwitch < ::ActiveRecord::Base
3
+ def assign(run_limit_count: nil, report_limit_count: nil)
4
+ self.run_limit_count = run_limit_count if run_limit_count
5
+ self.report_limit_count = report_limit_count if report_limit_count
6
+ self
7
+ end
8
+
9
+ def reached_run_limit?(new_value)
10
+ if new_value
11
+ run_count >= new_value
12
+ else
13
+ run_count >= run_limit_count
14
+ end
15
+ end
16
+
17
+ def reached_report_limit?(new_value)
18
+ if new_value
19
+ report_count >= new_value
20
+ else
21
+ report_count >= report_limit_count
22
+ end
23
+ end
24
+
25
+ def increment_run_count
26
+ with_writable { update!(run_count: run_count + 1) }
27
+ end
28
+
29
+ def increment_report_count
30
+ with_writable { update!(report_count: report_count + 1) }
31
+ end
32
+
33
+ def message
34
+ "Watching process is called for #{report_count}th. Report until for #{report_limit_count}th."
35
+ end
36
+
37
+ private
38
+
39
+ def with_writable
40
+ if self.class.const_defined?(:ApplicationRecord) && ApplicationRecord.respond_to?(:with_writable)
41
+ ApplicationRecord.with_writable { yield }
42
+ else
43
+ yield
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,7 @@
1
+ module CircuitSwitch
2
+ class Railtie < ::Rails::Railtie
3
+ rake_tasks do
4
+ load 'circuit_switch/tasks/circuit_switch.rake'
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,16 @@
1
+ require 'circuit_switch/configuration.rb'
2
+
3
+ module CircuitSwitch
4
+ class StacktraceModifier
5
+ class << self
6
+ delegate :config, to: ::CircuitSwitch
7
+
8
+ def call(backtrace:)
9
+ backtrace
10
+ .select { |path| path.match?(/(#{config.allowed_backtrace_paths.join('|')})/) }
11
+ .map { |path| path.sub(/(#{config.strip_paths.join('|')})/, '') }
12
+ .join("\n")
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,40 @@
1
+ namespace :circuit_switch do
2
+ desc 'Update run_is_terminated to true to close circuit'
3
+ task :terminate_to_run, ['caller'] => :environment do |_, arg|
4
+ called_path = arg[:caller]
5
+ puts "Start to update run_is_terminated of circuit_switch for '#{called_path}' to true."
6
+ sleep(3)
7
+
8
+ switch = CircuitSwitch::CircuitSwitch.find_by!(caller: called_path)
9
+ puts "circuit_switch is found. id: #{switch.id}."
10
+
11
+ switch.update(run_is_terminated: true)
12
+ puts "Updated run_is_terminated of circuit_switch for '#{called_path}' to true."
13
+ end
14
+
15
+ desc 'Update report_is_terminated to true to stop reporting'
16
+ task :terminate_to_report, ['caller'] => :environment do |_, arg|
17
+ called_path = arg[:caller]
18
+ puts "Start to update report_is_terminated of circuit_switch for '#{called_path}' to true."
19
+ sleep(3)
20
+
21
+ switch = CircuitSwitch::CircuitSwitch.find_by!(caller: called_path)
22
+ puts "circuit_switch is found. id: #{switch.id}."
23
+
24
+ switch.update(report_is_terminated: true)
25
+ puts "Updated report_is_terminated of circuit_switch for '#{called_path}' to true."
26
+ end
27
+
28
+ desc 'Delete switch'
29
+ task :delete_switch, ['caller'] => :environment do |_, arg|
30
+ called_path = arg[:caller]
31
+ puts "Start to delete circuit_switch for '#{called_path}'."
32
+ sleep(3)
33
+
34
+ switch = CircuitSwitch::CircuitSwitch.find_by!(caller: called_path)
35
+ puts "circuit_switch is found. id: #{switch.id}."
36
+
37
+ switch.destroy!
38
+ puts "Successfully deleted circuit_switch for '#{called_path}'."
39
+ end
40
+ end
@@ -0,0 +1,3 @@
1
+ Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].each do |task|
2
+ load task
3
+ end
@@ -0,0 +1,3 @@
1
+ module CircuitSwitch
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,22 @@
1
+ require 'date'
2
+
3
+ module CircuitSwitch
4
+ class DueDateNotifier < ::ActiveJob::Base
5
+ delegate :config, to: ::CircuitSwitch
6
+
7
+ def perform
8
+ raise CircuitSwitchError.new('Set config.due_date_notifier.') unless config.due_date_notifier
9
+
10
+ circuit_switches = CircuitSwitch.where('due_date <= ?', Date.today).order(id: :asc)
11
+ if circuit_switches.present?
12
+ message = "Due date has come! Let's consider about removing switches and cleaning up code! :)\n" +
13
+ circuit_switches.map { |switch| "id: #{switch.id}, caller: '#{switch.caller}' , created_at: #{switch.created_at}" }.join("\n")
14
+ config.due_date_notifier.call(message)
15
+ else
16
+ switches_count = CircuitSwitch.all.size
17
+ message = switches_count.zero? ? 'There is no switch!' : "#{switches_count} switches are waiting for their due_date."
18
+ config.due_date_notifier.call(message)
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,21 @@
1
+ module CircuitSwitch
2
+ class Reporter < ::ActiveJob::Base
3
+ delegate :config, to: ::CircuitSwitch
4
+
5
+ def perform(limit_count:, called_path:, run:)
6
+ circuit_switch =
7
+ if run
8
+ # Wait for RunCountUpdater saves circuit_switch
9
+ sleep(3)
10
+ CircuitSwitch.find_by!(caller: called_path)
11
+ else
12
+ CircuitSwitch.find_or_initialize_by(caller: called_path)
13
+ end
14
+ circuit_switch.due_date ||= config.due_date
15
+ circuit_switch.assign(report_limit_count: limit_count).increment_report_count
16
+ raise CalledNotification.new(circuit_switch.message)
17
+ rescue CalledNotification => notification
18
+ config.reporter.call(notification.to_message(called_path: called_path))
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,18 @@
1
+ module CircuitSwitch
2
+ class RunCountUpdater < ::ActiveJob::Base
3
+ delegate :config, to: ::CircuitSwitch
4
+
5
+ def perform(limit_count:, called_path:, reported:)
6
+ circuit_switch =
7
+ if reported
8
+ # Wait for Reporter saves circuit_switch
9
+ sleep(3)
10
+ CircuitSwitch.find_by!(caller: called_path)
11
+ else
12
+ CircuitSwitch.find_or_initialize_by(caller: called_path)
13
+ end
14
+ circuit_switch.due_date ||= config.due_date
15
+ circuit_switch.assign(run_limit_count: limit_count).increment_run_count
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,80 @@
1
+ require "circuit_switch/configuration.rb"
2
+ require "circuit_switch/core"
3
+ require "circuit_switch/notification"
4
+ require "circuit_switch/orm/active_record/circuit_switch"
5
+ require "circuit_switch/railtie" if defined?(Rails::Railtie)
6
+ require "circuit_switch/version"
7
+ require "circuit_switch/workers/due_date_notifier"
8
+ require "circuit_switch/workers/reporter"
9
+ require "circuit_switch/workers/run_count_updater"
10
+
11
+ module CircuitSwitch
12
+ class << self
13
+ def configure
14
+ yield config
15
+ end
16
+
17
+ def config
18
+ @config ||= Configuration.new
19
+ end
20
+
21
+ # @param if [Boolean, Proc] Call proc when `if` is truthy (default: true)
22
+ # @param close_if [Boolean, Proc] Call proc when `close_if` is falsy (default: false)
23
+ # @param close_if_reach_limit [Boolean] Stop calling proc when run count reaches limit (default: true)
24
+ # @param limit_count [Integer] Limit count. Use `run_limit_count` default value if it's nil
25
+ # Can't be set 0 when `close_if_reach_limit` is true (default: nil)
26
+ # @param [Proc] block
27
+ def run(
28
+ if: true,
29
+ close_if: false,
30
+ close_if_reach_limit: true,
31
+ limit_count: nil,
32
+ &block
33
+ )
34
+ Core.new.run(
35
+ if: binding.local_variable_get(:if),
36
+ close_if: close_if,
37
+ close_if_reach_limit: close_if_reach_limit,
38
+ limit_count: limit_count,
39
+ &block
40
+ )
41
+ end
42
+
43
+ # @param if [Boolean, Proc] Report when `if` is truthy (default: true)
44
+ # @param stop_report_if [Boolean, Proc] Report when `close_if` is falsy (default: false)
45
+ # @param stop_report_if_reach_limit [Boolean] Stop reporting when reported count reaches limit (default: true)
46
+ # @param limit_count [Integer] Limit count. Use `report_limit_count` default value if it's nil
47
+ # Can't be set 0 when `stop_report_if_reach_limit` is true (default: nil)
48
+ def report(
49
+ if: true,
50
+ stop_report_if: false,
51
+ stop_report_if_reach_limit: true,
52
+ limit_count: nil
53
+ )
54
+ if block_given?
55
+ raise ArgumentError.new('CircuitSwitch.report doesn\'t receive block. Use CircuitSwitch.run if you want to pass block.')
56
+ end
57
+
58
+ Core.new.report(
59
+ if: binding.local_variable_get(:if),
60
+ stop_report_if: stop_report_if,
61
+ stop_report_if_reach_limit: stop_report_if_reach_limit,
62
+ limit_count: limit_count
63
+ )
64
+ end
65
+
66
+ # Syntax sugar for `CircuitSwitch.run`
67
+ # @param if [Boolean, Proc] `CircuitSwitch.run` is runnable when `if` is truthy (default: true)
68
+ # @param limit_count [Integer] Limit count. Use `run_limit_count` default value if it's nil. Can't be set 0 (default: nil)
69
+ def open?(if: true, limit_count: nil)
70
+ if block_given?
71
+ raise ArgumentError.new('CircuitSwitch.open doesn\'t receive block. Use CircuitSwitch.run if you want to pass block.')
72
+ end
73
+
74
+ Core.new.run(
75
+ if: binding.local_variable_get(:if),
76
+ limit_count: limit_count
77
+ ) {}.run?
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CircuitSwitch
4
+ class InstallGenerator < ::Rails::Generators::Base
5
+ include ::Rails::Generators::Migration
6
+ source_root File.expand_path('templates', __dir__)
7
+ desc 'Installs CircuitSwitch.'
8
+
9
+ def install
10
+ template 'initializer.rb', 'config/initializers/circuit_switch.rb'
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,18 @@
1
+ require 'rails/generators/active_record'
2
+
3
+ module CircuitSwitch
4
+ class MigrationGenerator < ActiveRecord::Generators::Base
5
+ desc 'Create a migration to manage circuit switches state'
6
+ source_root File.expand_path('templates', __dir__)
7
+
8
+ def generate_migration
9
+ migration_template 'migration.rb.erb', 'db/migrate/create_circuit_switches.rb', migration_version: migration_version
10
+ end
11
+
12
+ def migration_version
13
+ if ActiveRecord::VERSION::MAJOR >= 5
14
+ "[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]"
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ CircuitSwitch.configure do |config|
4
+ # Specify proc to call your report tool: like;
5
+ # config.reporter = -> (message) { Bugsnag.notify(message) }
6
+ config.reporter = nil
7
+
8
+ # Condition to report
9
+ # config.report_if = Rails.env.production?
10
+
11
+ # Allowed paths to report
12
+ # CircuitSwitch recognizes logic as unique that first match with these paths.
13
+ # Allowed all paths when set `[]`.
14
+ # config.report_paths = [Rails.root]
15
+
16
+ # Excluded paths to report
17
+ # config.silent_paths = [CIRCUIT_SWITCH]
18
+
19
+ # Notifier to notify circuit_switch's due_date come and it's time to clean code!
20
+ # Specify proc to call your report tool: like;
21
+ # config.due_date_notifier = -> (message) { Slack::Web::Client.new.chat_postMessage(channel: '#your_channel', text: message) }
22
+ # config.due_date_notifier = nil
23
+
24
+ # Date for due_date_notifier
25
+ # config.due_date = Date.today + 10
26
+
27
+ # Option to contain error backtrace for report
28
+ # You don't need backtrace when you report to some bug report tool.
29
+ # You may be want backtrace when report to plain feed; e.g. Slack or email.
30
+ # config.with_backtrace = false
31
+
32
+ # Allowd backtrace paths to report
33
+ # Specify with `with_backtrace` option.
34
+ # Allowed all paths when set `[]`.
35
+ # config.allowed_backtrace_paths = [Dir.pwd]
36
+
37
+ # Omit path prefix in caller and backtrace for readability
38
+ # config.strip_paths = [Dir.pwd]
39
+ end
@@ -0,0 +1,15 @@
1
+ class CreateCircuitSwitches < ActiveRecord::Migration<%= migration_version %>
2
+ def change
3
+ create_table :circuit_switches do |t|
4
+ t.string :caller, null: false
5
+ t.integer :run_count, default: 0, null: false
6
+ t.integer :run_limit_count, default: 10, null: false
7
+ t.boolean :run_is_terminated, default: false, null: false
8
+ t.integer :report_count, default: 0, null: false
9
+ t.integer :report_limit_count, default: 10, null: false
10
+ t.boolean :report_is_terminated, default: false, null: false
11
+ t.date :due_date, null: false
12
+ t.timestamps
13
+ end
14
+ end
15
+ end
metadata ADDED
@@ -0,0 +1,156 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: circuit_switch
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - makicamel
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-10-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activejob
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: activerecord
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
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: byebug
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: sqlite3
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
+ - !ruby/object:Gem::Dependency
70
+ name: test-unit
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: test-unit-rr
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description: Circuit switch to help changing source code in safety and easy with report
98
+ tools
99
+ email:
100
+ - unright@gmail.com
101
+ executables: []
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".gitignore"
106
+ - CODE_OF_CONDUCT.md
107
+ - Gemfile
108
+ - LICENSE.txt
109
+ - README.md
110
+ - Rakefile
111
+ - bin/console
112
+ - bin/setup
113
+ - circuit_switch.gemspec
114
+ - lib/circuit_switch.rb
115
+ - lib/circuit_switch/configuration.rb
116
+ - lib/circuit_switch/core.rb
117
+ - lib/circuit_switch/notification.rb
118
+ - lib/circuit_switch/orm/active_record/circuit_switch.rb
119
+ - lib/circuit_switch/railtie.rb
120
+ - lib/circuit_switch/stacktrace_modifier.rb
121
+ - lib/circuit_switch/tasks.rb
122
+ - lib/circuit_switch/tasks/circuit_switch.rake
123
+ - lib/circuit_switch/version.rb
124
+ - lib/circuit_switch/workers/due_date_notifier.rb
125
+ - lib/circuit_switch/workers/reporter.rb
126
+ - lib/circuit_switch/workers/run_count_updater.rb
127
+ - lib/generators/circuit_switch/install_generator.rb
128
+ - lib/generators/circuit_switch/migration_generator.rb
129
+ - lib/generators/circuit_switch/templates/initializer.rb
130
+ - lib/generators/circuit_switch/templates/migration.rb.erb
131
+ homepage: https://github.com/makicamel/circuit_switch
132
+ licenses:
133
+ - MIT
134
+ metadata:
135
+ homepage_uri: https://github.com/makicamel/circuit_switch
136
+ source_code_uri: https://github.com/makicamel/circuit_switch
137
+ post_install_message:
138
+ rdoc_options: []
139
+ require_paths:
140
+ - lib
141
+ required_ruby_version: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: 2.3.0
146
+ required_rubygems_version: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ requirements: []
152
+ rubygems_version: 3.1.2
153
+ signing_key:
154
+ specification_version: 4
155
+ summary: Circuit switch with report tools
156
+ test_files: []