circuit_switch 0.2.2 → 0.5.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 948143d874eac4049767af92dacd5f8175ad016a951b93e95e05e3a3585eaf70
4
- data.tar.gz: 98981a823c9fa4dd0c20259003766ecf789dd44f7ad0e7bd8983223338f5a550
3
+ metadata.gz: e5700c391d205790305cce8ed4d213f694deeaa8883d10d6b8e48a47de7d8f7e
4
+ data.tar.gz: acee1e59d6da803a085f399c39ef72099dc3d70a49f270fcb1dd1d0c49c1cf40
5
5
  SHA512:
6
- metadata.gz: 317208a17b15dfcc29e333c217ee7320b0133a721a918d2917cd3d172615a86ffe73394e74d407454b9ff8e16fa2be702d6d22cc91467793a9260a84bae792ad
7
- data.tar.gz: 3ec9b0893cca1eaee59e1aa40c7c3be95348b90760aff1a5fef59053e7dbeb72c627b93940e04b14d0b3c2c2d5159beb00dc13b6b6145b340871734346138428
6
+ metadata.gz: a7cfad2c3e41054235f8546f68d01945c387b196b0f1bb11290eb4f3a61da6477c422f347aee3ac87645fe6d841c585052a8cbe1ec3c835a97d683509ea77933
7
+ data.tar.gz: 92a77c9ae39c41ba59fb4cfd021b359169cbbc0d0b604ab00a258cad7fcd7fae0348b0bd9d9ac51b7e199fb33d8b17f39314a030cd6e70b89fa300e57a818162
data/CHANGELOG.md CHANGED
@@ -1,3 +1,51 @@
1
+ ## 0.5.0
2
+
3
+ ### New features
4
+
5
+ * GUI has been released!
6
+ If you are on Rails, add the following to your `config/routes.rb` and access `/circuit_switch`.
7
+
8
+ ```ruby
9
+ Rails.application.routes.draw do
10
+ mount CircuitSwitch::Engine => 'circuit_switch'
11
+ end
12
+ ```
13
+
14
+ ## 0.4.1
15
+
16
+ * Fix bug `if` `stop_report_if_reach_limit` options don't receive `false`.
17
+ * Fix to report error with stacktrace.
18
+ * Fix not to update run count when run isn't executable.
19
+
20
+ ## 0.4.0
21
+
22
+ ### Breaking Changes
23
+
24
+ * Be able to choice to notify `CircuitSwitch::CalledNotification` or `String`.
25
+ Improve `config/initializers/circuit_switch.rb` like following.
26
+
27
+ ```diff
28
+ CircuitSwitch.configure do |config|
29
+ - config.reporter = ->(message) { Bugsnag.notify(message) }
30
+ + config.reporter = ->(message, error) { Bugsnag.notify(error) }
31
+ ```
32
+
33
+ ## 0.3.0
34
+
35
+ ### Breaking Changes
36
+
37
+ * Modify `key` to unique by default.
38
+ To migrate, run next.
39
+
40
+ ```
41
+ rails generate circuit_switch:migration circuit_switch make_key_unique
42
+ rails db:migrate
43
+ ```
44
+
45
+ ### Changes
46
+
47
+ * Fix to save switch when block for `CircuitSwitch.run` raises error.
48
+
1
49
  ## 0.2.2
2
50
 
3
51
  ### New features
data/README.md CHANGED
@@ -56,24 +56,30 @@ CircuitSwitch.run do
56
56
  end
57
57
  ```
58
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 always opened.
61
- You can also set `limit_count` to close circuit when reached the specified count. Default limit_count is 10. To change this default value, modify `circuit_switches.run_limit_count` default value in the migration file.
62
- `run` receives optional arguments.
63
-
64
- - `key`: [String] Named key to find switch instead of caller
65
- If no key passed, use caller.
66
- - `if`: [Boolean, Proc] Call proc when `if` is truthy (default: true)
67
- - `close_if`: [Boolean, Proc] Call proc when `close_if` is falsy (default: false)
68
- - `close_if_reach_limit`: [Boolean] Stop calling proc when run count reaches limit (default: false)
69
- - `limit_count`: [Integer] Limit count. Use `run_limit_count` default value if it's nil (default: nil)
70
- Can't be set 0 when `close_if_reach_limit` is true
71
- - `initially_closed`: [Boolean] Create switch with terminated mode (default: false)
72
-
73
- To close the circuit at specific date or when called 1000 times, code goes like:
59
+ `run` basically calls the received proc. But when a condition is met, it closes the circuit and does not evaluate the proc.
60
+ To switch circuit opening and closing, a set of options can be set. Without options, the circuit is always open.
61
+ You can set `close_if_reach_limit: true` so that the circuit is only open for 10 invocations. The constant 10 comes from the table definition we have arbitrarily chosen. In case you need a larger number, specify it in the `limit_count` option in combination with `close_if_reach_limit: true`, or alter default constraint on `circuit_switches.run_limit_count`.
62
+
63
+ - `key`: [String] The identifier to find record by. If `key` has not been passed, `circuit_switches.caller` is chosen as an alternative.
64
+ - `if`: [Boolean, Proc] Calls proc when the value of `if` is evaluated truthy (default: true)
65
+ - `close_if`: [Boolean, Proc] Calls proc when the value of `close_if` is evaluated falsy (default: false)
66
+ - `close_if_reach_limit`: [Boolean] Stops calling proc when `circuit_switches.run_count` has reached `circuit_switches.run_limit_count` (default: false)
67
+ - `limit_count`: [Integer] Mutates `circuit_switches.run_limit_count` whose value defined in schema is 10 by default. (default: nil)
68
+ Can't be set to 0 when `close_if_reach_limit` is true. This option is only relevant when `close_if_reach_limit` is set to true.
69
+ - `initially_closed`: [Boolean] Creates switch with terminated mode (default: false)
70
+
71
+ To close the circuit at a specific date, code goes like:
74
72
 
75
73
  ```ruby
