lowrail-profile 0.1.2

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,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "loaded_constant"
4
+
5
+ module Lowrail
6
+ # Readiness, not loading. Global TracePoints permanently patch VM bytecodes,
7
+ # even after disable. Observe AS's own initialization and successful native
8
+ # autoload/require completion instead; never resolve an autoload to check it.
9
+ module LoadHooks
10
+ class << self
11
+ def active_support(&block)
12
+ support = Lowrail.loaded_constant("ActiveSupport")
13
+ return block.call if support&.respond_to?(:on_load)
14
+ (@support_waiters ||= []) << block
15
+ Object.singleton_class.prepend(WatchSupport) unless Object.singleton_class < WatchSupport
16
+ watch_support if support
17
+ end
18
+
19
+ def watch_support
20
+ support = Lowrail.loaded_constant("ActiveSupport") or return
21
+ support.singleton_class.prepend(WatchLazyHooks) unless support.singleton_class < WatchLazyHooks
22
+ hooks = Lowrail.loaded_constant("ActiveSupport::LazyLoadHooks") or return
23
+ hooks.singleton_class.prepend(AfterExtension) unless hooks.singleton_class < AfterExtension
24
+ end
25
+
26
+ def support_ready
27
+ support = Lowrail.loaded_constant("ActiveSupport")
28
+ return unless support&.respond_to?(:on_load)
29
+ pending, @support_waiters = @support_waiters || [], []
30
+ pending.each(&:call)
31
+ end
32
+
33
+ # nil means no identifiable completion boundary, not permission to load.
34
+ def dependency(name)
35
+ owner = Object
36
+ name.delete_prefix("::").split("::").each do |part|
37
+ return unless Module === owner
38
+ return owner.autoload?(part, false) if owner.autoload?(part, false)
39
+ return unless owner.const_defined?(part, false)
40
+ owner = owner.const_get(part, false)
41
+ end
42
+ :loaded
43
+ end
44
+
45
+ def when_loaded(names, &activate)
46
+ dependencies = names.to_h { [_1, dependency(_1)] }.reject { |_, feature| feature == :loaded }
47
+ return activate.call if dependencies.empty?
48
+ (@waiters ||= []) << [dependencies, activate]
49
+ # Installed only after initialized boot: Zeitwerk must first finish
50
+ # aliasing Kernel#require. Native MRI autoload dispatches through it.
51
+ Kernel.prepend(RequireCompletion) unless Kernel < RequireCompletion
52
+ return if @zeitwerk_hooked
53
+ rails = Lowrail.loaded_constant("Rails")
54
+ return unless rails&.respond_to?(:autoloaders)
55
+ @zeitwerk_hooked = true
56
+ rails.autoloaders.each { |loader| loader.on_load { |name, _| completed(name: name) } }
57
+ end
58
+
59
+ def waiting? = @waiters && !@waiters.empty?
60
+
61
+ def completed(feature: nil, name: nil)
62
+ return unless waiting?
63
+ ready = []
64
+ @waiters.delete_if do |dependencies, activate|
65
+ dependencies.keys.each do |constant|
66
+ next unless (feature && dependencies[constant] == feature) || name == constant
67
+ state = dependency(constant)
68
+ state == :loaded ? dependencies.delete(constant) : dependencies[constant] = state
69
+ end
70
+ ready << activate if dependencies.empty?
71
+ dependencies.empty?
72
+ end
73
+ ready.each(&:call)
74
+ rescue StandardError, ScriptError => error
75
+ Lowrail.debug("load activation declined: #{error.class}: #{error.message}")
76
+ end
77
+ end
78
+
79
+ module WatchSupport
80
+ private
81
+
82
+ def const_added(name)
83
+ super
84
+ LoadHooks.watch_support if equal?(Object) && name == :ActiveSupport
85
+ end
86
+ end
87
+
88
+ module WatchLazyHooks
89
+ private
90
+
91
+ def const_added(name)
92
+ super
93
+ LoadHooks.watch_support if name == :LazyLoadHooks
94
+ end
95
+ end
96
+
97
+ module AfterExtension
98
+ def extended(base)
99
+ super
100
+ LoadHooks.support_ready if base.equal?(Lowrail.loaded_constant("ActiveSupport"))
101
+ end
102
+ end
103
+
104
+ module RequireCompletion
105
+ private
106
+
107
+ def require(path)
108
+ return super unless LoadHooks.waiting?
109
+ # Do not activate halfway through an enclosing require, nor after an
110
+ # exception that left partially defined constants. Never intercept
111
+ # require_relative: a Ruby wrapper changes its lexical base directory.
112
+ stack = (Thread.current[:__lowrail_requires] ||= [])
113
+ stack << []
114
+ success = false
115
+ result = super
116
+ stack.last << path if String === path
117
+ success = true
118
+ result
119
+ ensure
120
+ if stack
121
+ features = stack.pop
122
+ if success
123
+ if stack.empty?
124
+ features.each { |feature| LoadHooks.completed(feature: feature) }
125
+ else
126
+ stack.last.concat(features)
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ # What the profiler and the lowering runtime share from lib/lowrail.rb,
4
+ # without the runtime: requiring this loads nothing else.
5
+ module Lowrail
6
+ CONST_DEFINED = Module.instance_method(:const_defined?)
7
+ AUTOLOAD = Module.instance_method(:autoload?)
8
+ CONST_GET = Module.instance_method(:const_get)
9
+ CONST_PREFIX = String.instance_method(:delete_prefix)
10
+ CONST_PARTS = String.instance_method(:split)
11
+ CONST_EACH = Array.instance_method(:each)
12
+ private_constant :CONST_DEFINED, :AUTOLOAD, :CONST_GET, :CONST_PREFIX, :CONST_PARTS, :CONST_EACH
13
+
14
+ class << self
15
+ # Runtime facts observe constants; they never resolve an autoload or
16
+ # invoke const_missing. A missing dependency means wait or fall back.
17
+ def loaded_constant(name)
18
+ owner = Object
19
+ CONST_EACH.bind_call(CONST_PARTS.bind_call(CONST_PREFIX.bind_call(name, "::"), "::")) do |part|
20
+ return unless Module === owner && CONST_DEFINED.bind_call(owner, part, false) &&
21
+ !AUTOLOAD.bind_call(owner, part, false)
22
+ owner = CONST_GET.bind_call(owner, part, false)
23
+ end
24
+ owner
25
+ end
26
+
27
+ def debug(msg)
28
+ warn "[lowrail] #{msg}" if ENV["LOWRAIL_DEBUG"]
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,521 @@
1
+ # frozen_string_literal: true
2
+
3
+ # In-app allocation profile (docs/profile.md). Loaded only by exe/lowrail-profile,
4
+ # through RUBYOPT, when LOWRAIL_PROFILE names an output directory; nothing in
5
+ # Lowrail requires it otherwise, so an app with the gem but without the
6
+ # variable runs unchanged.
7
+ #
8
+ # Counts objects per source line inside windows: Rails::Engine#call (every
9
+ # request the app serves: integration and system tests, a local server, a
10
+ # workloads file), Active Job's perform_now, a mail's build and delivery, and
11
+ # Action Cable channel actions. Each window is named by its controller action,
12
+ # job, mailer action or channel action. Writes one TSV per process at exit. It
13
+ # never forces a load: every hook is installed from Active Support's on_load
14
+ # hooks, when the framework class is defined. Like the rest of setup, it
15
+ # requires no default gems, so Bundler's activation is unchanged.
16
+ #
17
+ # Never break the app: an extension of another version is refused before
18
+ # anything is hooked, and every profiler call (installing a hook, opening,
19
+ # naming and closing a window, recording) is contained where it runs, so the
20
+ # app's own results and exceptions pass through unchanged. Code in other
21
+ # Ractors runs uncounted: the native tables are the main Ractor's.
22
+ if (dir = ENV["LOWRAIL_PROFILE"]) && !dir.empty?
23
+ begin
24
+ ext = ENV.fetch("LOWRAIL_PROFILE_EXT")
25
+ require ext
26
+ api = (Lowrail::Profile::API if defined?(Lowrail::Profile::API))
27
+ raise LoadError, "#{ext} is not this lowrail-profile's counter (API #{api.inspect}, expected 3); run lowrail-profile again" unless api == 3
28
+ require_relative "load_hooks"
29
+
30
+ module Lowrail
31
+ module Profile
32
+ TYPES = %w[NONE Object Class Module Float String Regexp Array Hash Struct Bignum File Data MatchData
33
+ Complex Rational 0x10 nil true false Symbol Fixnum undef 0x17 0x18 0x19 IMEMO Node ICLASS Zombie
34
+ Moved 0x1f].freeze
35
+
36
+ KINDS = %w[request job mail cable].freeze
37
+ APP_ROOT = ENV["LOWRAIL_PROFILE_ROOT"]
38
+ HASH = "#"
39
+ DOT = "."
40
+ PERFORM = "perform"
41
+ PERFORM_ACTION = "perform_action"
42
+ SUBSCRIBED = "subscribed"
43
+ DELIVER = "deliver_mail"
44
+ SERVE = "serve"
45
+ ACTION = "action"
46
+ NOTED = "lowrail.profile.noted"
47
+ FILTERED = "[FILTERED]"
48
+ JSON_TYPE = "application/json"
49
+ # A write's Accept values a workloads file sends anyway (html, IntegrationTest's, xhr:, as: :json).
50
+ PLAIN_ACCEPT = %w[*/* text/html text/xml application/xml application/xhtml+xml application/json text/javascript].freeze
51
+ CONSTANT = /\A[A-Z]\w*(?:::[A-Z]\w*)*\z/
52
+ KERNEL_CLASS = Kernel.instance_method(:class)
53
+
54
+ module Window
55
+ def call(env)
56
+ open = Profile.open(0)
57
+ super
58
+ ensure
59
+ Profile.close(open, env)
60
+ end
61
+ end
62
+
63
+ # Names the request after the first controller action it dispatches.
64
+ module Dispatch
65
+ def dispatch(name, request, response)
66
+ Profile.named(self.class, HASH, name)
67
+ super
68
+ end
69
+ end
70
+
71
+ # Controller tests bypass Rails::Engine#call, so no window counts them; the report counts them here.
72
+ module ControllerTest
73
+ def process(...)
74
+ Profile.controller_test
75
+ super
76
+ end
77
+ end
78
+
79
+ # Minitest reads SEED in Minitest.run, before it initializes plugins
80
+ # (register_plugin since 5.24; init_plugins before).
81
+ module Suite
82
+ def self.minitest_plugin_init(_options) = Profile.leave_env
83
+
84
+ def init_plugins(...)
85
+ Profile.leave_env
86
+ super
87
+ end
88
+ end
89
+
90
+ module Job
91
+ def perform_now
92
+ open = Profile.open(1)
93
+ Profile.named(self.class, HASH, PERFORM) if open
94
+ super
95
+ ensure
96
+ Profile.close(open)
97
+ end
98
+ end
99
+
100
+ # A worker deserializes the job's arguments before perform_now.
101
+ module JobExecute
102
+ def execute(...)
103
+ open = Profile.open(1)
104
+ super
105
+ ensure
106
+ Profile.close(open)
107
+ end
108
+ end
109
+
110
+ # A mail's build (the mailer action and its templates) and its
111
+ # delivery are separate windows, as the app runs them.
112
+ module MailBuild
113
+ def process(method_name, ...)
114
+ open = Profile.open(2)
115
+ Profile.named(self.class, HASH, method_name) if open
116
+ super(method_name, ...)
117
+ ensure
118
+ Profile.close(open)
119
+ end
120
+ end
121
+
122
+ module MailDelivery
123
+ def deliver_mail(...)
124
+ open = Profile.open(2)
125
+ Profile.named(self, DOT, DELIVER) if open
126
+ super
127
+ ensure
128
+ Profile.close(open)
129
+ end
130
+ end
131
+
132
+ # Channel actions are not request shapes: --record notes only Rack requests.
133
+ module Cable
134
+ def perform_action(data)
135
+ open = Profile.open(3)
136
+ Profile.cable_named(self.class, data) if open
137
+ super
138
+ ensure
139
+ Profile.close(open)
140
+ end
141
+
142
+ def subscribe_to_channel
143
+ open = Profile.open(3)
144
+ Profile.named(self.class, HASH, SUBSCRIBED) if open
145
+ super
146
+ ensure
147
+ Profile.close(open)
148
+ end
149
+ end
150
+
151
+ # What Socket.tcp allocates while it connects follows timing (Happy
152
+ # Eyeballs races its attempts on threads and timers): windows count it
153
+ # apart. With a block, the block is the app's own work and is counted.
154
+ module Connect
155
+ def tcp(...)
156
+ return super if block_given? || !Profile.main?
157
+ Profile.connect(true)
158
+ begin
159
+ super
160
+ ensure
161
+ Profile.connect(false)
162
+ end
163
+ end
164
+ end
165
+
166
+ # A file ActionDispatch::Static serves answers before routing, so no
167
+ # controller names its request: it is named after the file handler.
168
+ module Static
169
+ private def serve(...)
170
+ Profile.named(self.class, HASH, SERVE)
171
+ super
172
+ end
173
+ end
174
+
175
+ # A forked worker (parallel tests, a preforking server) starts from
176
+ # zero, so the parent's requests are not counted twice.
177
+ module Fork
178
+ def _fork
179
+ pid = super
180
+ Profile.forked if pid == 0
181
+ pid
182
+ end
183
+ end
184
+
185
+ class << self
186
+ # Ractor.main? is Ruby 3.4's.
187
+ if Ractor.respond_to?(:main?)
188
+ def main? = Ractor.main?
189
+ else
190
+ def main? = Ractor.current.equal?(Ractor.main)
191
+ end
192
+
193
+ # lowrail-profile --record: request shapes by route, noted after the
194
+ # window closes, so they are not counted.
195
+ attr_accessor :shapes
196
+
197
+ # Each returns quietly when the profiler cannot do its part.
198
+ def open(kind)
199
+ return false unless main?
200
+ hooks unless @connects && @static
201
+ enter(kind)
202
+ rescue StandardError
203
+ false
204
+ end
205
+
206
+ # Hooked once the app has loaded them, before a window opens.
207
+ def hooks
208
+ @connects ||= hook("Socket") { _1.singleton_class.prepend(Connect) unless _1.singleton_class < Connect }
209
+ @static ||= hook("ActionDispatch::FileHandler") { _1.prepend(Static) unless _1 < Static }
210
+ end
211
+
212
+ def hook(name)
213
+ target = Lowrail.loaded_constant(name) or return false
214
+ install(name) { yield target }
215
+ true
216
+ end
217
+
218
+ def close(open, env = nil)
219
+ return unless open
220
+ leave
221
+ note(env) if env && shapes
222
+ rescue StandardError
223
+ nil
224
+ end
225
+
226
+ def named(klass, separator, action)
227
+ label(klass, separator, action) if main?
228
+ rescue StandardError
229
+ nil
230
+ end
231
+
232
+ def cable_named(klass, data)
233
+ label(klass, HASH, (data[ACTION] if Hash === data) || PERFORM_ACTION) if main?
234
+ rescue StandardError
235
+ nil
236
+ end
237
+
238
+ def controller_test
239
+ @controller_tests = controller_tests + 1 if main?
240
+ rescue StandardError
241
+ nil
242
+ end
243
+
244
+ def controller_tests = @controller_tests || 0
245
+
246
+ def forked
247
+ reset
248
+ @controller_tests = 0
249
+ self.shapes = {} if shapes
250
+ rescue StandardError
251
+ nil
252
+ end
253
+
254
+ # A framework hook that cannot be installed (a frozen class) leaves
255
+ # that framework uncounted and the app's load as it was.
256
+ def install(what)
257
+ yield
258
+ rescue StandardError, ScriptError => error
259
+ warn "[lowrail-profile] #{what} not profiled: #{error.class}: #{error.message}"
260
+ end
261
+
262
+ # Once the suite has read its seed, puts back the environment
263
+ # exe/lowrail-profile changed, so every process the suite starts
264
+ # (an rspec in after(:suite), a rake task) runs as without it:
265
+ # unprofiled, with the caller's SEED and SPEC_OPTS. Bundler's own
266
+ # RUBYOPT and RUBYLIB entries stay. Bundler keeps a copy from before
267
+ # (ORIGINAL_ENV, BUNDLER_ORIG_*) for with_original_env and
268
+ # with_unbundled_env: it gets the same edits.
269
+ def leave_env
270
+ return if @left
271
+ @left = true
272
+ ours = ENV["LOWRAIL_PROFILE_KEYS"].to_s.split(",") << "LOWRAIL_PROFILE_KEYS"
273
+ lib = ENV["LOWRAIL_PROFILE_LIB"]
274
+ seed, spec_opts = ENV["LOWRAIL_PROFILE_CALLER_SEED"], ENV["LOWRAIL_PROFILE_CALLER_SPEC_OPTS"]
275
+ saved = Lowrail.loaded_constant("Bundler::ORIGINAL_ENV")
276
+ [ENV, (saved if saved.is_a?(Hash) && !saved.frozen?)].compact.each do |env|
277
+ set = ->(key, value) { value.nil? ? env.delete(key) : env[key] = value }
278
+ set.("SEED", seed)
279
+ set.("SPEC_OPTS", spec_opts)
280
+ { "RUBYOPT" => [" ", ["-I#{lib}", "-rlowrail/profile"]], "RUBYLIB" => [File::PATH_SEPARATOR, [lib]] }.each do |key, (separator, parts)|
281
+ ["", "BUNDLER_ORIG_"].each do |prefix|
282
+ name = "#{prefix}#{key}"
283
+ next unless (value = env[name])
284
+ list = value.split(separator)
285
+ parts.each { |part| (i = list.index(part)) && list.delete_at(i) }
286
+ next if list.size == value.split(separator).size
287
+ # Bundler's mark for "unset before", which it restores as unset.
288
+ set.(name, list.empty? ? (prefix.empty? ? nil : "BUNDLER_ENVIRONMENT_PRESERVER_INTENTIONALLY_NIL") : list.join(separator))
289
+ end
290
+ end
291
+ ours.each { env.delete(_1) }
292
+ end
293
+ rescue StandardError => error
294
+ warn "[lowrail-profile] processes the suite starts may be profiled: #{error.class}: #{error.message}"
295
+ end
296
+
297
+ def note(env)
298
+ return if env[NOTED] || !(route = env["action_dispatch.route"] || matched_route(env))
299
+ env[NOTED] = true
300
+ verb = env["REQUEST_METHOD"].to_s.downcase
301
+ filter = parameter_filter(env)
302
+ # Every path value, the format included, is filtered before it names,
303
+ # groups or is kept; without the app's filter none is kept.
304
+ path_params = filter ? filter.filter((env["action_dispatch.request.path_parameters"] || {}).transform_keys(&:to_s)) : {}
305
+ format = path_params["format"]&.to_s&.dup&.freeze
306
+ # Accept is filtered as Rails' filtered_env filters it, and not kept
307
+ # without the app's filter.
308
+ accept = filter ? filter.filter("HTTP_ACCEPT" => env["HTTP_ACCEPT"].to_s)["HTTP_ACCEPT"].to_s.dup.freeze : ""
309
+ first = accept[/\A[^,;]*/].strip.downcase
310
+ # A GET keeps its Accept as sent, never as: :json, which would send its query as a body.
311
+ json = verb != "get" && [env["CONTENT_TYPE"], env["HTTP_ACCEPT"]].any? { _1.to_s.start_with?(JSON_TYPE) }
312
+ accept = nil if first.empty? || (verb != "get" && PLAIN_ACCEPT.include?(first))
313
+ xhr = env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
314
+ spec = route.path.spec.to_s
315
+ shape = shapes[[verb, spec, json, xhr, format, accept, !filter]] ||=
316
+ shape_of(env, route, verb, spec, path_params, filter, format: format, json: json, xhr: xhr, accept: accept)
317
+ shape["count"] += 1
318
+ rescue StandardError
319
+ nil
320
+ end
321
+
322
+ # Rails before 8.1 keeps only the matched route's pattern and
323
+ # parameters: the route with that pattern, controller and action,
324
+ # or none when routes share them (their constraints and defaults,
325
+ # which tell them apart, are not run again here).
326
+ def matched_route(env)
327
+ spec = env["action_dispatch.route_uri_pattern"] or return
328
+ params = env["action_dispatch.request.path_parameters"] || {}
329
+ candidates = env["action_dispatch.routes"]&.routes&.select do |r|
330
+ r.path.spec.to_s == spec && r.defaults[:controller] == params[:controller] && r.defaults[:action] == params[:action]
331
+ end
332
+ candidates.first if candidates&.size == 1
333
+ end
334
+
335
+ # What a workloads file needs to send the request again, with the
336
+ # app's filter_parameters applied before anything is kept. Params
337
+ # are kept only if they could be filtered; nothing is taken from the
338
+ # raw path or query string.
339
+ def shape_of(env, route, verb, spec, path_params, filter, **flags)
340
+ lossy = [false]
341
+ controller = route.defaults[:controller].to_s
342
+ required = route.required_parts.map(&:to_s)
343
+ parts = required.map do |part|
344
+ base = part == "id" ? controller.split("/").last.to_s : part.delete_suffix("_id") if part == "id" || part.end_with?("_id")
345
+ model = base.singularize.camelize if base && !base.empty?
346
+ [part, (model if model && record_class?(model))]
347
+ end
348
+ lossy[0] = true if (path_params.keys - %w[controller action format] - required - route.defaults.keys.map(&:to_s)).any?
349
+ query = env["QUERY_STRING"].to_s
350
+ params = if verb == "get"
351
+ lossy[0] = true if env["CONTENT_LENGTH"].to_i > 0
352
+ query.empty? ? {} : env["action_dispatch.request.query_parameters"] || (lossy[0] = true; {})
353
+ else
354
+ lossy[0] = true unless query.empty?
355
+ env["action_dispatch.request.request_parameters"] || (env["CONTENT_LENGTH"].to_i > 0 ? (lossy[0] = true; {}) : {})
356
+ end
357
+ params = filter && plain(filter.filter(params.except("authenticity_token")), lossy)
358
+ seen = filter && plain(path_params.slice(*required), lossy)
359
+ name = route.name || env["action_dispatch.routes"]&.routes&.find { _1.name && _1.path.spec.to_s == spec }&.name
360
+ { "verb" => verb, "template" => spec.sub(/\(\.:format\)\z/, ""), "route" => name, "parts" => parts,
361
+ "seen" => seen, **flags.transform_keys(&:to_s), "params" => params, "unfiltered" => !filter,
362
+ "filtered" => filtered?(params) || filtered?(seen) || flags[:format] == FILTERED || flags[:accept] == FILTERED, "lossy" => lossy[0], "count" => 0 }
363
+ end
364
+
365
+ # The app's filter, only when its list is names and patterns: a Proc
366
+ # may depend on Rails' merged params, which the parts filtered here
367
+ # are not, so with one no request value is kept. Rebuilt when the
368
+ # list's contents change (an initializer or test may change it after
369
+ # the first request, or a String in it in place).
370
+ def parameter_filter(env)
371
+ klass = Lowrail.loaded_constant("ActiveSupport::ParameterFilter") or return
372
+ filters = Array(env["action_dispatch.parameter_filter"])
373
+ return unless filters.all? { Symbol === _1 || String === _1 || Regexp === _1 }
374
+ unless @filter && @filter_source == filters
375
+ @filter_source = filters.map { String === _1 ? _1.dup.freeze : _1 }.freeze
376
+ @filter = klass.new(@filter_source, mask: FILTERED)
377
+ end
378
+ @filter
379
+ end
380
+
381
+ # An Active Record model the app has loaded already (never loads one).
382
+ def record_class?(name)
383
+ return false unless name.match?(CONSTANT)
384
+ base = Lowrail.loaded_constant("ActiveRecord::Base")
385
+ model = base && Lowrail.loaded_constant(name)
386
+ Class === model && model < base ? true : false
387
+ end
388
+
389
+ def filtered?(value)
390
+ case value
391
+ when Hash then value.each_value.any? { filtered?(_1) }
392
+ when Array then value.any? { filtered?(_1) }
393
+ else value == FILTERED
394
+ end
395
+ end
396
+
397
+ # JSON-safe copy; lossy[0] is set when anything was shortened or replaced.
398
+ def plain(value, lossy)
399
+ case value
400
+ when Hash then value.to_h { [_1.to_s, plain(_2, lossy)] }
401
+ when Array then (lossy[0] = true if value.size > 50; value.first(50).map { plain(_1, lossy) })
402
+ when String
403
+ if !value.valid_encoding? || (value.encoding != Encoding::UTF_8 && !value.ascii_only?) then (lossy[0] = true; "(binary)")
404
+ elsif value.size > 2000 then (lossy[0] = true; value[0, 2000])
405
+ else value.dup.freeze
406
+ end
407
+ when Integer, true, false, nil then value
408
+ when Float then value.finite? ? value : (lossy[0] = true; nil)
409
+ else (lossy[0] = true; "(#{KERNEL_CLASS.bind_call(value)})")
410
+ end
411
+ end
412
+
413
+ def write(dir)
414
+ windows, objects, dropped, rows, actions, attributed = snapshot
415
+ return if windows.sum == 0 && controller_tests == 0
416
+ root = (Rails.root.to_s if defined?(Rails) && Rails.respond_to?(:root) && Rails.root)
417
+ lines = [["# lowrail-profile 4", "requests=#{windows[0]}", "objects=#{objects[0]}", "dropped=#{dropped}",
418
+ "windows=#{windows.join(",")}", "kind_objects=#{objects.join(",")}", "controller_tests=#{controller_tests}",
419
+ "pid=#{Process.pid}", "root=#{root || Dir.pwd}", "app_root=#{APP_ROOT || Dir.pwd}",
420
+ "ruby=#{RUBY_DESCRIPTION}",
421
+ "rails_env=#{ENV["RAILS_ENV"]}", "rails=#{Lowrail.loaded_constant("Rails::VERSION::STRING")}"].join("\t")]
422
+ # Each path once, as a "P id path" row before its first use: paths
423
+ # were four fifths of an attribution run's bytes.
424
+ ids = {}
425
+ id = lambda do |path|
426
+ next "-" unless path
427
+ ids.fetch(path) { lines << "P\t#{ids.size}\t#{path}"; ids[path] = ids.size.to_s }
428
+ end
429
+ rows.each do |path, line, type, count, reached, first, via, kind|
430
+ lines << [id.(path), line, TYPES[type], count, reached, first, via ? 1 : 0, KINDS[kind]].join("\t")
431
+ end
432
+ actions.each { |kind, name, *rest| lines << ["A", KINDS[kind], name || "-", *rest].join("\t") }
433
+ attributed.each do |kind, name, path, line, caller_path, caller_line, count, first|
434
+ lines << ["@", KINDS[kind], name || "-", id.(path), line || "-", id.(caller_path), caller_line || "-", count, first].join("\t")
435
+ end
436
+ # Gems from a path (Bundler's path:, gemspec), which no gem
437
+ # directory names: the report classifies their lines by these.
438
+ Gem.loaded_specs.each_value do |spec|
439
+ # Ruby names a required file by its real path.
440
+ gem_dir = (File.realpath(spec.full_gem_path) rescue spec.full_gem_path)
441
+ lines << ["G", spec.name, gem_dir].join("\t") unless gem_dir.match?(%r{/(?:gems|bundler/gems)/[^/]+-(?:\d|\h{12})[^/]*\z})
442
+ end
443
+ File.write(File.join(dir, "#{Process.pid}.tsv"), lines.join("\n") << "\n")
444
+ if shapes&.any?
445
+ # At exit Bundler has long set up, so json resolves to the app's own.
446
+ require "json"
447
+ File.write(File.join(dir, "#{Process.pid}.shapes.json"), JSON.generate(shapes.values))
448
+ end
449
+ rescue StandardError => error
450
+ warn "[lowrail-profile] not written: #{error.class}: #{error.message}"
451
+ end
452
+ end
453
+ end
454
+ end
455
+
456
+ # The repeat run records the nearest app frame of every allocation.
457
+ if ENV["LOWRAIL_PROFILE_ATTRIBUTE"] == "1"
458
+ Lowrail::Profile.attribute(File.join(ENV.fetch("LOWRAIL_PROFILE_ROOT", Dir.pwd), ""))
459
+ end
460
+ Lowrail::Profile.shapes = {} if ENV["LOWRAIL_PROFILE_RECORD"] == "1"
461
+ Lowrail::Profile.start
462
+ Lowrail::LoadHooks.active_support do
463
+ ActiveSupport.on_load(:before_configuration) do
464
+ Lowrail::Profile.install("Rails::Engine#call") do
465
+ Rails::Engine.prepend(Lowrail::Profile::Window) unless Rails::Engine < Lowrail::Profile::Window
466
+ end
467
+ end
468
+ # RSpec read SPEC_OPTS when its runner started, before the suite boots
469
+ # the app. Only a boot inside the runner: a gem such as rswag-specs loads
470
+ # RSpec::Core::Runner into a rake parent or a Minitest suite too.
471
+ ActiveSupport.on_load(:before_configuration) do
472
+ Lowrail::Profile.leave_env if caller_locations.any? { _1.path.to_s.end_with?("/rspec/core/runner.rb") }
473
+ end
474
+ ActiveSupport.on_load(:active_support_test_case) do
475
+ Lowrail::Profile.install("Minitest") do
476
+ if Minitest.respond_to?(:register_plugin)
477
+ Minitest.register_plugin(Lowrail::Profile::Suite)
478
+ else
479
+ Minitest.singleton_class.prepend(Lowrail::Profile::Suite)
480
+ end
481
+ end
482
+ end
483
+ # Each hook runs when the app loads the class; the modules they prepend
484
+ # into (Metal, Base) are already loaded by then.
485
+ ActiveSupport.on_load(:action_controller) do
486
+ Lowrail::Profile.install("ActionController::Metal#dispatch") do
487
+ metal = ActionController::Metal
488
+ metal.prepend(Lowrail::Profile::Dispatch) unless metal < Lowrail::Profile::Dispatch
489
+ end
490
+ end
491
+ # Runs as each test class includes ActionController::TestCase::Behavior.
492
+ ActiveSupport.on_load(:action_controller_test_case) do
493
+ Lowrail::Profile.install("controller tests") do
494
+ behavior = ActionController::TestCase::Behavior
495
+ behavior.prepend(Lowrail::Profile::ControllerTest) unless behavior < Lowrail::Profile::ControllerTest
496
+ end
497
+ end
498
+ ActiveSupport.on_load(:active_job) do
499
+ Lowrail::Profile.install("Active Job") do
500
+ prepend(Lowrail::Profile::Job) unless self < Lowrail::Profile::Job
501
+ singleton_class.prepend(Lowrail::Profile::JobExecute) unless singleton_class < Lowrail::Profile::JobExecute
502
+ end
503
+ end
504
+ ActiveSupport.on_load(:action_mailer) do
505
+ Lowrail::Profile.install("Action Mailer") do
506
+ prepend(Lowrail::Profile::MailBuild) unless self < Lowrail::Profile::MailBuild
507
+ singleton_class.prepend(Lowrail::Profile::MailDelivery) unless singleton_class < Lowrail::Profile::MailDelivery
508
+ end
509
+ end
510
+ ActiveSupport.on_load(:action_cable_channel) do
511
+ Lowrail::Profile.install("Action Cable") do
512
+ prepend(Lowrail::Profile::Cable) unless self < Lowrail::Profile::Cable
513
+ end
514
+ end
515
+ end
516
+ Process.singleton_class.prepend(Lowrail::Profile::Fork)
517
+ at_exit { Lowrail::Profile.write(dir) }
518
+ rescue StandardError, ScriptError => error
519
+ warn "[lowrail-profile] off: #{error.class}: #{error.message}"
520
+ end
521
+ end