performance_promise 0.0.1

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.
@@ -0,0 +1,30 @@
1
+ module ValidateNumberOfQueries
2
+ def validate_makes(db_queries, render_time, makes)
3
+ makes = makes.evaluate # force evaluation of lazy evaluated promise
4
+
5
+ passes = (db_queries.length <= makes)
6
+ error_message = ''
7
+ backtrace = []
8
+
9
+ if passes
10
+ return passes, error_message, backtrace
11
+ end
12
+
13
+ guessed_order = Utils.guess_order(db_queries)
14
+ error_message = "promised #{makes}, made #{db_queries.length} (possibly #{guessed_order})"
15
+ backtrace = []
16
+ Utils.summarize_queries(db_queries).each do |db_query, count|
17
+ statement = "#{count} x #{db_query[:sql]}"
18
+ backtrace << statement
19
+ db_query[:trace].each do |trace|
20
+ if trace.starts_with?('app')
21
+ file, line_number = trace.split(':')
22
+ trace = " |_" + File.read(file).split("\n")[line_number.to_i - 1].strip + ' (' + trace + ')'
23
+ end
24
+ backtrace << trace
25
+ end
26
+ end
27
+
28
+ return passes, error_message, backtrace
29
+ end
30
+ end
@@ -0,0 +1,13 @@
1
+ module ValidateTimeTakenForRender
2
+ def validate_takes(db_queries, render_time, takes)
3
+ passes = (render_time <= takes)
4
+ error_message = ''
5
+ backtrace = []
6
+
7
+ unless passes
8
+ error_message = "promised #{takes} seconds, took #{render_time} seconds"
9
+ end
10
+
11
+ return passes, error_message, backtrace
12
+ end
13
+ end
@@ -0,0 +1,116 @@
1
+ require 'performance_promise/decorators'
2
+ require 'performance_promise/sql_recorder.rb'
3
+ require 'performance_promise/utils.rb'
4
+ require 'performance_promise/lazily_evaluated.rb'
5
+ require 'performance_promise/performance_validations.rb'
6
+
7
+ module PerformancePromise
8
+ class << self
9
+ attr_accessor :configuration
10
+ end
11
+
12
+ def self.configure
13
+ self.configuration ||= Configuration.new
14
+ yield(configuration)
15
+ end
16
+
17
+ def self.start
18
+ return unless PerformancePromise.configuration.enable
19
+ return unless PerformancePromise.configuration.allowed_environments.include?(Rails.env)
20
+
21
+ ActiveSupport::Notifications.subscribe "sql.active_record" do |name, start, finish, id, payload|
22
+ SQLRecorder.instance.record(payload, finish - start)
23
+ end
24
+
25
+ ActiveSupport::Notifications.subscribe "start_processing.action_controller" do |name, start, finish, id, payload|
26
+ SQLRecorder.instance.flush
27
+ end
28
+
29
+ ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, start, finish, id, payload|
30
+ db_queries = SQLRecorder.instance.flush
31
+ render_time = finish - start
32
+ method_name = "#{payload[:controller]}\##{payload[:action]}"
33
+ promised = PerformancePromise.promises[method_name]
34
+ if promised
35
+ PerformancePromise::validate_promise(method_name, db_queries, render_time, promised)
36
+ elsif PerformancePromise.configuration.untagged_methods_are_speedy
37
+ PerformancePromise.configuration.logger.warn 'No promises made. Assuming Speedy'
38
+ promised = PerformancePromise.configuration.speedy_promise
39
+ PerformancePromise::validate_promise(method_name, db_queries, render_time, promised)
40
+ end
41
+ end
42
+ end
43
+
44
+ class Configuration
45
+ attr_accessor :enable
46
+ attr_accessor :validations
47
+ attr_accessor :logger
48
+ attr_accessor :allowed_environments
49
+ attr_accessor :speedy_promise
50
+ attr_accessor :untagged_methods_are_speedy
51
+ attr_accessor :throw_exception
52
+
53
+ def initialize
54
+ # Set default values
55
+ @enable = false
56
+ @validations = [
57
+ :makes,
58
+ ]
59
+ @logger = Rails.logger
60
+ @allowed_environments = [
61
+ 'development',
62
+ 'test',
63
+ ]
64
+ @untagged_methods_are_speedy = false
65
+ @speedy_promise = {
66
+ :makes => 1.query,
67
+ :takes => 1.second,
68
+ }
69
+ @throw_exception = true
70
+ end
71
+ end
72
+
73
+ class BrokenPromise < RuntimeError
74
+ end
75
+
76
+ @@promises = {}
77
+
78
+ def self.promises
79
+ @@promises
80
+ end
81
+
82
+ def self.validate_promise(method, db_queries, render_time, options)
83
+ return if options[:skip]
84
+ promise_broken = false
85
+ self.configuration.validations.each do |validation|
86
+ promised = options[validation]
87
+ if promised
88
+ validation_method = 'validate_' + validation.to_s
89
+ passed, error_message, backtrace =
90
+ PerformanceValidations.send(validation_method, db_queries, render_time, promised)
91
+ unless passed
92
+ if PerformancePromise.configuration.throw_exception
93
+ bp = BrokenPromise.new("Broken promise: #{error_message}")
94
+ bp.set_backtrace(backtrace)
95
+ raise bp
96
+ else
97
+ PerformancePromise.configuration.logger.warn '-' * 80
98
+ PerformancePromise.configuration.logger.warn Utils.colored(:red, error_message)
99
+ backtrace.each do |trace|
100
+ PerformancePromise.configuration.logger.warn Utils.colored(:cyan, error_message)
101
+ end
102
+ PerformancePromise.configuration.logger.warn '-' * 80
103
+ end
104
+ promise_broken = true
105
+ end
106
+ end
107
+ end
108
+ PerformanceValidations.report_promise_passed(method, db_queries, options) unless promise_broken
109
+ end
110
+
111
+ end
112
+
113
+
114
+ class ApplicationController < ActionController::Base
115
+ extend MethodDecorators
116
+ end
@@ -0,0 +1,13 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = 'performance_promise'
3
+ s.version = '0.0.1'
4
+ s.date = '2015-12-14'
5
+ s.summary = 'Validate your Rails actions\' performance'
6
+ s.description = 'Validate your Rails actions\' performance'
7
+ s.authors = ['Bipin Suresh']
8
+ s.email = 'bipins@alumni.stanford.edu'
9
+ s.files = `git ls-files -z`.split("\x0")
10
+ s.test_files = s.files.grep(%r{^(test|spec|features)/})
11
+ s.homepage = 'http://rubygems.org/gems/performance_promise'
12
+ s.license = 'MIT'
13
+ end
@@ -0,0 +1,53 @@
1
+ require 'active_support/time'
2
+ require 'logger'
3
+ require './lib/performance_promise/performance.rb'
4
+
5
+
6
+ describe 'LazilyEvaluated' do
7
+ it 'creates a lazy-evaluated object a Fixnum' do
8
+ expect(1.query.class).to be LazilyEvaluated
9
+ expect(2.queries.class).to be LazilyEvaluated
10
+ end
11
+
12
+ it 'creates a lazy-evaluatd object from ActiveRecord::Base' do
13
+ expect(ActiveRecord::Base.N.queries.class).to be LazilyEvaluated
14
+ end
15
+
16
+ it 'creates a new lazy-evaluated object from arithmetic operations' do
17
+ expect((LazilyEvaluated.new(1) + LazilyEvaluated.new(2)).class).to be LazilyEvaluated
18
+ expect((LazilyEvaluated.new(1) - LazilyEvaluated.new(2)).class).to be LazilyEvaluated
19
+ expect((LazilyEvaluated.new(1) * LazilyEvaluated.new(2)).class).to be LazilyEvaluated
20
+ expect((LazilyEvaluated.new(1) / LazilyEvaluated.new(2)).class).to be LazilyEvaluated
21
+ end
22
+
23
+ context '#evaluate' do
24
+ before(:all) do
25
+ PerformancePromise.configure do |config|
26
+ config.enable = true
27
+ end
28
+ PerformancePromise.start
29
+ end
30
+
31
+ it 'short-circuits in production' do
32
+ expect(Rails).to receive(:env).and_return('production')
33
+ expect(ActiveRecord::Base).not_to receive(:count)
34
+ expect(ActiveRecord::Base.N.queries.evaluate).to be 0
35
+ end
36
+
37
+ it 'evaluates Fixnums correctly' do
38
+ expect((1.query).evaluate).to be 1
39
+ end
40
+
41
+ it 'lazily evaluates models' do
42
+ expect(ActiveRecord::Base).to receive(:count)
43
+ ActiveRecord::Base.N.evaluate
44
+ end
45
+
46
+ it 'evaluates simple arithmetic operations correctly' do
47
+ expect((1.query + 2.queries).evaluate).to be 3
48
+ expect((2.queries - 1.query).evaluate).to be 1
49
+ expect((2.queries * 2.queries).evaluate).to be 4
50
+ expect((2.queries / 2.queries).evaluate).to be 1
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,31 @@
1
+ require './lib/performance_promise/performance.rb'
2
+
3
+
4
+ describe 'Performance' do
5
+ before(:all) do
6
+ class ArticleController
7
+ extend MethodDecorators
8
+ end
9
+ end
10
+
11
+ it 'does not registers a promise when a function is not decorated' do
12
+ expect(PerformancePromise.promises['ArticleController#index']).to be_falsey
13
+ end
14
+
15
+ it 'registers a promise when a function is decorated' do
16
+ a = ArticleController.new
17
+ class ArticleController
18
+ Performance :makes => 1.query
19
+ def index
20
+ end
21
+ end
22
+ expect(PerformancePromise.promises['ArticleController#index']).to be_truthy
23
+ end
24
+
25
+ it 'calls the decorated function when called' do
26
+ a = ArticleController.new
27
+ expect(PerformancePromise.promises['ArticleController#index']).to be_truthy
28
+ expect(a).to receive(:index).with('argument')
29
+ a.index('argument')
30
+ end
31
+ end
@@ -0,0 +1,14 @@
1
+ require './lib/performance_promise/speedy.rb'
2
+
3
+
4
+ describe 'Speedy' do
5
+ it 'promises speedy configuration when tagged with Speedy()' do
6
+ class ArticleController
7
+ Speedy()
8
+ def index
9
+ end
10
+ end
11
+ speedy_promise = PerformancePromise.configuration.speedy_promise
12
+ expect(PerformancePromise.promises['ArticleController#index']).to equal(speedy_promise)
13
+ end
14
+ end
@@ -0,0 +1,230 @@
1
+ require 'active_support/time'
2
+ require 'logger'
3
+ require './lib/performance_promise.rb'
4
+ require './lib/performance_promise/decorators.rb'
5
+
6
+
7
+ RSpec.describe 'PerformancePromise' do
8
+ context '.start' do
9
+ context 'when not enabled' do
10
+ before(:each) do
11
+ PerformancePromise.configure do |config|
12
+ config.enable = false
13
+ end
14
+ end
15
+
16
+ it 'does not subscribe to any events' do
17
+ expect(ActiveSupport::Notifications).not_to receive(:subscribe)
18
+ PerformancePromise.start
19
+ end
20
+ end
21
+
22
+ context 'when enabled' do
23
+ before(:each) do
24
+ PerformancePromise.configure do |config|
25
+ config.enable = true
26
+ end
27
+ end
28
+
29
+ context 'when in production' do
30
+ before(:each) do
31
+ expect(Rails).to receive(:env).and_return('production')
32
+ end
33
+
34
+ it 'does not subscribe to any events' do
35
+ expect(ActiveSupport::Notifications).not_to receive(:subscribe)
36
+ PerformancePromise.start
37
+ end
38
+ end
39
+
40
+ context 'when in development' do
41
+ it 'subscribe to all events' do
42
+ expect(ActiveSupport::Notifications).to receive(:subscribe).with('sql.active_record')
43
+ expect(ActiveSupport::Notifications).to receive(:subscribe).with('start_processing.action_controller')
44
+ expect(ActiveSupport::Notifications).to receive(:subscribe).with('process_action.action_controller')
45
+ PerformancePromise.start
46
+ end
47
+ end
48
+ end
49
+ end
50
+
51
+ context 'after it is started' do
52
+ before(:all) do
53
+ PerformancePromise.configure do |config|
54
+ config.enable = true
55
+ end
56
+ PerformancePromise.start
57
+ end
58
+
59
+ it 'records the statement when a SQL statement is executed' do
60
+ expect(SQLRecorder.instance).to receive(:record)
61
+ ActiveSupport::Notifications.instrument('sql.active_record')
62
+ end
63
+
64
+ it 'flushes the Recorder when an action loads' do
65
+ expect(SQLRecorder.instance).to receive(:flush)
66
+ ActiveSupport::Notifications.instrument('start_processing.action_controller')
67
+ end
68
+
69
+ context 'when the action completes' do
70
+ context 'when the method is tagged' do
71
+ before(:each) do
72
+ PerformancePromise.promises['ActionController#index'] = {
73
+ :makes => 1.queries,
74
+ }
75
+ end
76
+ it 'validates the promise when the method is tagged' do
77
+ expect(PerformancePromise).to receive(:validate_promise)
78
+ ActiveSupport::Notifications.instrument(
79
+ 'process_action.action_controller', {
80
+ :controller => :ActionController,
81
+ :action => :index,
82
+ }
83
+ )
84
+ end
85
+ end
86
+
87
+ context 'when the method is untagged' do
88
+ before(:each) do
89
+ PerformancePromise.promises['ActionController#index'] = nil
90
+ end
91
+
92
+ it 'validates the promise if Speedy is enabled by default' do
93
+ PerformancePromise.configure do |config|
94
+ config.untagged_methods_are_speedy = true
95
+ end
96
+ expect(PerformancePromise).to receive(:validate_promise)
97
+ expect(PerformancePromise.configuration.logger).to receive(:warn).with('No promises made. Assuming Speedy')
98
+ ActiveSupport::Notifications.instrument(
99
+ 'process_action.action_controller', {
100
+ :controller => :ActionController,
101
+ :action => :index,
102
+ }
103
+ )
104
+ end
105
+
106
+ it 'does not validate promise if Speedy is not enabled by default' do
107
+ PerformancePromise.configure do |config|
108
+ config.untagged_methods_are_speedy = false
109
+ end
110
+ expect(PerformancePromise).not_to receive(:validate_promise)
111
+ ActiveSupport::Notifications.instrument(
112
+ 'process_action.action_controller', {
113
+ :controller => :ActionController,
114
+ :action => :index,
115
+ }
116
+ )
117
+ end
118
+ end
119
+ end
120
+ end
121
+
122
+ context '.validate_promise' do
123
+ before(:each) do
124
+ PerformancePromise.configure do |config|
125
+ config.enable = true
126
+ config.validations = []
127
+ end
128
+ PerformancePromise.start
129
+ end
130
+
131
+ it 'passes promises if all options are disabled' do
132
+ expect(PerformanceValidations).not_to receive(:report_failed_makes)
133
+ expect(PerformanceValidations).not_to receive(:report_failed_takes)
134
+ expect(PerformanceValidations).to receive(:report_promise_passed)
135
+ PerformancePromise.validate_promise('ActionController#index', [], 1, {})
136
+ end
137
+
138
+ context 'when asked to validate number of queries' do
139
+ before(:each) do
140
+ PerformancePromise.configure do |config|
141
+ config.validations = [
142
+ :makes,
143
+ ]
144
+ end
145
+ end
146
+
147
+ it 'does not do anything if no actual promise is made on #queries' do
148
+ expect(PerformanceValidations).not_to receive(:report_failed_makes)
149
+ expect(PerformanceValidations).to receive(:report_promise_passed)
150
+ PerformancePromise.validate_promise('ActionController#index', [], 1, {})
151
+ end
152
+
153
+ context 'when an actual promise is made' do
154
+ it 'reports a failure when a promise fails' do
155
+ options = {
156
+ :makes => 0.queries,
157
+ }
158
+ queries = [
159
+ 'SELECT * from articles',
160
+ ]
161
+ expect(PerformanceValidations).to receive(:report_failed_makes).and_return(['', []])
162
+ expect {
163
+ PerformancePromise.validate_promise('ActionController#index', queries, 1, options)
164
+ }.to raise_error(PerformancePromise::BrokenPromise)
165
+ end
166
+
167
+ it 'reports a success when a promise passes' do
168
+ options = {
169
+ :makes => 1.query,
170
+ }
171
+ queries = [
172
+ 'SELECT * from articles',
173
+ ]
174
+ expect(PerformanceValidations).not_to receive(:report_failed_makes)
175
+ expect(PerformanceValidations).to receive(:report_promise_passed)
176
+ PerformancePromise.validate_promise('ActionController#index', queries, 1, options)
177
+ end
178
+
179
+ it 'does not fail if an action is explicitly skipped' do
180
+ options = {
181
+ :makes => 0.queries,
182
+ :skip => true,
183
+ }
184
+ queries = [
185
+ 'SELECT * from articles',
186
+ ]
187
+ expect(PerformanceValidations).not_to receive(:report_failed_makes)
188
+ PerformancePromise.validate_promise('ActionController#index', queries, 1, options)
189
+ end
190
+ end
191
+ end
192
+
193
+ context 'when asked to validate time taken for render' do
194
+ before(:each) do
195
+ PerformancePromise.configure do |config|
196
+ config.validations = [
197
+ :takes,
198
+ ]
199
+ end
200
+ end
201
+
202
+ it 'does not do anything if no actual promise is made on time taken' do
203
+ expect(PerformanceValidations).not_to receive(:report_failed_takes)
204
+ expect(PerformanceValidations).to receive(:report_promise_passed)
205
+ PerformancePromise.validate_promise('ActionController#index', [], 1, {})
206
+ end
207
+
208
+ context 'when an actual promise is made' do
209
+ it 'reports a failure when a promise fails' do
210
+ options = {
211
+ :takes => 0.seconds,
212
+ }
213
+ expect(PerformanceValidations).to receive(:report_failed_takes).and_return(['', []])
214
+ expect {
215
+ PerformancePromise.validate_promise('ActionController#index', [], 1, options)
216
+ }.to raise_error(PerformancePromise::BrokenPromise)
217
+ end
218
+
219
+ it 'reports a success when a promise passes' do
220
+ options = {
221
+ :takes => 1,
222
+ }
223
+ expect(PerformanceValidations).not_to receive(:report_failed_takes)
224
+ expect(PerformanceValidations).to receive(:report_promise_passed)
225
+ PerformancePromise.validate_promise('ActionController#index', [], 1, options)
226
+ end
227
+ end
228
+ end
229
+ end
230
+ end
@@ -0,0 +1,121 @@
1
+ # This file was generated by the `rails generate rspec:install` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # The generated `.rspec` file contains `--require spec_helper` which will cause
4
+ # this file to always be loaded, without a need to explicitly require it in any
5
+ # files.
6
+ #
7
+ # Given that it is always loaded, you are encouraged to keep this file as
8
+ # light-weight as possible. Requiring heavyweight dependencies from this file
9
+ # will add to the boot time of your test suite on EVERY test run, even for an
10
+ # individual file that may not need all of that loaded. Instead, consider making
11
+ # a separate helper file that requires the additional dependencies and performs
12
+ # the additional setup, and require it from the spec files that actually need
13
+ # it.
14
+ #
15
+ # The `.rspec` file also contains a few flags that are not defaults but that
16
+ # users commonly want.
17
+ #
18
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
19
+ RSpec.configure do |config|
20
+ # rspec-expectations config goes here. You can use an alternate
21
+ # assertion/expectation library such as wrong or the stdlib/minitest
22
+ # assertions if you prefer.
23
+ config.expect_with :rspec do |expectations|
24
+ # This option will default to `true` in RSpec 4. It makes the `description`
25
+ # and `failure_message` of custom matchers include text for helper methods
26
+ # defined using `chain`, e.g.:
27
+ # be_bigger_than(2).and_smaller_than(4).description
28
+ # # => "be bigger than 2 and smaller than 4"
29
+ # ...rather than:
30
+ # # => "be bigger than 2"
31
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
32
+ end
33
+
34
+ # rspec-mocks config goes here. You can use an alternate test double
35
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
36
+ config.mock_with :rspec do |mocks|
37
+ # Prevents you from mocking or stubbing a method that does not exist on
38
+ # a real object. This is generally recommended, and will default to
39
+ # `true` in RSpec 4.
40
+ mocks.verify_partial_doubles = true
41
+ end
42
+
43
+ # The settings below are suggested to provide a good initial experience
44
+ # with RSpec, but feel free to customize to your heart's content.
45
+ =begin
46
+ # These two settings work together to allow you to limit a spec run
47
+ # to individual examples or groups you care about by tagging them with
48
+ # `:focus` metadata. When nothing is tagged with `:focus`, all examples
49
+ # get run.
50
+ config.filter_run :focus
51
+ config.run_all_when_everything_filtered = true
52
+
53
+ # Allows RSpec to persist some state between runs in order to support
54
+ # the `--only-failures` and `--next-failure` CLI options. We recommend
55
+ # you configure your source control system to ignore this file.
56
+ config.example_status_persistence_file_path = "spec/examples.txt"
57
+
58
+ # Limits the available syntax to the non-monkey patched syntax that is
59
+ # recommended. For more details, see:
60
+ # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
61
+ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
62
+ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
63
+ config.disable_monkey_patching!
64
+
65
+ # Many RSpec users commonly either run the entire suite or an individual
66
+ # file, and it's useful to allow more verbose output when running an
67
+ # individual spec file.
68
+ if config.files_to_run.one?
69
+ # Use the documentation formatter for detailed output,
70
+ # unless a formatter has already been configured
71
+ # (e.g. via a command-line flag).
72
+ config.default_formatter = 'doc'
73
+ end
74
+
75
+ # Print the 10 slowest examples and example groups at the
76
+ # end of the spec run, to help surface which specs are running
77
+ # particularly slow.
78
+ config.profile_examples = 10
79
+
80
+ # Run specs in random order to surface order dependencies. If you find an
81
+ # order dependency and want to debug it, you can fix the order by providing
82
+ # the seed, which is printed after each run.
83
+ # --seed 1234
84
+ config.order = :random
85
+
86
+ # Seed global randomization in this process using the `--seed` CLI option.
87
+ # Setting this allows you to use `--seed` to deterministically reproduce
88
+ # test failures related to randomization by passing the same `--seed` value
89
+ # as the one that triggered the failure.
90
+ Kernel.srand config.seed
91
+ =end
92
+ end
93
+
94
+
95
+ module Rails
96
+ class << self
97
+ def root
98
+ File.expand_path(__FILE__).split('/')[0..-3].join('/')
99
+ end
100
+
101
+ def logger
102
+ Logger.new(STDOUT)
103
+ end
104
+
105
+ def env
106
+ "test"
107
+ end
108
+ end
109
+ end
110
+
111
+ module ActionController
112
+ class Base
113
+ end
114
+ end
115
+
116
+ module ActiveRecord
117
+ class Base
118
+ def self.count
119
+ end
120
+ end
121
+ end