76
- CircuitSwitch.run(close_if: -> { Date.today >= some_day }, limit_count: 1_000) do
74
+ CircuitSwitch.run(close_if: -> { Date.today >= some_day }) do
75
+ # testing codes
76
+ end
77
+ ```
78
+
79
+ Or when the code of concern has been called 1000 times:
80
+
81
+ ```ruby
82
+ CircuitSwitch.run(close_if_reach_limit: true, limit_count: 1_000) do
77
83
  # testing codes
78
84
  end
79
85
  ```
@@ -105,19 +111,17 @@ When you just want to report, set your `reporter` to initializer and then call `
105
111
  CircuitSwitch.report(if: some_condition)
106
112
  ```
107
113
 
108
- `report` just reports the line of code is called. It doesn't receive proc. It's useful for refactoring or removing dead codes.
109
- 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.
110
- `report` receives optional arguments.
114
+ `report` just reports which line of code is called. It doesn't receive proc. It's useful for refactoring or removing dead codes.
115
+ Same as `run`, a set of options can be set. By default, this method does not send reports more than 10 times. The constant 10 comes from the table definition we have arbitrarily chosen. In case you need a larger number, specify it in the `limit_count` option, or alter default constraint on `circuit_switches.report_limit_count`.
111
116
 
112
- - `key`: [String] Named key to find switch instead of caller
113
- If no key passed, use caller.
114
- - `if`: [Boolean, Proc] Report when `if` is truthy (default: true)
115
- - `stop_report_if`: [Boolean, Proc] Report when `close_if` is falsy (default: false)
116
- - `stop_report_if_reach_limit`: [Boolean] Stop reporting when reported count reaches limit (default: true)
117
- - `limit_count`: [Integer] Limit count. Use `report_limit_count` default value if it's nil (default: nil)
118
- Can't be set 0 when `stop_report_if_reach_limit` is true
117
+ - `key`: [String] The identifier to find record by. If `key` has not been passed, `circuit_switches.caller` is chosen as an alternative.
118
+ - `if`: [Boolean, Proc] Reports when the value of `if` is evaluated truthy (default: true)
119
+ - `stop_report_if`: [Boolean, Proc] Reports when the value of `stop_report_if` is evaluated falsy (default: false)
120
+ - `stop_report_if_reach_limit`: [Boolean] Stops reporting when `circuit_switches.report_count` has reached `circuit_switches.report_limit_count` (default: true)
121
+ - `limit_count`: [Integer] Mutates `circuit_switches.report_limit_count` whose value defined in schema is 10 by default. (default: nil)
122
+ Can't be set to 0 when `stop_report_if_reach_limit` is true.
119
123
 
120
- To know about report is executed or not, you can get through `report?`.
124
+ To know if `report` has already been executed or not, you can get through `reported?`.
121
125
  Of course you can chain `report` and `run` or `open?`.
122
126
 
123
127
  #### `with_backtrace`
@@ -134,6 +138,24 @@ called_path: /app/services/greetings_service:21 block in validate
134
138
  /app/controllers/greetings_controller.rb:93 create
135
139
  ```
136
140
 
141
+ ## Test
142
+
143
+ To test, FactoryBot will look like this;
144
+
145
+ ```ruby
146
+ FactoryBot.define do
147
+ factory :circuit_switch, class: 'CircuitSwitch::CircuitSwitch' do
148
+ sequence(:key) { |n| "/path/to/file:#{n}" }
149
+ sequence(:caller) { |n| "/path/to/file:#{n}" }
150
+ due_date { Date.tomorrow }
151
+
152
+ trait :initially_closed do
153
+ run_is_terminated { true }
154
+ end
155
+ end
156
+ end
157
+ ```
158
+
137
159
  ## Task
138
160
 
139
161
  When find a problem and you want to terminate running or reporting right now, execute a task with it's caller.
@@ -158,7 +180,27 @@ By default, due_date is 10 days after today. To modify, set `due_date` to initia
158
180
 
159
181
  ## GUI to manage switches
160
182
 
161
- Under development :)
183
+ ![GUI](circuit_switch.png)
184
+
185
+ GUI is now only for Rails.
186
+ Add the following to your `config/routes.rb` and access `/circuit_switch`.
187
+
188
+ ```ruby
189
+ Rails.application.routes.draw do
190
+ mount CircuitSwitch::Engine => 'circuit_switch'
191
+ end
192
+ ```
193
+
194
+ ### Authentication
195
+
196
+ In production, you may need access protection.
197
+ With Devise, code goes like:
198
+
199
+ ```ruby
200
+ authenticate :user, lambda { |user| user.admin? } do
201
+ mount CircuitSwitch::Engine => 'circuit_switch'
202
+ end
203
+ ```
162
204
 
