rack-mini-profiler 2.3.3 → 3.0.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: 6ff9200889e574b3f90f901b90b88fe05f0c48993c945fc5dac37c2f1d86e693
4
- data.tar.gz: bdca4fb3ada1b7c56525753b9eaa6430389f309a76152e3f8a7e0c9297463bea
3
+ metadata.gz: cde7281c7a63d3d3ac5bc7605ba2cf81dedf6b598ff17ed568610a54a50b517f
4
+ data.tar.gz: 7af763d5136493c71cc4321fe54db79372e5b9aaac4c10d31bc2f27d22f324b7
5
5
  SHA512:
6
- metadata.gz: 43b8c69b37ba90c80c31d8d410b05dda421322d5c6d1f45654807b526f7d990bec54eaa711aa34bbf43141831453a75543b3a27189103ea3f3bcbac7f3f4101a
7
- data.tar.gz: bed607b319c32d85838767f7de608031411d7513fcbd8866d2d67feb44253b997e389671a903b192be07e04d1c018069ab835536de47ada14ad3af8bf89739d9
6
+ metadata.gz: abb415f975552a1256753e15ba9d6623aeb55fe4b058c775701f2b7d3a955f62d2a906a93929f1a22545f8558750d48c78f3b7e185f774c224d12e6a256a69a6
7
+ data.tar.gz: f5ff03170537e5dc17a826909d9b77609bc8d6f2390f42b29be9ff1af538332eaa33c269f7433d87142ba7e05315741b3ea5b4c69fcc76980a56c225338d843c
data/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 3.0.0 - 2022-02-24
4
+
5
+ - PERF: Improve snapshots page performance (#518) (introduces breaking changes to the API of `AbstractStore`, `MemoryStore` and `RedisStore`, and removes the `snapshots_limit` config option.)
6
+
7
+ ## 2.3.4 - 2022-02-23
8
+
9
+ - [FEATURE] Add cookie path support for subfolder sites
10
+ - [FIX] Remove deprecated uses of Redis#pipelined
11
+
3
12
  ## 2.3.3 - 2021-08-30
4
13
 
5
14
  - [FEATURE] Introduce `pp=flamegraph_mode`
data/README.md CHANGED
@@ -166,14 +166,11 @@ export RACK_MINI_PROFILER_PATCH="false"
166
166
 
167
167
  ### Flamegraphs
168
168
 
169
- To generate [flamegraphs](http://samsaffron.com/archive/2013/03/19/flame-graphs-in-ruby-miniprofiler):
169
+ To generate [flamegraphs](http://samsaffron.com/archive/2013/03/19/flame-graphs-in-ruby-miniprofiler), add the [**stackprof**](https://rubygems.org/gems/stackprof) gem to your Gemfile.
170
170
 
171
- * add the [**stackprof**](https://rubygems.org/gems/stackprof) gem to your Gemfile
172
- * visit a page in your app with `?pp=flamegraph`
171
+ Then, to view the flamegraph as a direct HTML response from your request, just visit any page in your app with `?pp=flamegraph` appended to the URL.
173
172
 
174
- To store flamegraph data for later viewing, append the `?pp=async-flamegraph` parameter. The request will return as normal.
175
- Flamegraph data for this request, and all subsequent requests made by this page (based on the `REFERER` header) will be stored.
176
- 'flamegraph' links will appear for these requests in the MiniProfiler UI.
173
+ Conversely, if you want your regular response instead (which is specially useful for JSON and/or XHR requests), just append the `?pp=async-flamegraph` parameter to your request/fetch URL; the request will then return as normal, and the flamegraph data will be stored for later *async* viewing, both for this request and for all subsequent requests made by this page (based on the `REFERER` header). For viewing these async flamegraphs, use the 'flamegraph' link that will appear inside the MiniProfiler UI for these requests.
177
174
 
178
175
  Note: Mini Profiler will not record SQL timings for a request if it asks for a flamegraph. The rationale behind this is to keep
179
176
  Mini Profiler's methods that are responsible for generating the timings data out of the flamegraph.
@@ -210,7 +207,7 @@ After enabling snapshots sampling, you can see the snapshots that have been coll
210
207
 
211
208
  Access to the snapshots page is restricted to only those who can see the speed badge on their own requests, see the section below this one about access control.
212
209
 
213
- Mini Profiler will keep a maximum of 1000 snapshots by default, and you can change that via the `snapshots_limit` config. When snapshots reach the configured limit, Mini Profiler will save a new snapshot only if it's worse than at least one of the existing snapshots and delete the best one (i.e. the snapshot whose request took the least time compared to other snapshots).
210
+ Mini Profiler will keep a maximum of 50 snapshot groups and a maximum of 15 snapshots per group making the default maximum number of snapshots in the system 750. The default group and per group limits can be changed via the `max_snapshot_groups` and `max_snapshots_per_group` configuration options, see the configurations table below.
214
211
 
215
212
  #### Snapshots Transporter
216
213
 
@@ -350,19 +347,41 @@ Single page applications built using Ember, Angular or other frameworks need som
350
347
  On route transition always call:
351
348
 
352
349
  ```
353
- window.MiniProfiler.pageTransition();
350
+ if (window.MiniProfiler !== undefined) {
351
+ window.MiniProfiler.pageTransition();
352
+ }
354
353
  ```
355
354
 
356
355
  This method will remove profiling information that was related to previous page and clear aggregate statistics.
357
356
 
358
357
  #### MiniProfiler's speed badge on pages that are not generated via Rails
359
- You need to inject the following in your SPA to load MiniProfiler's speed badge ([extra details surrounding this script](https://github.com/MiniProfiler/rack-mini-profiler/issues/139#issuecomment-192880706)):
358
+ You need to inject the following in your SPA to load MiniProfiler's speed badge ([extra details surrounding this script](https://github.com/MiniProfiler/rack-mini-profiler/issues/139#issuecomment-192880706) and [credit for the script tag](https://github.com/MiniProfiler/rack-mini-profiler/issues/479#issue-782488320) to [@ivanyv](https://github.com/ivanyv)):
360
359
 
361
360
  ```html
362
- <script async type="text/javascript" id="mini-profiler" src="/mini-profiler-resources/includes.js?v=12b4b45a3c42e6e15503d7a03810ff33" data-version="12b4b45a3c42e6e15503d7a03810ff33" data-path="/mini-profiler-resources/" data-current-id="redo66j4g1077kto8uh3" data-ids="redo66j4g1077kto8uh3" data-horizontal-position="left" data-vertical-position="top" data-trivial="false" data-children="false" data-max-traces="10" data-controls="false" data-authorized="true" data-toggle-shortcut="Alt+P" data-start-hidden="false" data-collapse-results="true"></script>
363
- ```
364
-
365
- _Note:_ The GUID (`data-version` and the `?v=` parameter on the `src`) will change with each release of `rack_mini_profiler`. The MiniProfiler's speed badge will continue to work, although you will have to change the GUID to expire the script to fetch the most recent version.
361
+ <script type="text/javascript" id="mini-profiler"
362
+ src="/mini-profiler-resources/includes.js?v=12b4b45a3c42e6e15503d7a03810ff33"
363
+ data-css-url="/mini-profiler-resources/includes.css?v=12b4b45a3c42e6e15503d7a03810ff33"
364
+ data-version="12b4b45a3c42e6e15503d7a03810ff33"
365
+ data-path="/mini-profiler-resources/"
366
+ data-horizontal-position="left"
367
+ data-vertical-position="top"
368
+ data-ids=""
369
+ data-trivial="false"
370
+ data-children="false"
371
+ data-max-traces="20"
372
+ data-controls="false"
373
+ data-total-sql-count="false"
374
+ data-authorized="true"
375
+ data-toggle-shortcut="alt+p"
376
+ data-start-hidden="false"
377
+ data-collapse-results="true"
378
+ data-html-container="body"
379
+ data-hidden-custom-fields></script>
380
+ ```
381
+
382
+ See an [example of how to do this in a React useEffect](https://gist.github.com/katelovescode/01cfc2b962c165193b160fd10af6c4d5).
383
+
384
+ _Note:_ The GUID (`data-version` and the `?v=` parameter on the `src` and `data-css-url`) will change with each release of `rack_mini_profiler`. The MiniProfiler's speed badge will continue to work, although you will have to change the GUID to expire the script to fetch the most recent version.
366
385
 
367
386
  #### Using MiniProfiler's built in route for apps without HTML responses
368
387
  MiniProfiler also ships with a `/rack-mini-profiler/requests` route that displays the speed badge on a blank HTML page. This can be useful when profiling an application that does not render HTML.
@@ -403,14 +422,16 @@ backtrace_threshold_ms|`0`|Minimum SQL query elapsed time before a backtrace is
403
422
  flamegraph_sample_rate|`0.5`|How often to capture stack traces for flamegraphs in milliseconds.
404
423
  flamegraph_mode|`:wall`|The [StackProf mode](https://github.com/tmm1/stackprof#all-options) to pass to `StackProf.run`.
405
424
  base_url_path|`'/mini-profiler-resources/'`|Path for assets; added as a prefix when naming assets and sought when responding to requests.
425
+ cookie_path|`'/'`|Set-Cookie header path for profile cookie
406
426
  collapse_results|`true`|If multiple timing results exist in a single page, collapse them till clicked.
407
427
  max_traces_to_show|20|Maximum number of mini profiler timing blocks to show on one page
408
428
  html_container|`body`|The HTML container (as a jQuery selector) to inject the mini_profiler UI into
409
429
  show_total_sql_count|`false`|Displays the total number of SQL executions.
410
- enable_advanced_debugging_tools|`false`|Enables sensitive debugging tools that can be used via the UI. In production we recommend keeping this disabled as memory and environment debugging tools can expose contents of memory that may contain passwords.
430
+ enable_advanced_debugging_tools|`false`|Enables sensitive debugging tools that can be used via the UI. In production we recommend keeping this disabled as memory and environment debugging tools can expose contents of memory that may contain passwords. Defaults to `true` in development.
411
431
  assets_url|`nil`|See the "Register MiniProfiler's assets in the Rails assets pipeline" section above.
412
432
  snapshot_every_n_requests|`-1`|Determines how frequently snapshots are taken. See the "Snapshots Sampling" above for more details.
413
- snapshots_limit|`1000`|Determines how many snapshots Mini Profiler is allowed to keep.
433
+ max_snapshot_groups|`50`|Determines how many snapshot groups Mini Profiler is allowed to keep.
434
+ max_snapshots_per_group|`15`|Determines how many snapshots per group Mini Profiler is allowed to keep.
414
435
  snapshot_hidden_custom_fields|`[]`|Each snapshot custom field will have a dedicated column in the UI by default. Use this config to exclude certain custom fields from having their own columns.
415
436
  snapshots_transport_destination_url|`nil`|Set this config to a valid URL to enable snapshots transporter which will `POST` snapshots to the given URL. The transporter requires `snapshots_transport_auth_key` config to be set as well.
416
437
  snapshots_transport_auth_key|`nil`|`POST` requests made by the snapshots transporter to the destination URL will have a `Mini-Profiler-Transport-Auth` header with the value of this config. Make sure you use a secure and random key for this config.
@@ -74,7 +74,7 @@ module Rack
74
74
  settings["bt"] = @backtrace_level if @backtrace_level
75
75
  settings["a"] = @allowed_tokens.join("|") if @allowed_tokens && MiniProfiler.request_authorized?
76
76
  settings_string = settings.map { |k, v| "#{k}=#{v}" }.join(",")
77
- cookie = { value: settings_string, path: '/', httponly: true }
77
+ cookie = { value: settings_string, path: MiniProfiler.config.cookie_path, httponly: true }
78
78
  cookie[:secure] = true if @request.ssl?
79
79
  cookie[:same_site] = 'Lax'
80
80
  Rack::Utils.set_cookie_header!(headers, COOKIE_NAME, cookie)
@@ -83,7 +83,7 @@ module Rack
83
83
 
84
84
  def discard_cookie!(headers)
85
85
  if @cookie
86
- Rack::Utils.delete_cookie_header!(headers, COOKIE_NAME, path: '/')
86
+ Rack::Utils.delete_cookie_header!(headers, COOKIE_NAME, path: MiniProfiler.config.cookie_path)
87
87
  end
88
88
  end
89
89
 
@@ -17,6 +17,7 @@ module Rack
17
17
  new.instance_eval {
18
18
  @auto_inject = true # automatically inject on every html page
19
19
  @base_url_path = "/mini-profiler-resources/".dup
20
+ @cookie_path = "/".dup
20
21
  @disable_caching = true
21
22
  # called prior to rack chain, to ensure we are allowed to profile
22
23
  @pre_authorize_cb = lambda { |env| true }
@@ -39,7 +40,8 @@ module Rack
39
40
  @skip_sql_param_names = /password/ # skips parameters with the name password by default
40
41
  @enable_advanced_debugging_tools = false
41
42
  @snapshot_every_n_requests = -1
42
- @snapshots_limit = 1000
43
+ @max_snapshot_groups = 50
44
+ @max_snapshots_per_group = 15
43
45
 
44
46
  # ui parameters
45
47
  @autorized = true
@@ -66,7 +68,7 @@ module Rack
66
68
 
67
69
  attr_accessor :authorization_mode, :auto_inject, :backtrace_ignores,
68
70
  :backtrace_includes, :backtrace_remove, :backtrace_threshold_ms,
69
- :base_url_path, :disable_caching, :enabled,
71
+ :base_url_path, :cookie_path, :disable_caching, :enabled,
70
72
  :flamegraph_sample_rate, :logger, :pre_authorize_cb, :skip_paths,
71
73
  :skip_schema_queries, :storage, :storage_failure, :storage_instance,
72
74
  :storage_options, :user_provider, :enable_advanced_debugging_tools,
@@ -80,10 +82,10 @@ module Rack
80
82
  :start_hidden, :toggle_shortcut, :html_container
81
83
 
82
84
  # snapshot related config
83
- attr_accessor :snapshot_every_n_requests, :snapshots_limit,
85
+ attr_accessor :snapshot_every_n_requests, :max_snapshots_per_group,
84
86
  :snapshot_hidden_custom_fields, :snapshots_transport_destination_url,
85
87
  :snapshots_transport_auth_key, :snapshots_redact_sql_queries,
86
- :snapshots_transport_gzip_requests
88
+ :snapshots_transport_gzip_requests, :max_snapshot_groups
87
89
 
88
90
  # Deprecated options
89
91
  attr_accessor :use_existing_jquery
@@ -130,10 +130,10 @@ module Rack
130
130
  def serve_results(env)
131
131
  request = Rack::Request.new(env)
132
132
  id = request.params['id']
133
- is_snapshot = request.params['snapshot']
134
- is_snapshot = [true, "true"].include?(is_snapshot)
133
+ group_name = request.params['group']
134
+ is_snapshot = group_name && group_name.size > 0
135
135
  if is_snapshot
136
- page_struct = @storage.load_snapshot(id)
136
+ page_struct = @storage.load_snapshot(id, group_name)
137
137
  else
138
138
  page_struct = @storage.load(id)
139
139
  end
@@ -773,7 +773,7 @@ This is the help menu of the <a href='#{Rack::MiniProfiler::SOURCE_CODE_URI}'>ra
773
773
  end
774
774
 
775
775
  # TODO : cache this snippet
776
- script = IO.read(::File.expand_path('../html/profile_handler.js', ::File.dirname(__FILE__)))
776
+ script = ::File.read(::File.expand_path('../html/profile_handler.js', ::File.dirname(__FILE__)))
777
777
  # replace the variables
778
778
  settings.each do |k, v|
779
779
  regex = Regexp.new("\\{#{k.to_s}\\}")
@@ -802,16 +802,16 @@ This is the help menu of the <a href='#{Rack::MiniProfiler::SOURCE_CODE_URI}'>ra
802
802
  headers = { 'Content-Type' => 'text/html' }
803
803
  qp = Rack::Utils.parse_nested_query(env['QUERY_STRING'])
804
804
  if group_name = qp["group_name"]
805
- list = @storage.find_snapshots_group(group_name)
805
+ list = @storage.snapshots_group(group_name)
806
806
  list.each do |snapshot|
807
- snapshot[:url] = url_for_snapshot(snapshot[:id])
807
+ snapshot[:url] = url_for_snapshot(snapshot[:id], group_name)
808
808
  end
809
809
  data = {
810
810
  group_name: group_name,
811
811
  list: list
812
812
  }
813
813
  else
814
- list = @storage.snapshot_groups_overview
814
+ list = @storage.snapshots_overview
815
815
  list.each do |group|
816
816
  group[:url] = url_for_snapshots_group(group[:name])
817
817
  end
@@ -864,7 +864,7 @@ This is the help menu of the <a href='#{Rack::MiniProfiler::SOURCE_CODE_URI}'>ra
864
864
  if defined?(Rails) && defined?(ActionController::RoutingError)
865
865
  hash = Rails.application.routes.recognize_path(path, method: method)
866
866
  if hash && hash[:controller] && hash[:action]
867
- "#{method} #{hash[:controller]}##{hash[:action]}"
867
+ "#{hash[:controller]}##{hash[:action]}"
868
868
  end
869
869
  end
870
870
  rescue ActionController::RoutingError
@@ -876,8 +876,8 @@ This is the help menu of the <a href='#{Rack::MiniProfiler::SOURCE_CODE_URI}'>ra
876
876
  "/#{@config.base_url_path.gsub('/', '')}/snapshots?#{qs}"
877
877
  end
878
878
 
879
- def url_for_snapshot(id)
880
- qs = Rack::Utils.build_query({ id: id, snapshot: true })
879
+ def url_for_snapshot(id, group_name)
880
+ qs = Rack::Utils.build_query({ id: id, group: group_name })
881
881
  "/#{@config.base_url_path.gsub('/', '')}/results?#{qs}"
882
882
  end
883
883
 
@@ -902,8 +902,12 @@ This is the help menu of the <a href='#{Rack::MiniProfiler::SOURCE_CODE_URI}'>ra
902
902
  if Rack::MiniProfiler.snapshots_transporter?
903
903
  Rack::MiniProfiler::SnapshotsTransporter.transport(page_struct)
904
904
  else
905
+ group_name = rails_route_from_path(page_struct[:request_path], page_struct[:request_method])
906
+ group_name ||= page_struct[:request_path]
907
+ group_name = "#{page_struct[:request_method]} #{group_name}"
905
908
  @storage.push_snapshot(
906
909
  page_struct,
910
+ group_name,
907
911
  @config
908
912
  )
909
913
  end
@@ -45,80 +45,53 @@ module Rack
45
45
  raise NotImplementedError.new("should_take_snapshot? is not implemented")
46
46
  end
47
47
 
48
- def push_snapshot(page_struct, config)
48
+ def push_snapshot(page_struct, group_name, config)
49
49
  raise NotImplementedError.new("push_snapshot is not implemented")
50
50
  end
51
51
 
52
- def fetch_snapshots(batch_size: 200, &blk)
53
- raise NotImplementedError.new("fetch_snapshots is not implemented")
52
+ # returns a hash where the keys are group names and the values
53
+ # are hashes that contain 3 keys:
54
+ # 1. `:worst_score` => the duration of the worst/slowest snapshot in the group (float)
55
+ # 2. `:best_score` => the duration of the best/fastest snapshot in the group (float)
56
+ # 3. `:snapshots_count` => the number of snapshots in the group (integer)
57
+ def fetch_snapshots_overview
58
+ raise NotImplementedError.new("fetch_snapshots_overview is not implemented")
54
59
  end
55
60
 
56
- def snapshot_groups_overview
57
- groups = {}
58
- fetch_snapshots do |batch|
59
- batch.each do |snapshot|
60
- group_name = default_snapshot_grouping(snapshot)
61
- hash = groups[group_name] ||= {}
62
- hash[:snapshots_count] ||= 0
63
- hash[:snapshots_count] += 1
64
- if !hash[:worst_score] || hash[:worst_score] < snapshot.duration_ms
65
- groups[group_name][:worst_score] = snapshot.duration_ms
66
- end
67
- if !hash[:best_score] || hash[:best_score] > snapshot.duration_ms
68
- groups[group_name][:best_score] = snapshot.duration_ms
69
- end
70
- end
71
- end
72
- groups = groups.to_a
61
+ # @param group_name [String]
62
+ # @return [Array<Rack::MiniProfiler::TimerStruct::Page>] list of snapshots of the group. Blank array if the group doesn't exist.
63
+ def fetch_snapshots_group(group_name)
64
+ raise NotImplementedError.new("fetch_snapshots_group is not implemented")
65
+ end
66
+
67
+ def load_snapshot(id, group_name)
68
+ raise NotImplementedError.new("load_snapshot is not implemented")
69
+ end
70
+
71
+ def snapshots_overview
72
+ groups = fetch_snapshots_overview.to_a
73
73
  groups.sort_by! { |name, hash| hash[:worst_score] }
74
74
  groups.reverse!
75
75
  groups.map! { |name, hash| hash.merge(name: name) }
76
76
  groups
77
77
  end
78
78
 
79
- def find_snapshots_group(group_name)
79
+ def snapshots_group(group_name)
80
+ snapshots = fetch_snapshots_group(group_name)
80
81
  data = []
81
- fetch_snapshots do |batch|
82
- batch.each do |snapshot|
83
- snapshot_group_name = default_snapshot_grouping(snapshot)
84
- if group_name == snapshot_group_name
85
- data << {
86
- id: snapshot[:id],
87
- duration: snapshot.duration_ms,
88
- sql_count: snapshot[:sql_count],
89
- timestamp: snapshot[:started_at],
90
- custom_fields: snapshot[:custom_fields]
91
- }
92
- end
93
- end
82
+ snapshots.each do |snapshot|
83
+ data << {
84
+ id: snapshot[:id],
85
+ duration: snapshot.duration_ms,
86
+ sql_count: snapshot[:sql_count],
87
+ timestamp: snapshot[:started_at],
88
+ custom_fields: snapshot[:custom_fields]
89
+ }
94
90
  end
95
91
  data.sort_by! { |s| s[:duration] }
96
92
  data.reverse!
97
93
  data
98
94
  end
99
-
100
- def load_snapshot(id)
101
- raise NotImplementedError.new("load_snapshot is not implemented")
102
- end
103
-
104
- private
105
-
106
- def default_snapshot_grouping(snapshot)
107
- group_name = rails_route_from_path(snapshot[:request_path], snapshot[:request_method])
108
- group_name ||= snapshot[:request_path]
109
- "#{snapshot[:request_method]} #{group_name}"
110
- end
111
-
112
- def rails_route_from_path(path, method)
113
- if defined?(Rails) && defined?(ActionController::RoutingError)
114
- hash = Rails.application.routes.recognize_path(path, method: method)
115
- if hash && hash[:controller] && hash[:action]
116
- "#{hash[:controller]}##{hash[:action]}"
117
- end
118
- end
119
- rescue ActionController::RoutingError
120
- nil
121
- end
122
95
  end
123
96
  end
124
97
  end
@@ -17,7 +17,9 @@ module Rack
17
17
  def [](key)
18
18
  begin
19
19
  data = ::File.open(path(key), "rb") { |f| f.read }
20
+ # rubocop:disable Security/MarshalLoad
20
21
  Marshal.load data
22
+ # rubocop:enable Security/MarshalLoad
21
23
  rescue
22
24
  nil
23
25
  end
@@ -24,7 +24,9 @@ module Rack
24
24
 
25
25
  def load(id)
26
26
  raw = @client.get("#{@prefix}#{id}")
27
- Marshal::load(raw) if raw
27
+ # rubocop:disable Security/MarshalLoad
28
+ Marshal.load(raw) if raw
29
+ # rubocop:enable Security/MarshalLoad
28
30
  end
29
31
 
30
32
  def set_unviewed(user, id)
@@ -65,14 +67,16 @@ module Rack
65
67
  key1, key2, cycle_at = nil
66
68
 
67
69
  if token_info
68
- key1, key2, cycle_at = Marshal::load(token_info)
70
+ # rubocop:disable Security/MarshalLoad
71
+ key1, key2, cycle_at = Marshal.load(token_info)
72
+ # rubocop:enable Security/MarshalLoad
69
73
 
70
- key1 = nil unless key1 && key1.length == 32
71
- key2 = nil unless key2 && key2.length == 32
74
+ key1 = nil unless key1 && key1.length == 32
75
+ key2 = nil unless key2 && key2.length == 32
72
76
 
73
- if key1 && cycle_at && (cycle_at > Process.clock_gettime(Process::CLOCK_MONOTONIC))
74
- return [key1, key2].compact
75
- end
77
+ if key1 && cycle_at && (cycle_at > Process.clock_gettime(Process::CLOCK_MONOTONIC))
78
+ return [key1, key2].compact
79
+ end
76
80
  end
77
81
 
78
82
  timeout = Rack::MiniProfiler::AbstractStore::MAX_TOKEN_AGE
@@ -53,6 +53,7 @@ module Rack
53
53
 
54
54
  @token1, @token2, @cycle_at = nil
55
55
  @snapshots_cycle = 0
56
+ @snapshot_groups = {}
56
57
  @snapshots = []
57
58
 
58
59
  initialize_locks
@@ -152,28 +153,69 @@ module Rack
152
153
  end
153
154
  end
154
155
 
155
- def push_snapshot(page_struct, config)
156
+ def push_snapshot(page_struct, group_name, config)
156
157
  @snapshots_lock.synchronize do
157
- @snapshots << page_struct
158
- @snapshots.sort_by! { |s| s.duration_ms }
159
- @snapshots.reverse!
160
- if @snapshots.size > config.snapshots_limit
161
- @snapshots.slice!(-1)
158
+ group = @snapshot_groups[group_name]
159
+ if !group
160
+ @snapshot_groups[group_name] = {
161
+ worst_score: page_struct.duration_ms,
162
+ best_score: page_struct.duration_ms,
163
+ snapshots: [page_struct]
164
+ }
165
+ if @snapshot_groups.size > config.max_snapshot_groups
166
+ group_keys = @snapshot_groups.keys
167
+ group_keys.sort_by! do |key|
168
+ @snapshot_groups[key][:worst_score]
169
+ end
170
+ group_keys.reverse!
171
+ group_keys.pop(group_keys.size - config.max_snapshot_groups)
172
+ @snapshot_groups = @snapshot_groups.slice(*group_keys)
173
+ end
174
+ else
175
+ snapshots = group[:snapshots]
176
+ snapshots << page_struct
177
+ snapshots.sort_by!(&:duration_ms)
178
+ snapshots.reverse!
179
+ if snapshots.size > config.max_snapshots_per_group
180
+ snapshots.pop(snapshots.size - config.max_snapshots_per_group)
181
+ end
182
+ group[:worst_score] = snapshots[0].duration_ms
183
+ group[:best_score] = snapshots[-1].duration_ms
162
184
  end
163
185
  end
164
186
  end
165
187
 
166
- def fetch_snapshots(batch_size: 200, &blk)
188
+ def fetch_snapshots_overview
167
189
  @snapshots_lock.synchronize do
168
- @snapshots.each_slice(batch_size) do |batch|
169
- blk.call(batch)
190
+ groups = {}
191
+ @snapshot_groups.each do |name, group|
192
+ groups[name] = {
193
+ worst_score: group[:worst_score],
194
+ best_score: group[:best_score],
195
+ snapshots_count: group[:snapshots].size
196
+ }
170
197
  end
198
+ groups
171
199
  end
172
200
  end
173
201
 
174
- def load_snapshot(id)
202
+ def fetch_snapshots_group(group_name)
175
203
  @snapshots_lock.synchronize do
176
- @snapshots.find { |s| s[:id] == id }
204
+ group = @snapshot_groups[group_name]
205
+ if group
206
+ group[:snapshots].dup
207
+ else
208
+ []
209
+ end
210
+ end
211
+ end
212
+
213
+ def load_snapshot(id, group_name)
214
+ @snapshots_lock.synchronize do
215
+ group = @snapshot_groups[group_name]
216
+ if group
217
+ group[:snapshots].find { |s| s[:id] == id }
218
+ end
177
219
  end
178
220
  end
179
221
 
@@ -182,7 +224,7 @@ module Rack
182
224
  # used in tests only
183
225
  def wipe_snapshots_data
184
226
  @snapshots_cycle = 0
185
- @snapshots = []
227
+ @snapshot_groups = {}
186
228
  end
187
229
  end
188
230
  end
@@ -25,7 +25,9 @@ module Rack
25
25
  key = prefixed_id(id)
26
26
  raw = redis.get key
27
27
  begin
28
- Marshal::load(raw) if raw
28
+ # rubocop:disable Security/MarshalLoad
29
+ Marshal.load(raw) if raw
30
+ # rubocop:enable Security/MarshalLoad
29
31
  rescue
30
32
  # bad format, junk old data
31
33
  redis.del key
@@ -131,81 +133,127 @@ unviewed_ids: #{get_unviewed_ids(user)}
131
133
  )
132
134
  end
133
135
 
134
- def push_snapshot(page_struct, config)
135
- zset_key = snapshot_zset_key()
136
- hash_key = snapshot_hash_key()
136
+ def push_snapshot(page_struct, group_name, config)
137
+ group_zset_key = group_snapshot_zset_key(group_name)
138
+ group_hash_key = group_snapshot_hash_key(group_name)
139
+ overview_zset_key = snapshot_overview_zset_key
137
140
 
138
141
  id = page_struct[:id]
139
- score = page_struct.duration_ms
140
- limit = config.snapshots_limit
142
+ score = page_struct.duration_ms.to_s
143
+
144
+ per_group_limit = config.max_snapshots_per_group.to_s
145
+ groups_limit = config.max_snapshot_groups.to_s
141
146
  bytes = Marshal.dump(page_struct)
142
147
 
143
148
  lua = <<~LUA
144
- local zset_key = KEYS[1]
145
- local hash_key = KEYS[2]
149
+ local group_zset_key = KEYS[1]
150
+ local group_hash_key = KEYS[2]
151
+ local overview_zset_key = KEYS[3]
152
+
146
153
  local id = ARGV[1]
147
154
  local score = tonumber(ARGV[2])
148
- local bytes = ARGV[3]
149
- local limit = tonumber(ARGV[4])
150
- redis.call("ZADD", zset_key, score, id)
151
- redis.call("HSET", hash_key, id, bytes)
152
- if redis.call("ZCARD", zset_key) > limit then
153
- local lowest_snapshot_id = redis.call("ZRANGE", zset_key, 0, 0)[1]
154
- redis.call("ZREM", zset_key, lowest_snapshot_id)
155
- redis.call("HDEL", hash_key, lowest_snapshot_id)
155
+ local group_name = ARGV[3]
156
+ local per_group_limit = tonumber(ARGV[4])
157
+ local groups_limit = tonumber(ARGV[5])
158
+ local prefix = ARGV[6]
159
+ local bytes = ARGV[7]
160
+
161
+ local current_group_score = redis.call("ZSCORE", overview_zset_key, group_name)
162
+ if current_group_score == false or score > tonumber(current_group_score) then
163
+ redis.call("ZADD", overview_zset_key, score, group_name)
164
+ end
165
+
166
+ local do_save = true
167
+ local overview_size = redis.call("ZCARD", overview_zset_key)
168
+ while (overview_size > groups_limit) do
169
+ local lowest_group = redis.call("ZRANGE", overview_zset_key, 0, 0)[1]
170
+ redis.call("ZREM", overview_zset_key, lowest_group)
171
+ if lowest_group == group_name then
172
+ do_save = false
173
+ else
174
+ local lowest_group_zset_key = prefix .. "-mp-group-snapshot-zset-key-" .. lowest_group
175
+ local lowest_group_hash_key = prefix .. "-mp-group-snapshot-hash-key-" .. lowest_group
176
+ redis.call("DEL", lowest_group_zset_key, lowest_group_hash_key)
177
+ end
178
+ overview_size = overview_size - 1
179
+ end
180
+
181
+ if do_save then
182
+ redis.call("ZADD", group_zset_key, score, id)
183
+ local group_size = redis.call("ZCARD", group_zset_key)
184
+ while (group_size > per_group_limit) do
185
+ local lowest_snapshot_id = redis.call("ZRANGE", group_zset_key, 0, 0)[1]
186
+ redis.call("ZREM", group_zset_key, lowest_snapshot_id)
187
+ if lowest_snapshot_id == id then
188
+ do_save = false
189
+ else
190
+ redis.call("HDEL", group_hash_key, lowest_snapshot_id)
191
+ end
192
+ group_size = group_size - 1
193
+ end
194
+ if do_save then
195
+ redis.call("HSET", group_hash_key, id, bytes)
196
+ end
156
197
  end
157
198
  LUA
158
199
  redis.eval(
159
200
  lua,
160
- keys: [zset_key, hash_key],
161
- argv: [id, score, bytes, limit]
201
+ keys: [group_zset_key, group_hash_key, overview_zset_key],
202
+ argv: [id, score, group_name, per_group_limit, groups_limit, @prefix, bytes]
162
203
  )
163
204
  end
164
205
 
165
- def fetch_snapshots(batch_size: 200, &blk)
166
- zset_key = snapshot_zset_key()
167
- hash_key = snapshot_hash_key()
168
- iteration = 0
169
- corrupt_snapshots = []
170
- while true
171
- ids = redis.zrange(
172
- zset_key,
173
- batch_size * iteration,
174
- batch_size * iteration + batch_size - 1
175
- )
176
- break if ids.size == 0
177
- batch = redis.mapped_hmget(hash_key, *ids).to_a
178
- batch.map! do |id, bytes|
179
- begin
180
- Marshal.load(bytes)
181
- rescue
182
- corrupt_snapshots << id
183
- nil
184
- end
206
+ def fetch_snapshots_overview
207
+ overview_zset_key = snapshot_overview_zset_key
208
+ groups = redis
209
+ .zrange(overview_zset_key, 0, -1, withscores: true)
210
+ .map { |(name, worst_score)| [name, { worst_score: worst_score }] }
211
+
212
+ prefixed_group_names = groups.map { |(group_name, _)| group_snapshot_zset_key(group_name) }
213
+ metadata = redis.eval(<<~LUA, keys: prefixed_group_names)
214
+ local metadata = {}
215
+ for i, k in ipairs(KEYS) do
216
+ local best = redis.call("ZRANGE", k, 0, 0, "WITHSCORES")[2]
217
+ local count = redis.call("ZCARD", k)
218
+ metadata[i] = {best, count}
185
219
  end
186
- batch.compact!
187
- blk.call(batch) if batch.size != 0
188
- break if ids.size < batch_size
189
- iteration += 1
220
+ return metadata
221
+ LUA
222
+ groups.each.with_index do |(_, hash), index|
223
+ best, count = metadata[index]
224
+ hash[:best_score] = best.to_f
225
+ hash[:snapshots_count] = count.to_i
226
+ end
227
+ groups.to_h
228
+ end
229
+
230
+ def fetch_snapshots_group(group_name)
231
+ group_hash_key = group_snapshot_hash_key(group_name)
232
+ snapshots = []
233
+ corrupt_snapshots = []
234
+ redis.hgetall(group_hash_key).each do |id, bytes|
235
+ # rubocop:disable Security/MarshalLoad
236
+ snapshots << Marshal.load(bytes)
237
+ # rubocop:enable Security/MarshalLoad
238
+ rescue
239
+ corrupt_snapshots << id
190
240
  end
191
241
  if corrupt_snapshots.size > 0
192
- redis.pipelined do
193
- redis.zrem(zset_key, corrupt_snapshots)
194
- redis.hdel(hash_key, corrupt_snapshots)
195
- end
242
+ cleanup_corrupt_snapshots(corrupt_snapshots, group_name)
196
243
  end
244
+ snapshots
197
245
  end
198
246
 
199
- def load_snapshot(id)
200
- hash_key = snapshot_hash_key()
201
- bytes = redis.hget(hash_key, id)
247
+ def load_snapshot(id, group_name)
248
+ group_hash_key = group_snapshot_hash_key(group_name)
249
+ bytes = redis.hget(group_hash_key, id)
250
+ return if !bytes
202
251
  begin
252
+ # rubocop:disable Security/MarshalLoad
203
253
  Marshal.load(bytes)
254
+ # rubocop:enable Security/MarshalLoad
204
255
  rescue
205
- redis.pipelined do
206
- redis.zrem(snapshot_zset_key(), id)
207
- redis.hdel(hash_key, id)
208
- end
256
+ cleanup_corrupt_snapshots([id], group_name)
209
257
  nil
210
258
  end
211
259
  end
@@ -231,12 +279,20 @@ unviewed_ids: #{get_unviewed_ids(user)}
231
279
  @snapshot_counter_key ||= "#{@prefix}-mini-profiler-snapshots-counter"
232
280
  end
233
281
 
234
- def snapshot_zset_key
235
- @snapshot_zset_key ||= "#{@prefix}-mini-profiler-snapshots-zset"
282
+ def group_snapshot_zset_key(group_name)
283
+ # if you change this key, remember to change it in the LUA script in
284
+ # the push_snapshot method as well
285
+ "#{@prefix}-mp-group-snapshot-zset-key-#{group_name}"
236
286
  end
237
287
 
238
- def snapshot_hash_key
239
- @snapshot_hash_key ||= "#{@prefix}-mini-profiler-snapshots-hash"
288
+ def group_snapshot_hash_key(group_name)
289
+ # if you change this key, remember to change it in the LUA script in
290
+ # the push_snapshot method as well
291
+ "#{@prefix}-mp-group-snapshot-hash-key-#{group_name}"
292
+ end
293
+
294
+ def snapshot_overview_zset_key
295
+ "#{@prefix}-mp-overviewgroup-snapshot-zset-key"
240
296
  end
241
297
 
242
298
  def cached_redis_eval(script, script_sha, reraise: true, argv: [], keys: [])
@@ -251,13 +307,45 @@ unviewed_ids: #{get_unviewed_ids(user)}
251
307
  end
252
308
  end
253
309
 
310
+ def cleanup_corrupt_snapshots(corrupt_snapshots_ids, group_name)
311
+ group_hash_key = group_snapshot_hash_key(group_name)
312
+ group_zset_key = group_snapshot_zset_key(group_name)
313
+ overview_zset_key = snapshot_overview_zset_key
314
+ lua = <<~LUA
315
+ local group_hash_key = KEYS[1]
316
+ local group_zset_key = KEYS[2]
317
+ local overview_zset_key = KEYS[3]
318
+ local group_name = ARGV[1]
319
+ for i, k in ipairs(ARGV) do
320
+ if k ~= group_name then
321
+ redis.call("HDEL", group_hash_key, k)
322
+ redis.call("ZREM", group_zset_key, k)
323
+ end
324
+ end
325
+ if redis.call("ZCARD", group_zset_key) == 0 then
326
+ redis.call("ZREM", overview_zset_key, group_name)
327
+ redis.call("DEL", group_hash_key, group_zset_key)
328
+ else
329
+ local worst_score = tonumber(redis.call("ZRANGE", group_zset_key, -1, -1, "WITHSCORES")[2])
330
+ redis.call("ZADD", overview_zset_key, worst_score, group_name)
331
+ end
332
+ LUA
333
+ redis.eval(
334
+ lua,
335
+ keys: [group_hash_key, group_zset_key, overview_zset_key],
336
+ argv: [group_name, *corrupt_snapshots_ids]
337
+ )
338
+ end
339
+
254
340
  # only used in tests
255
341
  def wipe_snapshots_data
256
- redis.pipelined do
257
- redis.del(snapshot_counter_key())
258
- redis.del(snapshot_zset_key())
259
- redis.del(snapshot_hash_key())
260
- end
342
+ keys = redis.keys(group_snapshot_hash_key('*'))
343
+ keys += redis.keys(group_snapshot_zset_key('*'))
344
+ redis.del(
345
+ keys,
346
+ snapshot_overview_zset_key,
347
+ snapshot_counter_key
348
+ )
261
349
  end
262
350
  end
263
351
  end
@@ -2,7 +2,7 @@
2
2
 
3
3
  module Rack
4
4
  class MiniProfiler
5
- VERSION = '2.3.3'
5
+ VERSION = '3.0.0'
6
6
  SOURCE_CODE_URI = 'https://github.com/MiniProfiler/rack-mini-profiler'
7
7
  end
8
8
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rack-mini-profiler
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.3.3
4
+ version: 3.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sam Saffron
@@ -10,7 +10,7 @@ authors:
10
10
  autorequire:
11
11
  bindir: bin
12
12
  cert_chain: []
13
- date: 2021-08-30 00:00:00.000000000 Z
13
+ date: 2022-02-24 00:00:00.000000000 Z
14
14
  dependencies:
15
15
  - !ruby/object:Gem::Dependency
16
16
  name: rack