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,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lowrail
4
+ module Profile
5
+ VERSION = "0.1.2"
6
+ end
7
+ end
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ # bin/rails runner workload for lowrail-profile --workloads FILE: the file's
4
+ # requests (lowrail/workloads.rb, gem/lib/lowrail/workloads.rb) through the
5
+ # app's full middleware stack, 10 warmup passes and 20 counted ones (counts
6
+ # reset after warmup), under the request policy script/census app uses
7
+ # (Workloads::Replayer: a browser's headers, sign-in, CSRF tokens, the
8
+ # cookies earlier responses set). A response outside the request's expect:
9
+ # stops the run, so a broken path is not profiled as an error page.
10
+ #
11
+ # Experimental. Without --allow-writes only GETs are sent (see below). The
12
+ # requests are real: they write to the app's database and go through its
13
+ # own queue adapter and mail delivery, so jobs they enqueue run inline or reach
14
+ # real workers and mail is delivered as configured. What is not run here is the
15
+ # file's own mail and job workloads (the census runs them). The receipt says
16
+ # which, and which adapters the requests used.
17
+ require "rack/mock"
18
+ require "json"
19
+ require "uri"
20
+ require_relative "workloads"
21
+ require_relative "loaded_constant"
22
+
23
+ file, receipt = ARGV.fetch(0), ARGV[1]
24
+
25
+ # Without --allow-writes: no production database on another machine, and a
26
+ # file that declares only GETs, refused as each declaration is evaluated (before
27
+ # a setup block runs). Code the file runs itself is the app's, as in a test.
28
+ unless ENV["LOWRAIL_PROFILE_ALLOW_WRITES"] == "1"
29
+ if Rails.env.production?
30
+ # Every writable database: database_tasks: false only skips Rails' tasks
31
+ # (configs_for hides it by default), a replica takes no writes. Active
32
+ # Record is not loaded for this; before it is, its raw configuration.
33
+ configs = if (base = Lowrail.loaded_constant("ActiveRecord::Base"))
34
+ base.configurations.configs_for(env_name: Rails.env, include_hidden: true).map(&:configuration_hash)
35
+ elsif File.exist?(Rails.root.join("config/database.yml")) || ENV["DATABASE_URL"]
36
+ begin
37
+ config = Rails.application.config.database_configuration[Rails.env] || {}
38
+ rescue StandardError => e
39
+ abort "lowrail-profile: RAILS_ENV=production and its database configuration did not load (#{e.message}); " \
40
+ "--workloads sends real requests, so it needs --allow-writes there"
41
+ end
42
+ config.key?("adapter") || config.key?("url") ? [config] : config.values.grep(Hash)
43
+ else
44
+ []
45
+ end
46
+ configs = configs.reject { _1[:replica] || _1["replica"] }
47
+ hosts = configs.map { |c| c[:host] || c["host"] || ((url = c[:url] || c["url"]) && (URI(url).host rescue url)) }
48
+ hosts << URI(ENV["DATABASE_URL"]).host if ENV["DATABASE_URL"]
49
+ remote = hosts.compact.map(&:to_s).reject { _1.empty? || _1.start_with?("/") || %w[localhost 127.0.0.1 ::1 [::1]].include?(_1) }
50
+ abort "lowrail-profile: RAILS_ENV=production with a database on #{remote.uniq.join(", ")}; --workloads sends real requests, " \
51
+ "so it needs --allow-writes there" if remote.any?
52
+ end
53
+ # The method the app's router sees: env: and headers: can replace the
54
+ # declared one, and a JSON GET with params goes out as a POST that only
55
+ # Rack::MethodOverride turns back into a GET (API-only apps drop it). A
56
+ # block or alternate: changes only path and params, never the method.
57
+ overridden = Rails.application.middleware.middlewares.any? { _1.name == "Rack::MethodOverride" }
58
+ probe = Lowrail::Workloads::MockClient.new(nil, "localhost")
59
+ read_only = Module.new do
60
+ refuse = ->(what) { raise Lowrail::Workloads::WriteRefused, "#{what}; --workloads sends real requests, so it needs --allow-writes" }
61
+ define_method(:setup) { refuse.("setup runs code before the requests") }
62
+ (Lowrail::Workloads::VERBS - [:get]).each do |verb|
63
+ define_method(verb) { |path, **| refuse.("#{verb.upcase} #{path} is a write") }
64
+ end
65
+ define_method(:get) do |path, **opts, &block|
66
+ refuse.("GET #{path} has jobs: (its jobs run or are enqueued for real)") if opts[:jobs]
67
+ super(path, **opts, &block)
68
+ r = @requests.last
69
+ env = probe.env(r.verb, r.path, params: r.params, headers: r.headers, body: r.body)
70
+ sent = env["REQUEST_METHOD"]
71
+ if overridden && sent == "POST"
72
+ method = (Rack::MethodOverride.new(nil).method_override(env) rescue nil)
73
+ sent = method if Rack::MethodOverride::HTTP_METHODS.include?(method)
74
+ end
75
+ refuse.("GET #{path} is sent as #{sent}") unless sent == "GET"
76
+ end
77
+ define_method(:sign_in) do |path = nil, method: :post, cookie: nil, **opts|
78
+ refuse.("sign_in #{method.to_s.upcase} #{path} is a write") unless cookie || method.to_sym == :get
79
+ super(path, method: method, cookie: cookie, **opts)
80
+ end
81
+ end
82
+ Lowrail::Workloads::Definition.prepend(read_only)
83
+ end
84
+ begin
85
+ definition = Lowrail::Workloads.load(file)
86
+ rescue Lowrail::Workloads::WriteRefused => e
87
+ abort "lowrail-profile: #{file}: #{e.message}"
88
+ end
89
+ abort "lowrail-profile: #{file} has no requests" if definition.requests.empty?
90
+ host = ENV.fetch("LOWRAIL_PROFILE_HOST", "localhost")
91
+ client = -> { Lowrail::Workloads::MockClient.new(Rails.application, host) }
92
+ replay = Lowrail::Workloads::Replayer.new(definition, client.(), client.())
93
+
94
+ # The adapters in use, or before their framework is loaded (it is not loaded
95
+ # here for this) the configured ones; Rails' defaults are async and smtp.
96
+ loaded = ->(owner, name) { owner.const_defined?(name, false) && !owner.autoload?(name, false) }
97
+ config = Rails.application.config
98
+ side_effects = {
99
+ "queue_adapter" => if defined?(ActiveJob) && loaded.(ActiveJob, :Base) then ActiveJob::Base.queue_adapter_name
100
+ elsif config.respond_to?(:active_job) then config.active_job.queue_adapter || "async (default)"
101
+ end,
102
+ "delivery_method" => if defined?(ActionMailer) && loaded.(ActionMailer, :Base) then ActionMailer::Base.delivery_method
103
+ elsif config.respond_to?(:action_mailer) then config.action_mailer.delivery_method || "smtp (default)"
104
+ end
105
+ }.compact.transform_values(&:to_s)
106
+ warn "lowrail-profile: the requests are real#{" (#{side_effects.map { "#{_1} #{_2}" }.join(", ")})" unless side_effects.empty?}; " \
107
+ "run them against a disposable database, queue and mail service"
108
+ measured = {}
109
+ # Every counted request as sent, in order: compare checks that two captures
110
+ # measured the same sequence, not only the same declarations.
111
+ require "digest"
112
+ sequence = Digest::SHA256.new
113
+ sequence << JSON.generate([host, Lowrail::Workloads::BROWSER])
114
+ counted = 0
115
+ # Written before the passes (a diagnostic if the run stops) and after them;
116
+ # only the final one is complete, and only it writes the run's measured.json.
117
+ write = lambda do |complete|
118
+ measured_run = { "requests" => counted, "sha256" => sequence.hexdigest[0, 16], "complete" => complete }
119
+ uncertified = definition.manifest["requests"].select { _1["headers_uncertified"] }.map { _1["name"] }
120
+ measured_run["uncertified"] = uncertified unless uncertified.empty?
121
+ if complete && (run = ENV["LOWRAIL_PROFILE"]) && File.directory?(run)
122
+ File.write(File.join(run, "measured.json"), JSON.generate(measured_run) + "\n")
123
+ end
124
+ next unless receipt
125
+ File.write(receipt, JSON.pretty_generate("manifest" => definition.manifest, "replayed" => definition.requests.map(&:name),
126
+ "side_effects" => side_effects.merge("requests_enqueuing_jobs" => definition.requests.select(&:jobs).map(&:name),
127
+ "note" => "requests enqueue through the app's own queue adapter and deliver through its mail delivery: an inline " \
128
+ "adapter runs their jobs in the request, any other enqueues real work"),
129
+ "not_replayed" => { "mails" => definition.mails.map(&:name), "jobs" => definition.jobs.map(&:name) },
130
+ # A block's or alternate's requests as measured (the manifest has only the declaration).
131
+ "measured_variants" => measured,
132
+ "measured" => measured_run) + "\n")
133
+ end
134
+ write.(false)
135
+
136
+ current = nil
137
+ pass = lambda do |record|
138
+ definition.requests.each do |r|
139
+ current = r
140
+ spec = replay.perform(r)
141
+ next unless record
142
+ counted += 1
143
+ sequence << JSON.generate([r.name, r.verb, r.signed_in, spec.variant, spec.to_h["headers_sha256"]])
144
+ next unless r.block || r.alternate
145
+ list = measured[r.name] ||= []
146
+ list << spec.variant unless list.size >= 20 || list.include?(spec.variant)
147
+ end
148
+ end
149
+ begin
150
+ replay.sign_in
151
+ 10.times { pass.(false) }
152
+ Lowrail::Profile.reset if defined?(Lowrail::Profile::Window)
153
+ 20.times { pass.(true) }
154
+ rescue RuntimeError => e
155
+ abort "lowrail-profile: #{current ? "#{current.name}: " : "sign_in: "}#{e.message}"
156
+ end
157
+ write.(true)
@@ -0,0 +1,489 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The workloads file, lowrail/workloads.rb in the app, read by both
4
+ # `script/census app` and `lowrail-profile` (docs/upstream/census.md#workloads-file).
5
+ # It is Ruby in ActionDispatch::IntegrationTest's words (get, post, params:,
6
+ # headers:, xhr:, as: :json, route helpers), evaluated only inside an app that
7
+ # has finished booting, so it loads nothing earlier than the app would. Loading
8
+ # this file requires nothing; json and digest are required when a manifest is built.
9
+ module Lowrail
10
+ module Workloads
11
+ PATH = "lowrail/workloads.rb"
12
+ VERBS = %i[get post patch put delete].freeze
13
+ WRITE_EXPECT = [200, 201, 202, 204, 302, 303].freeze
14
+ JSON_TYPE = "application/json"
15
+ OPTIONS = %i[params headers env xhr as name expect jobs alternate signed_in csrf].freeze
16
+ # What a recording writes for a value the app's filter_parameters hides.
17
+ FILTERED = "[FILTERED]"
18
+ # A browser's headers, which both clients send under each request's own:
19
+ # census 4's Rack::Test client and lowrail-profile's (MockClient, which
20
+ # also sends the Host header Rack::Test sends). Apps
21
+ # branch on them (allow_browser, Origin and Sec-Fetch-Site CSRF checks).
22
+ BROWSER = { "HTTPS" => "on", "HTTP_USER_AGENT" => "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0",
23
+ "HTTP_ACCEPT" => "text/html", "HTTP_SEC_FETCH_SITE" => "same-origin", "HTTP_ORIGIN" => "https://localhost" }.freeze
24
+ CONSTANT = /\A[A-Z]\w*(?:::[A-Z]\w*)*\z/
25
+ HELPER = /\A[a-z_]\w*\z/
26
+ # lowrail-profile --workloads without --allow-writes.
27
+ class WriteRefused < StandardError; end
28
+
29
+ # One request as the file declares it. #at(n) is the request for its n-th
30
+ # run (from 1): alternates in turn, or the block's overrides for n. Its
31
+ # values are frozen copies, so changing an object the file passed in does
32
+ # not change the request after its manifest was written.
33
+ class Request
34
+ attr_reader :name, :verb, :path, :params, :body, :headers, :expect, :kind, :csrf, :jobs, :signed_in, :alternate, :block, :source
35
+
36
+ def initialize(verb, path, opts, block, scope, source)
37
+ unknown = opts.keys - OPTIONS
38
+ raise ArgumentError, "#{source}: unknown option #{unknown.map(&:inspect).join(", ")} (#{OPTIONS.join(", ")})" if unknown.any?
39
+ raise ArgumentError, "#{source}: as: #{opts[:as].inspect} is not supported (only :json)" if opts[:as] && opts[:as] != :json
40
+ @verb, @scope, @source, @block = verb, scope, source, block
41
+ @json = opts[:as] == :json
42
+ @xhr = opts[:xhr] ? true : false
43
+ # IntegrationTest sends a JSON GET with params as a POST with a method override.
44
+ @verb = :post if verb == :get && @json && opts[:params]
45
+ @name = -((opts[:name] || "#{verb.upcase} #{path}").to_s)
46
+ @expect = [*(opts[:expect] || (verb == :get ? 200 : WRITE_EXPECT))].freeze
47
+ @kind = @json ? :json : verb == :get ? :html : :form
48
+ @csrf = opts.key?(:csrf) && !opts[:csrf] ? "false" : @json || @xhr ? "header" : "param"
49
+ @jobs = opts[:jobs] ? true : false
50
+ @signed_in = opts.fetch(:signed_in, true) ? true : false
51
+ @headers = Workloads.rack_headers(opts[:headers]).merge(Workloads.stringify(opts[:env] || {}))
52
+ @headers = { "HTTP_ACCEPT" => JSON_TYPE, "CONTENT_TYPE" => JSON_TYPE }.merge(@headers) if @json
53
+ @headers["HTTP_X_HTTP_METHOD_OVERRIDE"] = "GET" if @verb != verb
54
+ if @xhr
55
+ @headers["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"
56
+ @headers["HTTP_ACCEPT"] ||= "text/javascript, text/html, application/xml, text/xml, */*"
57
+ end
58
+ @headers.freeze
59
+ set(path, opts[:params])
60
+ if (list = opts[:alternate])
61
+ raise ArgumentError, "#{source}: alternate: takes a list of overrides (path:, params:)" unless list.is_a?(Array) && list.all?(Hash)
62
+ @alternate = list.map { |o| copy(o) }.freeze
63
+ end
64
+ freeze
65
+ end
66
+
67
+ def at(n)
68
+ if @alternate then @alternate[n % @alternate.size - 1]
69
+ elsif @block then copy(@scope.instance_exec(n, &@block))
70
+ else self
71
+ end
72
+ end
73
+
74
+ # The declaration only: a block's overrides are not known until it runs
75
+ # (lowrail-profile --workloads lists the variants it measured).
76
+ def to_h
77
+ h = { "name" => name, "method" => verb.to_s, "path" => path, "params_sha256" => Workloads.digest(params),
78
+ "body_sha256" => Workloads.digest(body), "headers" => headers.keys.sort,
79
+ "headers_sha256" => Workloads.digest(headers.sort.map { |k, v| [k, Workloads.json_value?(v) ? v : Workloads.class_of(v).name] }),
80
+ "expect" => expect, "kind" => kind.to_s }
81
+ # env: objects other than JSON values have no identity a digest can certify.
82
+ uncertified = headers.reject { Workloads.json_value?(_2) }.keys.sort
83
+ h["headers_uncertified"] = uncertified unless uncertified.empty?
84
+ h["xhr"] = true if @xhr
85
+ h["as"] = "json" if @json
86
+ h["jobs"] = true if jobs
87
+ h["signed_in"] = false unless signed_in
88
+ h["csrf"] = false if csrf == "false"
89
+ h["alternate"] = alternate.map(&:variant) if alternate
90
+ h["block"] = source if block
91
+ h
92
+ end
93
+
94
+ def variant = { "path" => path, "params_sha256" => Workloads.digest(params), "body_sha256" => Workloads.digest(body) }
95
+
96
+ protected
97
+
98
+ # params as rack sends them (string keys), or for as: :json the body.
99
+ def set(path, params)
100
+ raise ArgumentError, "#{@source}: path must be a String starting with / (got #{path.inspect})" unless path.is_a?(String) && path.start_with?("/")
101
+ @path = -path
102
+ # Kept apart from the body, so an override of the path alone keeps them.
103
+ @declared = Workloads.stringify(params || {})
104
+ @params, @body = @json && @verb != :get ? [{}.freeze, (-@declared.to_json unless @declared.empty?)] : [@declared, nil]
105
+ end
106
+
107
+ private
108
+
109
+ def copy(overrides)
110
+ raise ArgumentError, "#{@source}: an override is a Hash of path: and params: (got #{overrides.inspect})" unless overrides.is_a?(Hash)
111
+ unknown = overrides.keys - %i[path params]
112
+ raise ArgumentError, "#{@source}: an override sets only path: and params: (got #{unknown.join(", ")})" if unknown.any?
113
+ dup.tap { _1.set(overrides.fetch(:path, @path), overrides.key?(:params) ? overrides[:params] : @declared) }.freeze
114
+ end
115
+ end
116
+
117
+ Mail = Struct.new(:name, :block, :source)
118
+ Job = Struct.new(:name, :block, :source)
119
+
120
+ # The file's evaluation context. Methods a file may call are public; route
121
+ # helpers come from the app's routes.
122
+ class Definition
123
+ attr_reader :file, :requests, :mails, :jobs, :skipped_jobs, :sign_in_spec, :csrf_page, :setups
124
+
125
+ def initialize(file)
126
+ @file = file
127
+ @requests, @mails, @jobs, @skipped_jobs, @setups = [], [], [], [], []
128
+ @lets = {}
129
+ singleton_class.include(Rails.application.routes.url_helpers) if defined?(Rails.application.routes)
130
+ end
131
+
132
+ VERBS.each do |verb|
133
+ define_method(verb) do |path, **opts, &block|
134
+ @requests << Request.new(verb, path, opts, block, self, Workloads.caller_source(caller_locations(1, 1)))
135
+ nil
136
+ end
137
+ end
138
+
139
+ # Runs at once, in file order: resets and lookups the requests below need.
140
+ def setup(&block)
141
+ @setups << Workloads.source(block)
142
+ instance_exec(&block)
143
+ end
144
+
145
+ # A value computed on first use, then kept: a record the requests create
146
+ # before a mail or job uses it.
147
+ def let(name, &block)
148
+ lets = @lets
149
+ define_singleton_method(name) { lets.fetch(name) { lets[name] = instance_exec(&block) } }
150
+ end
151
+
152
+ # Sign the measuring client in once: GET form (default: path) for its
153
+ # token, then this request; or set a cookie (signed: true for a signed one).
154
+ def sign_in(path = nil, params: {}, method: :post, form: path, expect: [302, 303], cookie: nil)
155
+ raise ArgumentError, "sign_in takes a path or cookie:" unless path || cookie
156
+ @sign_in_spec = Workloads.deep_freeze({ path: path && -path, params: Workloads.stringify(params), method: method.to_sym,
157
+ form: form && -form, expect: [*expect], cookie: cookie && Workloads.stringify(cookie.to_h).transform_keys(&:to_sym) })
158
+ end
159
+
160
+ # The page whose CSRF token the writes send (default: the first HTML GET).
161
+ def csrf_from(path) = @csrf_page = -path
162
+
163
+ # A mail delivered with deliver_now; the block returns the message.
164
+ def mail(name = nil, &block)
165
+ source = Workloads.source(block)
166
+ @mails << Mail.new(name || Workloads.guess(block, /\b([A-Z]\w*(?:::[A-Z]\w*)*Mailer)\.(\w+)/) { "deliver #{_1}##{_2}" } || "mail at #{source}", block, source)
167
+ end
168
+
169
+ # A job performed as a queue would run it; the block returns the job (MyJob.new(args)).
170
+ def job(name = nil, &block)
171
+ source = Workloads.source(block)
172
+ @jobs << Job.new(name || Workloads.guess(block, /\b([A-Z]\w*(?:::[A-Z]\w*)*)\.new\b/) { "perform #{_1}" } || "job at #{source}", block, source)
173
+ end
174
+
175
+ # Jobs that requests with jobs: true enqueue, left out by class name.
176
+ def skip_jobs(*names) = @skipped_jobs.concat(names.flatten.map(&:to_s))
177
+
178
+ def csrf_page_or_default = @csrf_page || requests.find { _1.verb == :get && _1.kind == :html }&.path
179
+
180
+ def manifest
181
+ require "json"
182
+ require "digest"
183
+ @manifest ||= Workloads.deep_freeze(
184
+ "format" => 2, "file" => file, "sha256" => (Digest::SHA256.file(file).hexdigest if File.exist?(file)),
185
+ "setup" => setups, "lets" => @lets.keys.map(&:to_s).sort, "sign_in" => sign_in_manifest,
186
+ "csrf_from" => csrf_page_or_default, "requests" => requests.map(&:to_h),
187
+ "mails" => mails.map { { "name" => _1.name, "block" => _1.source } },
188
+ "jobs" => jobs.map { { "name" => _1.name, "block" => _1.source } }, "skip_jobs" => skipped_jobs)
189
+ end
190
+
191
+ private
192
+
193
+ # Digests, not values: the manifest is written next to reports.
194
+ def sign_in_manifest
195
+ s = sign_in_spec or return
196
+ if (cookie = s[:cookie])
197
+ { "cookie" => cookie[:name].to_s, "signed" => cookie[:signed] ? true : false, "value_sha256" => Workloads.digest(cookie[:value].to_s) }
198
+ else
199
+ { "method" => s[:method].to_s, "path" => s[:path], "form" => s[:form], "expect" => s[:expect], "params_sha256" => Workloads.digest(s[:params]) }
200
+ end
201
+ end
202
+ end
203
+
204
+ # The request policy both clients follow, so script/census app and
205
+ # lowrail-profile --workloads send the same requests: sign-in, the CSRF
206
+ # token (from csrf_from's page, as a param or X-CSRF-Token header), and
207
+ # each request's turn. A client answers request(verb, path, params:,
208
+ # headers:, body:, expect:) with a response that has #body (raising when
209
+ # the status is not expected), and cookie(name, value).
210
+ class Replayer
211
+ def initialize(definition, signed_in, anonymous)
212
+ @definition, @signed_in, @anonymous = definition, signed_in, anonymous
213
+ @tokens = {}.compare_by_identity
214
+ @turns = {}.compare_by_identity
215
+ end
216
+
217
+ def sign_in
218
+ s = @definition.sign_in_spec or return
219
+ if (cookie = s[:cookie])
220
+ name, value = cookie.fetch(:name).to_s, cookie.fetch(:value).to_s
221
+ return @signed_in.cookie(*(cookie[:signed] ? Workloads.signed_cookie(name, value) : [name, value]))
222
+ end
223
+ token = Workloads.csrf_token(@signed_in.request(:get, s[:form]).body)
224
+ params = token ? s[:params].merge("authenticity_token" => token) : s[:params]
225
+ @signed_in.request(s[:method], s[:path], params: params, headers: token ? { "HTTP_X_CSRF_TOKEN" => token } : {}, expect: s[:expect])
226
+ end
227
+
228
+ # The request's next turn; returns the request as sent (path and params).
229
+ def perform(r)
230
+ client = r.signed_in ? @signed_in : @anonymous
231
+ spec = r.at(@turns[r] = @turns.fetch(r, 0) + 1)
232
+ headers, params = spec.headers, spec.params
233
+ if r.verb != :get && r.csrf != "false" && (token = token(client))
234
+ headers = headers.merge("HTTP_X_CSRF_TOKEN" => token) if r.csrf == "header"
235
+ params = params.merge("authenticity_token" => token) if r.csrf == "param" && !spec.body
236
+ end
237
+ client.request(r.verb, spec.path, params: params, headers: headers, expect: r.expect, body: spec.body)
238
+ spec
239
+ end
240
+
241
+ private
242
+
243
+ def token(client)
244
+ @tokens.fetch(client) do
245
+ page = @definition.csrf_page_or_default
246
+ @tokens[client] = page && Workloads.csrf_token(client.request(:get, page).body)
247
+ end
248
+ end
249
+ end
250
+
251
+ # lowrail-profile --workloads' client: Rack::MockRequest through the app's
252
+ # full middleware stack with BROWSER's headers, keeping the cookies earlier
253
+ # responses set as census 4's Rack::Test session keeps them: by name and
254
+ # Path (default: the request's directory), sent to paths under it, dropped
255
+ # once their Expires has passed. Domain, Secure and Max-Age are not modeled
256
+ # (Rack::Test ignores Max-Age; there is one host). Requires rack/mock.
257
+ class MockClient
258
+ Response = Struct.new(:status, :body)
259
+ Cookie = Struct.new(:name, :value, :path, :expires)
260
+
261
+ def initialize(app, host)
262
+ @app, @host, @cookies = app, host, []
263
+ @headers = BROWSER.merge("HTTP_HOST" => host, "HTTP_ORIGIN" => "https://#{host}").freeze
264
+ end
265
+
266
+ def cookie(name, value) = store(Cookie.new(name, value, "/", nil))
267
+
268
+ # The Rack env #request sends.
269
+ def env(verb, path, params: {}, headers: {}, body: nil)
270
+ opts = { method: verb.to_s.upcase, **@headers, **headers }
271
+ request_path = path[/\A[^?#]*/]
272
+ now = Time.now
273
+ sent = @cookies.select { !(_1.expires && _1.expires < now) && request_path.start_with?(_1.path) }
274
+ opts["HTTP_COOKIE"] = sent.map { "#{_1.name}=#{_1.value}" }.join("; ") unless sent.empty?
275
+ # As Rack::Test: a write without a body is still an empty form.
276
+ if body then opts[:input] = body
277
+ # A copy: Rack::MockRequest merges a GET's query into the Hash it gets.
278
+ elsif verb != :get || !params.empty? then opts[:params] = params.dup
279
+ end
280
+ Rack::MockRequest.env_for("https://#{@host}#{path}", opts)
281
+ end
282
+
283
+ def request(verb, path, params: {}, headers: {}, expect: [200], body: nil)
284
+ request_path = path[/\A[^?#]*/]
285
+ status, response_headers, response = @app.call(env(verb, path, params: params, headers: headers, body: body))
286
+ text = +""
287
+ begin
288
+ response.each { text << _1 }
289
+ ensure
290
+ response.close if response.respond_to?(:close)
291
+ end
292
+ Array(response_headers["set-cookie"]).flat_map { _1.split("\n") }.each do |line|
293
+ pair, *attributes = line.split(/; */)
294
+ name, value = pair.split("=", 2)
295
+ options = attributes.to_h { |a| k, v = a.split("=", 2); [k.downcase, v] }
296
+ # Rack::Test's normalization: the first comma-separated path, stripped.
297
+ cookie_path = options["path"] ? (options["path"].split(",").first || "/").strip : request_path.sub(%r{/[^/]*\z}, "")
298
+ expires = (require "time"; Time.parse(options["expires"]) rescue nil) if options["expires"]
299
+ store(Cookie.new(name, value.to_s, cookie_path.empty? ? "/" : cookie_path, expires))
300
+ end
301
+ raise "#{verb.upcase} #{path} returned #{status} (expected #{Array(expect).join(" or ")})" unless Array(expect).include?(status)
302
+ raise "#{verb.upcase} #{path}: empty body" if status == 200 && text.empty? && verb == :get
303
+ Response.new(status, text)
304
+ end
305
+
306
+ private
307
+
308
+ def store(cookie)
309
+ @cookies.reject! { _1.name.downcase == cookie.name.downcase && _1.path == cookie.path }
310
+ @cookies << cookie
311
+ @cookies.sort_by! { [_1.name, _1.path] }
312
+ end
313
+ end
314
+
315
+ module_function
316
+
317
+ def load(file)
318
+ definition = Definition.new(file)
319
+ definition.instance_eval(File.read(file), file, 1)
320
+ names = definition.requests.map(&:name) + definition.mails.map(&:name) + definition.jobs.map(&:name)
321
+ dups = names.select { names.count(_1) > 1 }.uniq
322
+ raise ArgumentError, "#{file}: duplicate names #{dups.join(", ")}; give one of each a name:" if dups.any?
323
+ definition.requests.freeze
324
+ definition
325
+ end
326
+
327
+ def rack_headers(headers)
328
+ (headers || {}).to_h do |k, v|
329
+ key = k.to_s.upcase.tr("-", "_")
330
+ [%w[CONTENT_TYPE CONTENT_LENGTH].include?(key) || key.start_with?("HTTP_") ? key : "HTTP_#{key}", -v.to_s]
331
+ end
332
+ end
333
+
334
+ # A frozen copy with string keys; strings are copied, other objects kept.
335
+ def stringify(value)
336
+ case value
337
+ when Hash then value.to_h { |k, v| [-k.to_s, stringify(v)] }.freeze
338
+ when Array then value.map { stringify(_1) }.freeze
339
+ when Symbol then -value.to_s
340
+ when String then -value
341
+ else value
342
+ end
343
+ end
344
+
345
+ def digest(value)
346
+ return if value.nil? || value.respond_to?(:empty?) && value.empty?
347
+ Digest::SHA256.hexdigest(value.is_a?(String) ? value : JSON.generate(value))[0, 16]
348
+ end
349
+
350
+ def deep_freeze(value)
351
+ case value
352
+ when Hash then value.each_value { deep_freeze(_1) }.freeze
353
+ when Array then value.each { deep_freeze(_1) }.freeze
354
+ else value.freeze
355
+ end
356
+ end
357
+
358
+ KERNEL_CLASS = Kernel.instance_method(:class)
359
+ def class_of(value) = KERNEL_CLASS.bind_call(value)
360
+
361
+ def json_value?(value)
362
+ case value
363
+ when String, Integer, true, false, nil then true
364
+ when Float then value.finite?
365
+ when Array then value.all? { json_value?(_1) }
366
+ when Hash then value.all? { |k, v| String === k && json_value?(v) }
367
+ else false
368
+ end
369
+ end
370
+
371
+ def source(block) = block.source_location.then { "#{File.basename(_1)}:#{_2}" }
372
+ def caller_source(locations) = locations.first.then { "#{File.basename(_1.path)}:#{_1.lineno}" }
373
+
374
+ # A default name from the block's first source line.
375
+ def guess(block, pattern)
376
+ file, line = block.source_location
377
+ text = File.exist?(file) ? File.readlines(file)[line - 1].to_s : ""
378
+ (m = text.match(pattern)) && yield(*m.captures)
379
+ end
380
+
381
+ # The token a page gives a form: its csrf-token meta tag, or a form's field.
382
+ def csrf_token(body)
383
+ body[/<meta name="csrf-token" content="([^"]+)"/, 1] || body[/name="authenticity_token" value="([^"]+)"/, 1]
384
+ end
385
+
386
+ # A cookie signed with the app's own key generator, as the app signs it.
387
+ def signed_cookie(name, value)
388
+ require "action_dispatch/testing/test_request"
389
+ request = ActionDispatch::TestRequest.create
390
+ request.env.merge!(Rails.application.env_config)
391
+ request.cookie_jar.signed[name.to_sym] = value
392
+ request.cookie_jar.to_header.split("=", 2)
393
+ end
394
+
395
+ # Recorded request shapes (lowrail-profile --record) as render entries,
396
+ # most frequent first. Only a shape that replays as recorded is enabled:
397
+ # a GET whose path parts are records the file can look up and whose params
398
+ # were kept whole and unfiltered. A write repeats one test's params, so it
399
+ # must not accumulate state from run to run; it and every other shape
400
+ # start commented out, with the reason.
401
+ def recorded(shapes, limit)
402
+ shapes.sort_by { [-_1["count"], _1["verb"] == "get" ? 0 : 1, _1["template"], _1["format"].to_s] }.first(limit).map do |s|
403
+ format = s["format"]
404
+ name = "#{s["verb"].upcase} #{s["template"]}#{".#{format}" if format}#{" (#{s["accept"]})" if s["accept"]}"
405
+ reasons = []
406
+ reasons << "a write: make it repeatable, then uncomment" if s["verb"] != "get"
407
+ reasons << "the app's filter_parameters is not only names and patterns (a Proc), or could not be applied, so no request values were kept" if s["unfiltered"]
408
+ reasons << "values the app filters are #{FILTERED}: fill them in" if s["filtered"]
409
+ reasons << "part of the request was not kept (long or binary values, uploads, optional path parts or a write's query)" if s["lossy"]
410
+ missing = s["parts"].reject(&:last).map { ":#{_1[0]}" }
411
+ reasons << "needs #{missing.join(", ")}: the path is the one seen" if missing.any?
412
+ { name: name, verb: s["verb"], route: s["route"], parts: s["parts"], template: s["template"], seen: s["seen"],
413
+ format: format, json: s["json"], xhr: s["xhr"], accept: s["accept"], params: s["params"], commented: reasons.any?,
414
+ note: "#{s["count"]} #{s["count"] == 1 ? "request" : "requests"}#{" (#{reasons.join("; ")})" if reasons.any?}" }
415
+ end
416
+ end
417
+
418
+ # A starter file from request shapes: name:, verb:, route: (helper name or
419
+ # nil), parts: [[part, "Model" or nil]], template:, path: or seen: (the
420
+ # path an unresolved shape was seen with), format:, json:, xhr:, accept:,
421
+ # params:, note:, commented:. Each record a path needs is the model's first
422
+ # row, looked up when the file is evaluated (commented out when only
423
+ # commented-out requests use it). Every value from a request is a quoted
424
+ # literal, never Ruby syntax.
425
+ def render(entries, intro)
426
+ var = ->(model) { model.gsub("::", "_").gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase }
427
+ entries = entries.map do |e|
428
+ parts = e[:parts].map { |part, model| [part.to_s, (model if model.is_a?(String) && model.match?(CONSTANT))] }
429
+ e.merge(parts: parts, resolved: parts.all?(&:last))
430
+ end
431
+ models = ->(list) { list.flat_map { |e| e[:parts].map(&:last) }.compact.uniq }
432
+ live = models.(entries.select { _1[:resolved] && !_1[:commented] })
433
+ out = intro.lines.map { "# #{_1.chomp}".rstrip + "\n" }.join
434
+ bindings = models.(entries).map { "#{"# " unless live.include?(_1)}#{var.(_1)} = #{_1}.first!\n" }
435
+ out << "\n" << bindings.join unless bindings.empty?
436
+ spaced = true
437
+ entries.each do |e|
438
+ target = if e[:resolved] && e[:route].is_a?(String) && e[:route].match?(HELPER)
439
+ args = e[:parts].map { var.(_2) }
440
+ args << "format: #{e[:format].to_s.inspect}" if e[:format]
441
+ "#{e[:route]}_path#{"(#{args.join(", ")})" unless args.empty?}"
442
+ elsif e[:resolved]
443
+ path_literal(e[:template], e[:parts].to_h { |part, model| [part, [:ruby, "#{var.(model)}.to_param"]] }, e[:format])
444
+ elsif e[:path]
445
+ e[:path].to_s.inspect
446
+ else
447
+ path_literal(e[:template], (e[:seen] || {}).to_h { |part, value| [part.to_s, [:text, value.to_s]] }, e[:format])
448
+ end
449
+ line = +"#{e[:verb]} #{target}, name: #{e[:name].to_s.inspect}"
450
+ line << ", as: :json" if e[:json]
451
+ line << ", xhr: true" if e[:xhr]
452
+ line << ", headers: { \"Accept\" => #{e[:accept].to_s.inspect} }" if e[:accept]
453
+ line << ", params: #{literal(e[:params])}" if e[:params].is_a?(Hash) && !e[:params].empty?
454
+ commented = e[:commented] || !e[:resolved]
455
+ noted = e[:note] || !e[:resolved]
456
+ out << "\n" if noted || spaced
457
+ spaced = noted
458
+ Array(e[:note]).each { out << "# #{_1}\n" }
459
+ out << "# needs #{e[:parts].reject(&:last).map { ":#{_1[0]}" }.join(", ")}: the path is the one seen\n" if !e[:resolved] && !e[:note]
460
+ out << (commented ? "# " : "") << line << "\n"
461
+ end
462
+ out
463
+ end
464
+
465
+ # A double-quoted Ruby string for a route template: its text escaped,
466
+ # each :part a value ([:ruby, expression] interpolated, [:text, string]
467
+ # escaped), optional segments left out, then the format.
468
+ # A recorded value as Ruby, the same on every Ruby (Hash#inspect changed in 3.4).
469
+ def literal(value)
470
+ case value
471
+ when Hash then "{#{value.map { |k, v| "#{literal(k)} => #{literal(v)}" }.join(", ")}}"
472
+ when Array then "[#{value.map { literal(_1) }.join(", ")}]"
473
+ else value.inspect
474
+ end
475
+ end
476
+
477
+ def path_literal(template, values, format)
478
+ text = ->(s) { s.inspect[1..-2] }
479
+ body = template.to_s.gsub(/\([^()]*\)/, "").split(/(:[a-z_]\w*)/).map do |piece|
480
+ kind, value = values[piece.delete_prefix(":")] if piece.start_with?(":")
481
+ if kind == :ruby then "\#{#{value}}"
482
+ elsif kind == :text then text.(value)
483
+ else text.(piece)
484
+ end
485
+ end.join
486
+ %("#{body}#{text.(".#{format}") if format}")
487
+ end
488
+ end
489
+ end