163
205
  ## Contributing
164
206
 
@@ -0,0 +1,5 @@
1
+ module CircuitSwitch
2
+ class ApplicationController < ActionController::Base
3
+ protect_from_forgery with: :exception
4
+ end
5
+ end
@@ -0,0 +1,40 @@
1
+ require_dependency 'circuit_switch/application_controller'
2
+
3
+ module CircuitSwitch
4
+ class CircuitSwitchController < ::CircuitSwitch::ApplicationController
5
+ def index
6
+ @circuit_switches = ::CircuitSwitch::CircuitSwitch.all.order(order_by)
7
+ end
8
+
9
+ def edit
10
+ @circuit_switch = ::CircuitSwitch::CircuitSwitch.find(params[:id])
11
+ end
12
+
13
+ def update
14
+ @circuit_switch = ::CircuitSwitch::CircuitSwitch.find(params[:id])
15
+ if @circuit_switch.update circuit_switch_params
16
+ flash[:success] = "Switch for `#{@circuit_switch.key}` is successfully updated."
17
+ redirect_to circuit_switch_index_path
18
+ else
19
+ render :edit
20
+ end
21
+ end
22
+
23
+ def destroy
24
+ @circuit_switch = ::CircuitSwitch::CircuitSwitch.find(params[:id])
25
+ @circuit_switch.destroy!
26
+ flash[:success] = "Switch for `#{@circuit_switch.key}` is successfully destroyed."
27
+ redirect_to circuit_switch_index_path
28
+ end
29
+
30
+ private
31
+
32
+ def order_by
33
+ params[:order_by].in?(%w[id due_date]) ? params[:order_by] : 'id'
34
+ end
35
+
36
+ def circuit_switch_params
37
+ params.require(:circuit_switch).permit(:key, :caller, :run_count, :run_limit_count, :run_is_terminated, :report_count, :report_limit_count, :report_is_terminated, :due_date)
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,129 @@
1
+ <h1 class="p-3 fw-light">Edit switch</h1>
2
+
3
+ <div class="container">
4
+ <% if @circuit_switch.errors.any? %>
5
+ <div class="alert alert-danger">
6
+ <ul class="mb-0">
7
+ <% @circuit_switch.errors.full_messages.each do |message| %>
8
+ <li><%= message %></li>
9
+ <% end %>
10
+ </ul>
11
+ </div>
12
+ <% end %>
13
+
14
+ <%= form_with(model: @circuit_switch, local: true) do |form| %>
15
+ <div class="fw-light">
16
+ <div class="py-1 row">
17
+ <div class="col-10 mt-auto">
18
+ id: <%= @circuit_switch.id %>
19
+ <span class="px-4 text-muted">
20
+ created_at: <%= @circuit_switch.created_at %> /
21
+ updated_at: <%= @circuit_switch.updated_at %>
22
+ </span>
23
+ </div>
24
+ <div class="col-2 text-end">
25
+ <%= link_to 'Back', circuit_switch_index_path, class: 'btn btn-outline-dark' %>
26
+ </div>
27
+ </div>
28
+
29
+ <div class="py-1">
30
+ <div class="py-1">
31
+ <%= form.label :key, 'key:', class: 'form-label' %>
32
+ <%= form.text_area :key, class: 'form-control font-monospace' %>
33
+ </div>
34
+ <div class="py-1">
35
+ <%= form.label :caller, 'caller:', class: 'form-label' %>
36
+ <%= form.text_area :caller, class: 'form-control font-monospace' %>
37
+ </div>
38
+ </div>
39
+
40
+ <div class="py-1">
41
+ <div class="py-2 row">
42
+ <%= form.label :run_is_terminated, 'run_mode:', class: 'col-sm-2 col-form-label' %>
43
+ <div class="col-sm-2">
44
+ <%= form.select :run_is_terminated, { open: false, closed: true }, { selected: @circuit_switch.run_is_terminated }, { class: ['form-select', (@circuit_switch.run_is_terminated ? 'alert-dark' : 'alert-primary')] } %>
45
+ </div>
46
+ </div>
47
+ <div class="py-2 row">
48
+ <div class="col-sm-2">
49
+ <%= form.label :run_count, 'run_count:', class: 'col-form-label' %>
50
+ <i class="fas fa-info-circle text-black-50 align-baseline px-1" data-bs-toggle="tooltip" data-bs-placement="top" title="Increment only when run_mode is open"></i>
51
+ </div>
52
+ <div class="col-sm-2">
53
+ <%= form.text_field :run_count, class: 'form-control' %>
54
+ </div>
55
+ </div>
56
+ <div class="py-2 row">
57
+ <div class="col-sm-2">
58
+ <%= form.label :run_limit_count, 'run_limit_count:', class: 'col-form-label' %>
59
+ <i class="fas fa-info-circle text-black-50 align-baseline px-1" data-bs-toggle="tooltip" data-bs-placement="top" title="Reference only when call with `close_if_reach_limit` true"></i>
60
+ </div>
61
+ <div class="col-sm-2">
62
+ <%= form.text_field :run_limit_count, class: 'form-control' %>
63
+ </div>
64
+ </div>
65
+ <div class="py-2 row">
66
+ <%= form.label :report_is_terminated, 'report_mode:', class: 'col-sm-2 col-sm-2 col-form-label' %>
67
+ <div class="col-sm-2">
68
+ <%= form.select :report_is_terminated, { reporting: false, terminated: true }, { selected: @circuit_switch.report_is_terminated }, { class: ['form-select', (@circuit_switch.report_is_terminated ? 'alert-dark' : 'alert-primary')] } %>
69
+ </div>
70
+ </div>
71
+ <div class="py-2 row">
72
+ <div class="col-sm-2">
73
+ <%= form.label :report_count, 'report_count:', class: 'col-form-label' %>
74
+ <i class="fas fa-info-circle text-black-50 align-baseline px-1" data-bs-toggle="tooltip" data-bs-placement="top" title="Increment only when report_mode is reporting"></i>
75
+ </div>
76
+ <div class="col-sm-2">
77
+ <%= form.text_field :report_count, class: 'form-control' %>
78
+ </div>
79
+ </div>
80
+ <div class="py-2 row">
81
+ <div class="col-sm-2">
82
+ <%= form.label :report_limit_count, 'report_limit_count:', class: 'col-form-label' %>
83
+ <i class="fas fa-info-circle text-black-50 align-baseline px-1" data-bs-toggle="tooltip" data-bs-placement="top" title="Reference only when call with `stop_report_if_reach_limit` true"></i>
84
+ </div>
85
+ <div class="col-sm-2">
86
+ <%= form.text_field :report_limit_count, class: 'form-control' %>
87
+ </div>
88
+ </div>
89
+ </div>
90
+
91
+ <div class="py-1">
92
+ <div class="py-2 row">
93
+ <div class="col-sm-2">
94
+ <%= form.label :due_date, 'due_date:', class: 'col-form-label' %>
95
+ <i class="fas fa-info-circle text-black-50 align-baseline px-1" data-bs-toggle="tooltip" data-bs-placement="top" title="Date to remove switch"></i>
96
+ </div>
97
+ <div class="col-sm-2">
98
+ <%= form.text_field :due_date, class: 'form-control' %>
99
+ </div>
100
+ </div>
101
+ </div>
102
+
103
+ <div class="py-2">
104
+ <%= form.submit 'update', class: 'btn btn-dark' %>
105
+ </div>
106
+ </div>
107
+ <% end %>
108
+
109
+ <%= button_to 'delete', circuit_switch_path(@circuit_switch), method: :delete, class: 'btn btn-danger btn-destroy' %>
110
+ </div>
111
+
112
+ <script>
113
+ $('select').on('change', function() {
114
+ style = $(this).val() == 'true' ? 'alert-dark' : 'alert-primary'
115
+ $(this).removeClass('alert-primary alert-dark')
116
+ $(this).addClass(style)
117
+ })
118
+
119
+ $('.btn-destroy').on('click', function (event) {
120
+ if (!window.confirm('Are you sure to destroy?')) {
121
+ event.preventDefault()
122
+ }
123
+ })
124
+
125
+ tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
126
+ tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
127
+ return new bootstrap.Tooltip(tooltipTriggerEl)
128
+ })
129
+ </script>
@@ -0,0 +1,83 @@
1
+ <h1 class="p-3 fw-light">
2
+ circuit_switch <i class="fas fa-xs fa-toggle-on text-warning"></i>
3
+ </h1>
4
+
5
+ <div class="container">
6
+ <% if flash[:success].present? %>
7
+ <div class="alert alert-info"><%= flash[:success] %></div>
8
+ <% end %>
9
+
10
+ <div class="dropdown py-2 text-end">
11
+ <a class="btn btn-sm btn-outline-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
12
+ <%= params[:order_by] == 'due_date' ? 'due date ordered' : 'id ordered' %>
13
+ </a>
14
+
15
+ <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
16
+ <li><%= link_to 'id ordered', circuit_switch_index_path(order_by: :id), class: 'dropdown-item' %></li>
17
+ <li><%= link_to 'due date ordered', circuit_switch_index_path(order_by: :due_date), class: 'dropdown-item' %></li>
18
+ </ul>
19
+ </div>
20
+
21
+ <table class="table table-striped table-hover striped-primary table-bordered border fw-light">
22
+ <thead class="table-dark border border-dark">
23
+ <tr>
24
+ <th scope="col" class="px-3 py-4 fw-light text-center">id</th>
25
+ <th scope="col" class="px-3 py-4 fw-light">key</th>
26
+ <th scope="col" class="px-3 py-4 fw-light">caller</th>
27
+ <th scope="col" class="px-1 py-4 fw-light">due_date</th>
28
+ <th scope="col" class="px-3 py-4 fw-light text-center">run</th>
29
+ <th scope="col" class="px-3 py-4 fw-light text-center">report</th>
30
+ <th scope="col" class="px-3 py-4 fw-light text-center">show/edit</th>
31
+ <th scope="col" class="px-3 py-4 fw-light text-center">destroy</th>
32
+ </tr>
33
+ </thead>
34
+
35
+ <tbody>
36
+ <% @circuit_switches.each do |circuit_switch| %>
37
+ <tr>
38
+ <td class="text-center align-middle"><%= circuit_switch.id %></td>
39
+ <td class="text-break small font-monospace"><%= circuit_switch.key %></td>
40
+ <td class="text-break small font-monospace"><%= circuit_switch.caller %></td>
41
+ <td class="text-nowrap"><%= circuit_switch.due_date %></td>
42
+ <td class="text-center align-middle">
43
+ <% if circuit_switch.run_is_terminated %>
44
+ <i class="fas fa-lg fa-ban text-muted" data-bs-toggle="tooltip" data-bs-placement="top" title="closed mode"></i>
45
+ <% else %>
46
+ <i class="fas fa-lg fa-walking " data-bs-toggle="tooltip" data-bs-placement="top" title="opened mode"></i>
47
+ <% end %>
48
+ </td>
49
+ <td class="text-center align-middle">
50
+ <% if circuit_switch.report_is_terminated %>
51
+ <i class="fas fa-lg fa-ban text-muted" data-bs-toggle="tooltip" data-bs-placement="top" title="terminated mode"></i>
52
+ <% else %>
53
+ <i class="fas fa-lg fa-bullhorn " data-bs-toggle="tooltip" data-bs-placement="top" title="reporting mode"></i>
54
+ <% end %>
55
+ </td>
56
+ <td class="text-center align-middle py-3">
57
+ <%= button_to edit_circuit_switch_path(circuit_switch), method: :get, class: 'btn btn-outline-dark' do %>
58
+ <i class="fas fa-edit"></i>
59
+ <% end %>
60
+ </td>
61
+ <td class="text-center align-middle py-3">
62
+ <%= button_to circuit_switch_path(circuit_switch), method: :delete, class: 'btn btn-danger btn-destroy' do %>
63
+ <i class="fas fa-broom"></i>
64
+ <% end %>
65
+ </td>
66
+ </tr>
67
+ <% end %>
68
+ </tbody>
69
+ </table>
70
+ </div>
71
+
72
+ <script>
73
+ $('.btn-destroy').on('click', function (event) {
74
+ if (!window.confirm('Are you sure to destroy?')) {
75
+ event.preventDefault()
76
+ }
77
+ })
78
+
79
+ tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
80
+ tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
81
+ return new bootstrap.Tooltip(tooltipTriggerEl)
82
+ })
83
+ </script>
@@ -0,0 +1,16 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset='utf-8'>
5
+ <title>circuit_switch</title>
6
+ <%= csrf_meta_tags %>
7
+ <%= csp_meta_tag %>
8
+ <%= javascript_include_tag 'https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js', integrity: 'sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW', crossorigin: 'anonymous' %>
9
+ <%= javascript_include_tag 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js' %>
10
+ <%= javascript_include_tag 'https://kit.fontawesome.com/3e20336786.js', crossorigin: 'anonymous' %>
11
+ <%= stylesheet_link_tag 'https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css', media: 'all', integrity: 'sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1', crossorigin: 'anonymous' %>
12
+ </head>
13
+ <body>
14
+ <%= yield %>
15
+ </body>
16
+ </html>
Binary file
data/config/routes.rb ADDED
@@ -0,0 +1,4 @@
1
+ CircuitSwitch::Engine.routes.draw do
2
+ resources 'circuit_switch', only: [:index, :edit, :update, :destroy], controller: 'circuit_switch'
3
+ root to: 'circuit_switch#index'
4
+ end
@@ -46,7 +46,7 @@ module CircuitSwitch
46
46
  close_if_reach_limit: close_if_reach_limit,
47
47
  limit_count: limit_count,
48
48
  initially_closed: initially_closed,
49
- }.select { |_, v| v }
49
+ }.reject { |_, v| v.nil? }
50
50
  assign_runner(**arguments)
51
51
  execute_run(&block)
52
52
  end
@@ -58,7 +58,7 @@ module CircuitSwitch
58
58
  stop_report_if: stop_report_if,
59
59
  stop_report_if_reach_limit: stop_report_if_reach_limit,
60
60
  limit_count: limit_count
61
- }.select { |_, v| v }
61
+ }.reject { |_, v| v.nil? }
62
62
  assign_reporter(**arguments)
63
63
  execute_report
64
64
  end
@@ -1,5 +1,3 @@
1
- require 'active_support/core_ext/module/aliasing'
2
-
3
1
  module CircuitSwitch
4
2
  class Configuration
5
3
  CIRCUIT_SWITCH = 'circuit_switch'.freeze
@@ -9,6 +9,7 @@ module CircuitSwitch
9
9
  :report_if, :stop_report_if, :stop_report_if_reach_limit, :report_limit_count
10
10
 
11
11
  def execute_run(&block)
12
+ run_executable = false
12
13
  if close_if_reach_limit && run_limit_count == 0
13
14
  raise CircuitSwitchError.new('Can\'t set limit_count to 0 when close_if_reach_limit is true')
14
15
  end
@@ -21,24 +22,31 @@ module CircuitSwitch
21
22
  return self if close_if_reach_limit && switch.reached_run_limit?(run_limit_count)
22
23
  return self if switch.run_is_terminated?
23
24
 
25
+ run_executable = true
24
26
  unless switch.new_record? && initially_closed
25
27
  yield
26
28
  @run = true
27
29
  end
28
- RunCountUpdater.perform_later(
29
- key: key,
30
- limit_count: run_limit_count,
31
- called_path: called_path,
32
- reported: reported?,
33
- initially_closed: initially_closed
34
- )
35
30
  self
31
+ ensure
32
+ if run_executable
33
+ RunCountUpdater.perform_later(
34
+ key: key,
35
+ limit_count: run_limit_count,
36
+ called_path: called_path,
37
+ reported: reported?,
38
+ initially_closed: initially_closed
39
+ )
40
+ end
36
41
  end
37
42
 
38
43
  def execute_report
39
44
  if config.reporter.nil?
40
45
  raise CircuitSwitchError.new('Set config.reporter.')
41
46
  end
47
+ if config.reporter.arity == 1
48
+ Logger.new($stdout).info('config.reporter now receives 2 arguments. Improve your `config/initialzers/circuit_switch.rb`.')
49
+ end
42
50
  if stop_report_if_reach_limit && report_limit_count == 0
43
51
  raise CircuitSwitchError.new('Can\'t set limit_count to 0 when stop_report_if_reach_limit is true')
44
52
  end
@@ -51,6 +59,7 @@ module CircuitSwitch
51
59
  key: key,
52
60
  limit_count: report_limit_count,
53
61
  called_path: called_path,
62
+ stacktrace: StacktraceModifier.call(backtrace: caller),
54
63
  run: run?
55
64
  )
56
65
  @reported = true
@@ -0,0 +1,9 @@
1
+ module CircuitSwitch
2
+ def self.table_name_prefix
3
+ ''
4
+ end
5
+
6
+ class Engine < ::Rails::Engine
7
+ isolate_namespace ::CircuitSwitch
8
+ end
9
+ end
@@ -10,7 +10,7 @@ module CircuitSwitch
10
10
  class CalledNotification < CircuitSwitchNotification
11
11
  def to_message(called_path:)
12
12
  if ::CircuitSwitch.config.with_backtrace
13
- "#{message}\ncalled_path: #{called_path}\n#{StacktraceModifier.call(backtrace: backtrace)}"
13
+ "#{message}\ncalled_path: #{called_path}\n#{backtrace.join("\n")}"
14
14
  else
15
15
  message
16
16
  end
@@ -2,6 +2,8 @@ require 'active_record'
2
2
 
3
3
  module CircuitSwitch
4
4
  class CircuitSwitch < ::ActiveRecord::Base
5
+ validates :key, uniqueness: true
6
+
5
7
  after_initialize do |switch|
6
8
  switch.key ||= switch.caller
7
9
  end
@@ -28,11 +30,11 @@ module CircuitSwitch
28
30
  end
29
31
  end
30
32
 
31
- def increment_run_count
33
+ def increment_run_count!
32
34
  with_writable { update!(run_count: run_count + 1) }
33
35
  end
34
36
 
35
- def increment_report_count
37
+ def increment_report_count!
36
38
  with_writable { update!(report_count: report_count + 1) }
37
39
  end
38
40
 
@@ -6,10 +6,14 @@ module CircuitSwitch
6
6
  delegate :config, to: ::CircuitSwitch
7
7
 
8
8
  def call(backtrace:)
9
- backtrace
10
- .select { |path| /(#{config.allowed_backtrace_paths.join('|')})/.match?(path) }
11
- .map { |path| path.sub(/(#{config.strip_paths.join('|')})/, '') }
12
- .join("\n")
9
+ if config.with_backtrace
10
+ backtrace
11
+ .select { |path| /(#{config.allowed_backtrace_paths.join('|')})/.match?(path) }
12
+ .map { |path| path.sub(/(#{config.strip_paths.join('|')})/, '') }
13
+ else
14
+ backtrace
15
+ .select { |path| /(#{config.allowed_backtrace_paths.join('|')})/.match?(path) }
16
+ end
13
17
  end
14
18
  end
15
19
  end
@@ -1,3 +1,3 @@
1
1
  module CircuitSwitch
2
- VERSION = '0.2.2'
2
+ VERSION = '0.5.0'
3
3
  end
@@ -5,21 +5,35 @@ module CircuitSwitch
5
5
  class Reporter < ::ActiveJob::Base
6
6
  delegate :config, to: ::CircuitSwitch
7
7
 
8
- def perform(key:, limit_count:, called_path:, run:)
8
+ def perform(key:, limit_count:, called_path:, stacktrace:, run:)
9
9
  # Wait for RunCountUpdater saves circuit_switch
10
10
  sleep(3) if run
11
11
 
12
- circuit_switch = key ? CircuitSwitch.find_by(key: key) : CircuitSwitch.find_by(caller: called_path)
13
- if run && circuit_switch.nil?
14
- raise ActiveRecord::RecordNotFound.new('Couldn\'t find CircuitSwitch::CircuitSwitch')
15
- end
12
+ first_raise = true
13
+ begin
14
+ circuit_switch = key ? CircuitSwitch.find_by(key: key) : CircuitSwitch.find_by(caller: called_path)
15
+ if run && circuit_switch.nil?
16
+ raise ActiveRecord::RecordNotFound.new('Couldn\'t find CircuitSwitch::CircuitSwitch')
17
+ end
18
+
19
+ circuit_switch ||= CircuitSwitch.new(key: key, caller: called_path)
20
+ circuit_switch.due_date ||= config.due_date
21
+ circuit_switch.assign(report_limit_count: limit_count).increment_report_count!
22
+ raise CalledNotification.new(circuit_switch.message)
23
+ rescue ActiveRecord::RecordInvalid => e
24
+ raise e unless first_raise
16
25
 
17
- circuit_switch ||= CircuitSwitch.new(key: key, caller: called_path)
18
- circuit_switch.due_date ||= config.due_date
19
- circuit_switch.assign(report_limit_count: limit_count).increment_report_count
20
- raise CalledNotification.new(circuit_switch.message)
21
- rescue CalledNotification => notification
22
- config.reporter.call(notification.to_message(called_path: called_path))
26
+ first_raise = false
27
+ sleep(2)
28
+ retry
29
+ rescue CalledNotification => notification
30
+ notification.set_backtrace(stacktrace)
31
+ if config.reporter.arity == 1
32
+ config.reporter.call(notification.to_message(called_path: called_path))
33
+ else
34
+ config.reporter.call(notification.to_message(called_path: called_path), notification)
35
+ end
36
+ end
23
37
  end
24
38
  end
25
39
  end
@@ -9,14 +9,23 @@ module CircuitSwitch
9
9
  # Wait for Reporter saves circuit_switch
10
10
  sleep(3) if reported
11
11
 
12
- circuit_switch = key ? CircuitSwitch.find_by(key: key) : CircuitSwitch.find_by(caller: called_path)
13
- if reported && circuit_switch.nil?
14
- raise ActiveRecord::RecordNotFound.new('Couldn\'t find CircuitSwitch::CircuitSwitch')
15
- end
12
+ first_raise = true
13
+ begin
14
+ circuit_switch = key ? CircuitSwitch.find_by(key: key) : CircuitSwitch.find_by(caller: called_path)
15
+ if reported && circuit_switch.nil?
16
+ raise ActiveRecord::RecordNotFound.new('Couldn\'t find CircuitSwitch::CircuitSwitch')
17
+ end
18
+
19
+ circuit_switch ||= CircuitSwitch.new(key: key, caller: called_path, run_is_terminated: initially_closed)
20
+ circuit_switch.due_date ||= config.due_date
21
+ circuit_switch.assign(run_limit_count: limit_count).increment_run_count!
22
+ rescue ActiveRecord::RecordInvalid => e
23
+ raise e unless first_raise
16
24
 
17
- circuit_switch ||= CircuitSwitch.new(key: key, caller: called_path, run_is_terminated: initially_closed)
18
- circuit_switch.due_date ||= config.due_date
19
- circuit_switch.assign(run_limit_count: limit_count).increment_run_count
25
+ first_raise = false
26
+ sleep(2)
27
+ retry
28
+ end
20
29
  end
21
30
  end
22
31
  end
@@ -1,6 +1,7 @@
1
1
  require_relative 'circuit_switch/configuration'
2
2
  require_relative 'circuit_switch/builder'
3
3
  require_relative 'circuit_switch/orm/active_record/circuit_switch'
4
+ require_relative 'circuit_switch/engine' if defined?(Rails)
4
5
  require_relative 'circuit_switch/railtie' if defined?(Rails::Railtie)
5
6
  require_relative 'circuit_switch/version'
6
7
  require_relative 'circuit_switch/workers/due_date_notifier'
@@ -31,7 +32,7 @@ module CircuitSwitch
31
32
  close_if_reach_limit: close_if_reach_limit,
32
33
  limit_count: limit_count,
33
34
  initially_closed: initially_closed,
34
- }.select { |_, v| v }
35
+ }.reject { |_, v| v.nil? }
35
36
  Builder.new.run(**arguments, &block)
36
37
  end
37
38
 
@@ -52,7 +53,7 @@ module CircuitSwitch
52
53
  stop_report_if: stop_report_if,
53
54
  stop_report_if_reach_limit: stop_report_if_reach_limit,
54
55
  limit_count: limit_count
55
- }.select { |_, v| v }
56
+ }.reject { |_, v| v.nil? }
56
57
  Builder.new.report(**arguments)
57
58
  end
58
59
 
@@ -76,7 +77,7 @@ module CircuitSwitch
76
77
  close_if_reach_limit: close_if_reach_limit,
77
78
  limit_count: limit_count,
78
79
  initially_closed: initially_closed,
79
- }.select { |_, v| v }
80
+ }.reject { |_, v| v.nil? }
80
81
  Builder.new.run(**arguments) {}.run?
81
82
  end
82
83
  end
@@ -5,12 +5,15 @@ module CircuitSwitch
5
5
  desc 'Create a migration to manage circuit switches state'
6
6
  source_root File.expand_path('templates', __dir__)
7
7
  argument :migration_type, required: false, type: :array, default: ['create'],
8
- desc: 'Type of migration to create or add key column. By default to create.',
8
+ desc: 'Type of migration to create or add key column or make key unique. By default to create.',
9
9
  banner: 'create or add_key'
10
10
 
11
11
  def generate_migration
12
- if migration_type == ['add_key']
12
+ case migration_type
13
+ when ['add_key']
13
14
  migration_template 'add_key.rb.erb', 'db/migrate/add_key_to_circuit_switches.rb', migration_version: migration_version
15
+ when ['make_key_unique']
16
+ migration_template 'make_key_unique.rb.erb', 'db/migrate/make_key_unique_for_circuit_switches.rb', migration_version: migration_version
14
17
  else
15
18
  migration_template 'migration.rb.erb', 'db/migrate/create_circuit_switches.rb', migration_version: migration_version
16
19
  end
@@ -2,7 +2,8 @@
2
2
 
3
3
  CircuitSwitch.configure do |config|
4
4
  # Specify proc to call your report tool: like;
5
- # config.reporter = -> (message) { Bugsnag.notify(message) }
5
+ # config.reporter = -> (message, error) { Bugsnag.notify(error) }
6
+ # config.reporter = -> (message, error) { Sentry::Rails.capture_message(message) }
6
7
  config.reporter = nil
7
8
 
8
9
  # Condition to report
@@ -29,11 +30,10 @@ CircuitSwitch.configure do |config|
29
30
 
30
31
  # Option to contain error backtrace for report
31
32
  # You don't need backtrace when you report to some bug report tool.
32
- # You may be want backtrace when report to plain feed; e.g. Slack or email.
33
+ # You may want backtrace when reporting to a plain feed; e.g. Slack or email.
33
34
  # config.with_backtrace = false
34
35
 
35
36
  # Allowed backtrace paths to report
36
- # Specify with `with_backtrace` option.
37
37
  # Allowed all paths when set `[]`.
38
38
  # config.allowed_backtrace_paths = [Dir.pwd]
39
39
 
@@ -0,0 +1,11 @@
1
+ class MakeKeyUniqueForCircuitSwitches < ActiveRecord::Migration<%= migration_version %>
2
+ def up
3
+ remove_index :circuit_switches, :key
4
+ add_index :circuit_switches, :key, unique: true
5
+ end
6
+
7
+ def down
8
+ remove_index :circuit_switches, :key
9
+ add_index :circuit_switches, :key
10
+ end
11
+ end
@@ -1,7 +1,7 @@
1
1
  class CreateCircuitSwitches < ActiveRecord::Migration<%= migration_version %>
2
2
  def change
3
3
  create_table :circuit_switches do |t|
4
- t.string :key, null: false, index: true
4
+ t.string :key, null: false
5
5
  t.string :caller, null: false
6
6
  t.integer :run_count, default: 0, null: false
7
7
  t.integer :run_limit_count, default: 10, null: false
@@ -12,5 +12,7 @@ class CreateCircuitSwitches < ActiveRecord::Migration<%= migration_version %>
12
12
  t.date :due_date, null: false
13
13
  t.timestamps
14
14
  end
15
+
16
+ add_index :circuit_switches, [:key], unique: true
15
17
  end
16
18
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: circuit_switch
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.2
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - makicamel
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2021-10-31 00:00:00.000000000 Z
11
+ date: 2021-11-21 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activejob
@@ -124,13 +124,21 @@ files:
124
124
  - LICENSE.txt
125
125
  - README.md
126
126
  - Rakefile
127
+ - app/controllers/circuit_switch/application_controller.rb
128
+ - app/controllers/circuit_switch/circuit_switch_controller.rb
129
+ - app/views/circuit_switch/circuit_switch/edit.html.erb
130
+ - app/views/circuit_switch/circuit_switch/index.html.erb
131
+ - app/views/layouts/circuit_switch/application.html.erb
127
132
  - bin/console
128
133
  - bin/setup
129
134
  - circuit_switch.gemspec
135
+ - circuit_switch.png
136
+ - config/routes.rb
130
137
  - lib/circuit_switch.rb
131
138
  - lib/circuit_switch/builder.rb
132
139
  - lib/circuit_switch/configuration.rb
133
140
  - lib/circuit_switch/core.rb
141
+ - lib/circuit_switch/engine.rb
134
142
  - lib/circuit_switch/notification.rb
135
143
  - lib/circuit_switch/orm/active_record/circuit_switch.rb
136
144
  - lib/circuit_switch/railtie.rb
@@ -145,6 +153,7 @@ files:
145
153
  - lib/generators/circuit_switch/migration_generator.rb
146
154
  - lib/generators/circuit_switch/templates/add_key.rb.erb
147
155
  - lib/generators/circuit_switch/templates/initializer.rb
156
+ - lib/generators/circuit_switch/templates/make_key_unique.rb.erb
148
157
  - lib/generators/circuit_switch/templates/migration.rb.erb
149
158
  homepage: https://github.com/makicamel/circuit_switch
150
159
  licenses: