nukadoko 0.1.0 → 0.2.0

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.
Files changed (147) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +291 -0
  3. data/README.ja.md +58 -5
  4. data/README.md +15 -3
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +274 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claims.rb +407 -30
  15. data/lib/nukadoko/cli.rb +802 -19
  16. data/lib/nukadoko/codes.json +942 -0
  17. data/lib/nukadoko/codes.rb +19 -0
  18. data/lib/nukadoko/command.rb +214 -12
  19. data/lib/nukadoko/criteria.rb +172 -0
  20. data/lib/nukadoko/definition.rb +33 -41
  21. data/lib/nukadoko/env_check.rb +90 -0
  22. data/lib/nukadoko/features.rb +80 -10
  23. data/lib/nukadoko/fixtures.rb +296 -10
  24. data/lib/nukadoko/http_recording.rb +68 -0
  25. data/lib/nukadoko/init.rb +130 -0
  26. data/lib/nukadoko/judge.rb +221 -0
  27. data/lib/nukadoko/judgment_file.rb +78 -0
  28. data/lib/nukadoko/judgments.rb +256 -0
  29. data/lib/nukadoko/literal.rb +129 -0
  30. data/lib/nukadoko/measured.rb +105 -0
  31. data/lib/nukadoko/order.rb +84 -0
  32. data/lib/nukadoko/parts.rb +42 -21
  33. data/lib/nukadoko/pattern.rb +11 -1
  34. data/lib/nukadoko/poll.rb +17 -6
  35. data/lib/nukadoko/program.rb +105 -17
  36. data/lib/nukadoko/project_fixtures.rb +17 -2
  37. data/lib/nukadoko/report_allure.rb +751 -0
  38. data/lib/nukadoko/report_messages.rb +167 -0
  39. data/lib/nukadoko/report_run.rb +169 -0
  40. data/lib/nukadoko/run.rb +865 -88
  41. data/lib/nukadoko/run_record.rb +532 -0
  42. data/lib/nukadoko/scaffold.rb +1015 -0
  43. data/lib/nukadoko/schema.rb +61 -4
  44. data/lib/nukadoko/secrets.rb +359 -0
  45. data/lib/nukadoko/selection.rb +163 -0
  46. data/lib/nukadoko/signature.rb +4 -1
  47. data/lib/nukadoko/skill.rb +36 -0
  48. data/lib/nukadoko/step.rb +62 -21
  49. data/lib/nukadoko/summary.rb +662 -0
  50. data/lib/nukadoko/table.rb +34 -2
  51. data/lib/nukadoko/text_fit.rb +179 -0
  52. data/lib/nukadoko/trace.rb +244 -0
  53. data/lib/nukadoko/trace_actions.rb +116 -0
  54. data/lib/nukadoko/tree_passes.rb +119 -0
  55. data/lib/nukadoko/verdict.rb +128 -0
  56. data/lib/nukadoko/version.rb +2 -1
  57. data/lib/nukadoko/vocabulary.rb +6 -0
  58. data/lib/nukadoko/walk.rb +305 -0
  59. data/lib/nukadoko/walk_files.rb +473 -0
  60. data/lib/nukadoko/walk_step.rb +149 -0
  61. data/lib/nukadoko.rb +36 -0
  62. data/llms.txt +296 -0
  63. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  64. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  65. data/sig/generated/nukadoko/base.rbs +136 -0
  66. data/sig/generated/nukadoko/check.rbs +255 -0
  67. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  68. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  69. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  70. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  71. data/sig/generated/nukadoko/claims.rbs +165 -0
  72. data/sig/generated/nukadoko/cli.rbs +182 -0
  73. data/sig/generated/nukadoko/codes.rbs +16 -0
  74. data/sig/generated/nukadoko/command.rbs +109 -0
  75. data/sig/generated/nukadoko/criteria.rbs +83 -0
  76. data/sig/generated/nukadoko/definition.rbs +30 -0
  77. data/sig/generated/nukadoko/env_check.rbs +38 -0
  78. data/sig/generated/nukadoko/features.rbs +101 -0
  79. data/sig/generated/nukadoko/fixtures.rbs +152 -0
  80. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  81. data/sig/generated/nukadoko/init.rbs +66 -0
  82. data/sig/generated/nukadoko/judge.rbs +64 -0
  83. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  84. data/sig/generated/nukadoko/judgments.rbs +120 -0
  85. data/sig/generated/nukadoko/literal.rbs +71 -0
  86. data/sig/generated/nukadoko/measured.rbs +42 -0
  87. data/sig/generated/nukadoko/order.rbs +54 -0
  88. data/sig/generated/nukadoko/parts.rbs +35 -0
  89. data/sig/generated/nukadoko/pattern.rbs +28 -0
  90. data/sig/generated/nukadoko/poll.rbs +40 -0
  91. data/sig/generated/nukadoko/program.rbs +101 -0
  92. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  93. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  94. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  95. data/sig/generated/nukadoko/report_run.rbs +102 -0
  96. data/sig/generated/nukadoko/run.rbs +257 -0
  97. data/sig/generated/nukadoko/run_record.rbs +174 -0
  98. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  99. data/sig/generated/nukadoko/schema.rbs +137 -0
  100. data/sig/generated/nukadoko/secrets.rbs +157 -0
  101. data/sig/generated/nukadoko/selection.rbs +73 -0
  102. data/sig/generated/nukadoko/signature.rbs +17 -0
  103. data/sig/generated/nukadoko/skill.rbs +20 -0
  104. data/sig/generated/nukadoko/step.rbs +115 -0
  105. data/sig/generated/nukadoko/summary.rbs +204 -0
  106. data/sig/generated/nukadoko/table.rbs +43 -0
  107. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  108. data/sig/generated/nukadoko/trace.rbs +127 -0
  109. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  110. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  111. data/sig/generated/nukadoko/verdict.rbs +56 -0
  112. data/sig/generated/nukadoko/version.rbs +5 -0
  113. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  114. data/sig/generated/nukadoko/walk.rbs +139 -0
  115. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  116. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  117. data/sig/generated/nukadoko.rbs +15 -0
  118. data/sig/nukadoko.rbs +5 -48
  119. data/skills/nukadoko/SKILL.md +120 -0
  120. data/skills/nukadoko/references/checking-steps.md +200 -0
  121. data/skills/nukadoko/references/diagnosing.md +200 -0
  122. data/skills/nukadoko/references/done.md +99 -0
  123. data/skills/nukadoko/references/evidence.md +124 -0
  124. data/skills/nukadoko/references/examples/cli.md +230 -0
  125. data/skills/nukadoko/references/examples/http-api.md +339 -0
  126. data/skills/nukadoko/references/examples/workflow.md +173 -0
  127. data/skills/nukadoko/references/exploring.md +184 -0
  128. data/skills/nukadoko/references/fixtures.md +198 -0
  129. data/skills/nukadoko/references/from-prose.md +51 -0
  130. data/skills/nukadoko/references/judgments.md +95 -0
  131. data/skills/nukadoko/references/maintenance.md +97 -0
  132. data/skills/nukadoko/references/merge-risk.md +74 -0
  133. data/skills/nukadoko/references/parts.md +152 -0
  134. data/skills/nukadoko/references/perturbed-worlds.md +107 -0
  135. data/skills/nukadoko/references/program.md +200 -0
  136. data/skills/nukadoko/references/reviewing.md +200 -0
  137. data/skills/nukadoko/references/running.md +200 -0
  138. data/skills/nukadoko/references/scenario-rules.md +188 -0
  139. data/skills/nukadoko/references/states.md +66 -0
  140. data/skills/nukadoko/references/step-files.md +200 -0
  141. data/skills/nukadoko/references/verdicts.md +200 -0
  142. data/skills/nukadoko/references/writing-steps.md +200 -0
  143. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  144. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  145. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  146. data/skills/nukadoko-verification/SKILL.md +263 -0
  147. metadata +121 -1
@@ -1,4 +1,5 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  require "gherkin"
4
5
 
@@ -8,18 +9,38 @@ require "gherkin"
8
9
  module Nukadoko
9
10
  module Engine
10
11
  # `keyword_line` is the Scenario keyword's own line, the same for every
11
- # row of an outline. A step from a Background has `background` set.
12
- Scenario = Data.define(:uri, :line, :keyword_line, :name, :tags, :steps)
12
+ # row of an outline, and `outline_name` the name as written, before a
13
+ # row fills it. A step from a Background has `background` set.
14
+ Scenario = Data.define(:uri, :line, :keyword_line, :name, :tags, :steps, :tag_lines, :columns, :outline_name, :serial)
13
15
  PickleStep = Data.define(:text, :line, :kind, :table, :doc_string, :background)
16
+ # What makes a file, or a part of one, run nothing: a file that does
17
+ # not parse, or an outline with no row to run. `line` is nil for a file.
18
+ FeatureProblem = Data.define(:code, :uri, :line, :message)
19
+
20
+ # A directory is every .feature file under it; a list is those files.
21
+ # What runs nothing goes into `problems`, for nuka check to report.
22
+ #: (String | Array[String], ?problems: Array[FeatureProblem]) -> Array[Scenario]
23
+ def self.load_features(dir_or_paths, problems: [])
24
+ paths = dir_or_paths.is_a?(Array) ? dir_or_paths : Dir.glob(File.join(dir_or_paths, "**/*.feature")).sort
25
+ return [] if paths.empty?
14
26
 
15
- def self.load_features(dir)
16
- paths = Dir.glob(File.join(dir, "**/*.feature")).sort
17
27
  lines = {}
18
28
  background = {}
29
+ headers = {}
30
+ names = {}
31
+ serial = {}
19
32
  scenarios = []
33
+ parse_errors = Hash.new { |h, k| h[k] = [] }
20
34
  Gherkin.from_paths(paths, include_source: false, include_gherkin_document: true, include_pickles: true).each do |envelope|
21
- if (doc = envelope.gherkin_document)
22
- collect_lines(doc.feature, lines, background) if doc.feature
35
+ if (error = envelope.parse_error)
36
+ parse_errors[error.source.uri] << error.message
37
+ elsif (doc = envelope.gherkin_document)
38
+ if doc.feature
39
+ collect_lines(doc.feature, lines, background, headers, names)
40
+ serial[doc.uri] = doc.feature.tags.any? { _1.name == SERIAL_TAG }
41
+ problems.concat(serial_tags_on_scenarios(doc))
42
+ problems.concat(outlines_that_do_not_run(doc))
43
+ end
23
44
  elsif (pickle = envelope.pickle)
24
45
  steps = pickle.steps.map do |step|
25
46
  table = step.argument&.data_table&.rows&.map { |row| row.cells.map(&:value) }
@@ -27,23 +48,72 @@ module Nukadoko
27
48
  background.key?(step.ast_node_ids.first))
28
49
  end
29
50
  scenarios << Scenario.new(pickle.uri, lines.fetch(pickle.ast_node_ids.last), lines.fetch(pickle.ast_node_ids.first),
30
- pickle.name, pickle.tags.map(&:name), steps)
51
+ pickle.name, pickle.tags.map(&:name), steps,
52
+ pickle.tags.to_h { [_1.name, lines[_1.ast_node_id]] }, headers.fetch(pickle.ast_node_ids.last, []),
53
+ names.fetch(pickle.ast_node_ids.first, pickle.name), serial.fetch(pickle.uri, false))
31
54
  end
32
55
  end
56
+ # One finding per file, every error in the parser's words and order.
57
+ parse_errors.each { |uri, messages| problems << FeatureProblem.new("feature-parse-error", uri, nil, "Parser errors:\n#{messages.join("\n")}") }
33
58
  scenarios
34
59
  end
35
60
 
36
- def self.collect_lines(node, lines, background)
61
+ # The tag on a Feature line that runs the file while no other file runs.
62
+ SERIAL_TAG = "@nukadoko:serial"
63
+
64
+ # nuka run --concurrency reads the serial tag on the Feature line only,
65
+ # so on a scenario it would read as a rule in force while doing nothing.
66
+ #: (untyped) -> Array[FeatureProblem]
67
+ def self.serial_tags_on_scenarios(doc)
68
+ scenarios = doc.feature.children.flat_map { |child| child.rule ? child.rule.children.filter_map(&:scenario) : [child.scenario].compact }
69
+ scenarios.select { |scenario| scenario.tags.any? { _1.name == SERIAL_TAG } }.map do |scenario|
70
+ FeatureProblem.new("serial-tag-on-scenario", doc.uri, scenario.location.line,
71
+ %(@nukadoko:serial on scenario "#{scenario.name}" has no effect: nuka run --concurrency reads @nukadoko:serial only from the Feature line. Move the tag there.))
72
+ end
73
+ end
74
+
75
+ # An outline with no Examples runs its placeholder text as written, and
76
+ # an Examples table with no rows leaves the outline out of the run.
77
+ #: (untyped) -> Array[FeatureProblem]
78
+ def self.outlines_that_do_not_run(doc)
79
+ outline = Gherkin::Dialect.for(doc.feature.language).scenario_outline_keywords
80
+ scenarios = doc.feature.children.flat_map { |child| child.rule ? child.rule.children.filter_map(&:scenario) : [child.scenario].compact }
81
+ scenarios.flat_map do |scenario|
82
+ if scenario.examples.empty?
83
+ next [] unless outline.include?(scenario.keyword)
84
+
85
+ next [FeatureProblem.new("outline-does-not-run", doc.uri, scenario.location.line,
86
+ %(Scenario outline "#{scenario.name}" has no Examples table, so the placeholder text runs as written. Add one Examples row for each boundary that must run.))]
87
+ end
88
+ scenario.examples.select { _1.table_body.empty? }.map do |block|
89
+ FeatureProblem.new("outline-does-not-run", doc.uri, block.location.line,
90
+ %(Scenario "#{scenario.name}" has an Examples table with no rows, so the scenario is left out of the run. Add a row, or remove the table.))
91
+ end
92
+ end
93
+ end
94
+
95
+ #: (untyped, Hash[String, Integer], Hash[String, bool], Hash[String, Array[String]], Hash[String, String]) -> void
96
+ def self.collect_lines(node, lines, background, headers, names)
97
+ node.tags&.each { lines[_1.id] = _1.location.line }
37
98
  node.children.each do |child|
38
- next collect_lines(child.rule, lines, background) if child.rule
99
+ next collect_lines(child.rule, lines, background, headers, names) if child.rule
39
100
 
40
101
  scenario = child.scenario || child.background
41
102
  next unless scenario
42
103
 
104
+ names[scenario.id] = scenario.name if child.scenario
43
105
  lines[scenario.id] = scenario.location.line if child.scenario
44
106
  scenario.steps.each { |step| lines[step.id] = step.location.line }
45
107
  child.background&.steps&.each { |step| background[step.id] = true }
46
- child.scenario&.examples&.each { |examples| examples.table_body.each { |row| lines[row.id] = row.location.line } }
108
+ child.scenario&.tags&.each { lines[_1.id] = _1.location.line }
109
+ child.scenario&.examples&.each do |examples|
110
+ examples.tags.each { lines[_1.id] = _1.location.line }
111
+ columns = examples.table_header&.cells&.map(&:value) || []
112
+ examples.table_body.each do |row|
113
+ lines[row.id] = row.location.line
114
+ headers[row.id] = columns
115
+ end
116
+ end
47
117
  end
48
118
  end
49
119
  end
@@ -1,26 +1,57 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  require "net/http"
4
5
  require "json"
6
+ require "fileutils"
7
+ require "time"
5
8
 
6
9
  # Fixtures are built by the engine, not the step, so what they record is
7
10
  # measured: every request a step sends goes through Request and lands in the
8
11
  # step's http.jsonl as it was sent and answered.
9
12
  module Nukadoko
10
13
  module Engine
11
- Response = Data.define(:status, :headers, :body) do
14
+ Response = Data.define(
15
+ :status, #: Integer
16
+ :headers, #: Hash[String, Array[String]]
17
+ :body, #: String
18
+ )
19
+
20
+ class Response
21
+ #: () -> untyped
12
22
  def json = JSON.parse(body)
23
+ #: () -> bool
13
24
  def ok? = status.between?(200, 299)
14
25
  end
15
26
 
16
27
  class Request
17
- attr_reader :log
28
+ attr_reader :log #: Array[Hash[Symbol, untyped]]
18
29
 
30
+ #: (String) -> void
19
31
  def initialize(base_url)
20
32
  @base = URI(base_url)
21
33
  @log = []
22
34
  end
23
35
 
36
+ BODY_TEXT = 16 * 1024
37
+
38
+ #: (Float) -> Integer
39
+ def self.since(started) = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
40
+
41
+ # A body as http.jsonl keeps it: its text, at most 16 KiB, and its
42
+ # size; none when there was none.
43
+ #: (Symbol, String?) -> Hash[Symbol, untyped]
44
+ def self.body(name, bytes)
45
+ return {} if bytes.nil? || bytes.empty?
46
+
47
+ raw = bytes.b
48
+ text = raw.byteslice(0, BODY_TEXT).to_s.force_encoding("UTF-8")
49
+ text = text.scrub("") if raw.bytesize > BODY_TEXT
50
+ return { name => { bytes: raw.bytesize, binary: true } } unless text.valid_encoding?
51
+
52
+ { name => { text: text, bytes: raw.bytesize, **(raw.bytesize > BODY_TEXT ? { truncated: true } : {}) } }
53
+ end
54
+
24
55
  %w[get post put patch delete].each do |verb|
25
56
  # `data:` is sent as JSON; `body:` is sent as it is, for a request
26
57
  # whose body is meant to be wrong.
@@ -33,10 +64,22 @@ module Nukadoko
33
64
  req.body = JSON.generate(data)
34
65
  end
35
66
  req.body = body if body
67
+ # The world's origin gets the step's traceparent, so the program's
68
+ # log says which step a request came from.
69
+ traceparent = req["traceparent"] ? nil : Trace.current&.stamp(uri)
70
+ req["traceparent"] = traceparent if traceparent
36
71
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
37
- res = Net::HTTP.start(uri.host, uri.port) { _1.request(req) }
38
- @log << { method: verb.upcase, url: uri.to_s, request_body: req.body, status: res.code.to_i,
39
- response_body: res.body, ms: ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round(1) }
72
+ entry = { method: verb.upcase, url: uri.to_s, **(path.to_s == uri.to_s ? {} : { declared_url: path.to_s }) }
73
+ stamp = traceparent ? { traceparent: traceparent, traceparent_sent_to: [Trace.origin(uri)] } : {}
74
+ begin
75
+ res = HttpRecording.unrecorded { Net::HTTP.start(uri.host.to_s, uri.port) { _1.request(req) } }
76
+ rescue StandardError => e
77
+ @log << entry.merge(status: 0, duration_ms: Request.since(started), via: "request", **stamp, **Request.body(:request_body, req.body),
78
+ error: e.message.lines.first.to_s.chomp)
79
+ ::Kernel.raise e
80
+ end
81
+ @log << entry.merge(status: res.code.to_i, duration_ms: Request.since(started), via: "request", **stamp,
82
+ **Request.body(:request_body, req.body), **Request.body(:response_body, res.body))
40
83
  Response.new(res.code.to_i, res.to_hash, res.body.to_s)
41
84
  end
42
85
  end
@@ -46,31 +89,274 @@ module Nukadoko
46
89
  # TypeScript engine. Requests the page sends are recorded by the engine's
47
90
  # own listener, and each step gets a trace chunk.
48
91
  class Browser
92
+ #: (String?, ?Hash[Symbol, untyped]) -> void
49
93
  def initialize(base_url, launch_options = {})
50
94
  @base_url = base_url
51
95
  @launch_options = launch_options
52
96
  end
53
97
 
98
+ #: (String, Array[Hash[Symbol, untyped]]) -> [untyped, ^() -> void]
54
99
  def page_for(step_dir, log)
55
100
  require "playwright"
56
101
  @execution ||= Playwright.create(playwright_cli_executable_path: ENV.fetch("PLAYWRIGHT_CLI", "npx playwright"))
57
102
  @browser ||= @execution.playwright.chromium.launch(**@launch_options)
58
- @context ||= @browser.new_context(baseURL: @base_url).tap { _1.tracing.start(screenshots: true, snapshots: true) }
59
- @page ||= @context.new_page
103
+ @context ||= @browser.new_context(baseURL: @base_url).tap do |context|
104
+ context.tracing.start(screenshots: true, snapshots: true)
105
+ watch_requests(context)
106
+ end
107
+ @page ||= @context.new_page.tap { stamp(_1) }
60
108
  @context.tracing.start_chunk
61
- listener = ->(req) { log << { method: req.method, url: req.url, from: "page" } }
109
+ @boundary = Trace.current
110
+ listener = ->(req) { log << { method: req.method, url: req.url, via: "page" } }
62
111
  @page.on("request", listener)
63
- [@page, -> { @page.off("request", listener); @context.tracing.stop_chunk(path: File.join(step_dir, "trace.zip")) }]
112
+ finish = lambda do
113
+ @page.off("request", listener)
114
+ @boundary = nil
115
+ @context.tracing.stop_chunk(path: File.join(step_dir, "trace.zip"))
116
+ end
117
+ [@page, finish]
118
+ end
119
+
120
+ STAMPED_TYPES = %w[Document Fetch XHR].freeze
121
+ ORDERED_KINDS = %w[document fetch xhr].freeze
122
+
123
+ # The step that runs now, as a page request names it: set for every
124
+ # step, a page or not, so a request a page sends during a step is
125
+ # that step's.
126
+ attr_writer :step #: Hash[Symbol, untyped]?
127
+
128
+ # Which requests to the world the page had finished receiving the
129
+ # response of, and which were in flight, around a claim step's
130
+ # reading: an order of the events this process received, never a
131
+ # claim that the page drew from a response. Only a document, a
132
+ # fetch, and an XMLHttpRequest count; an EventSource stays open, so
133
+ # it would be in flight on every reading.
134
+ #: (untyped) -> void
135
+ def watch_requests(context)
136
+ @requests = []
137
+ @by_request = {}
138
+ context.on("request", lambda do |request|
139
+ next unless ORDERED_KINDS.include?(request.resource_type) && Trace.stamps?(@base_url, request.url)
140
+
141
+ entry = { request: request, method: request.method, url: request.url, sent: monotonic, sent_at: Time.now.utc.iso8601(3), step: @step }
142
+ @requests << entry
143
+ @by_request[request.object_id] = entry
144
+ end)
145
+ context.on("requestfinished", lambda do |request|
146
+ entry = @by_request[request.object_id] or next
147
+ entry.merge!(finished: monotonic, finished_at: Time.now.utc.iso8601(3))
148
+ end)
149
+ context.on("requestfailed", lambda do |request|
150
+ entry = @by_request[request.object_id] or next
151
+ entry.merge!(ended: monotonic, failed_at: Time.now.utc.iso8601(3))
152
+ end)
153
+ end
154
+
155
+ # Runs one reading of a claim step and keeps when it began and ended.
156
+ #: [T] () { () -> T } -> T
157
+ def reading
158
+ started = monotonic
159
+ value = yield
160
+ @reading = [started, monotonic]
161
+ value
162
+ ensure
163
+ @reading ||= [started, monotonic] if started
164
+ end
165
+
166
+ #: () -> nil
167
+ def begin_step = (@reading = nil)
168
+
169
+ # A claim step's `pages`, `page_requests`, and `judged_view`, after
170
+ # the reading its claims were judged on, when a page was open.
171
+ #: (String, String, ?aria_in_claims: bool) -> Hash[Symbol, untyped]
172
+ def judged(dir, step_record_id, aria_in_claims: false)
173
+ return {} unless @page && @reading
174
+
175
+ started, ended = @reading
176
+ listed = []
177
+ index = lambda do |entry|
178
+ at = listed.index(entry) || (listed << entry).size - 1
179
+ at
180
+ end
181
+ before = @requests.select { _1[:finished] && _1[:finished] < started }.max_by { _1[:finished] }
182
+ open = @requests.select { _1[:sent] <= ended && !(_1[:finished] && _1[:finished] < started) && !(_1[:ended] && _1[:ended] < started) }
183
+ page = { as: nil, page: 1, url: @page.url, last_response: before && index.(before), in_flight: open.map { index.(_1) } }
184
+ # What the pages had received is of requests to a world, so a run
185
+ # with none keeps the view alone.
186
+ received = @base_url ? { pages: [page], page_requests: listed.map { request_record(_1, step_record_id) } } : {}
187
+ { **received, judged_view: view(dir, ended, aria_in_claims) }
188
+ rescue StandardError
189
+ {}
190
+ end
191
+
192
+ #: (Hash[Symbol, untyped], String) -> Hash[Symbol, untyped]
193
+ def request_record(entry, step_record_id)
194
+ # @type var trace: String?
195
+ trace = begin
196
+ entry[:request].header_value("traceparent") if entry[:finished] || entry[:failed_at]
197
+ rescue StandardError
198
+ nil
199
+ end
200
+ ids = trace&.match(/\A00-(\h{32})-(\h{16})-\h{2}\z/)
201
+ during = if entry[:step].nil? then "pause"
202
+ elsif entry[:step][:step_record_id] == step_record_id then "this-step"
203
+ else "earlier-step"
204
+ end
205
+ { method: entry[:method], url: entry[:url],
206
+ **(entry[:finished] || entry[:failed_at] ? { trace_id: ids && ids[1], span_id: ids && ids[2] } : {}),
207
+ sent_at: entry[:sent_at], finished_at: entry[:finished_at], **(entry[:failed_at] ? { failed_at: entry[:failed_at] } : {}),
208
+ sent_during: during, **(during == "earlier-step" ? { step: entry[:step] } : {}) }
209
+ end
210
+
211
+ # What the page showed right after the judged reading: its title, a
212
+ # viewport screenshot, and its ARIA snapshot, each with how long after
213
+ # the reading it was taken. The claims judged what observe returned,
214
+ # not these files.
215
+ # In a trace group of its own, so the step's actions leave these calls out.
216
+ #: (String, Float, bool) -> Hash[Symbol, untyped]
217
+ def view(dir, ended, aria_in_claims)
218
+ @context.tracing.group(TraceActions::JUDGED_VIEW_GROUP)
219
+ view_files(dir, ended, aria_in_claims)
220
+ ensure
221
+ @context.tracing.group_end rescue nil
222
+ end
223
+
224
+ # A step whose claims judge a tree nukadoko took keeps that tree in its
225
+ # claims, so the view takes no second one.
226
+ #: (String, Float, bool) -> Hash[Symbol, untyped]
227
+ def view_files(dir, ended, aria_in_claims)
228
+ FileUtils.mkdir_p(File.join(dir, "judged"))
229
+ title = (@page.title rescue nil)
230
+ shot = begin
231
+ @page.screenshot(path: File.join(dir, "judged", "page.png"))
232
+ { file: "judged/page.png", after_reading_ms: ((monotonic - ended) * 1000).round }
233
+ rescue StandardError
234
+ nil
235
+ end
236
+ aria = aria_in_claims ? nil : begin
237
+ tree = @page.aria_snapshot(mode: "ai")
238
+ File.write(File.join(dir, "judged", "page.aria.yml"), tree.end_with?("\n") ? tree : "#{tree}\n")
239
+ { file: "judged/page.aria.yml", after_reading_ms: ((monotonic - ended) * 1000).round }
240
+ rescue StandardError
241
+ nil
242
+ end
243
+ { pages: [{ as: nil, page: 1, url: @page.url, title: title, screenshot: shot, aria: aria }], **(aria_in_claims ? { aria_in_claims: true } : {}) }
244
+ end
245
+
246
+ #: () -> Float
247
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
248
+
249
+
250
+ # A page's documents, fetches, and XMLHttpRequests to the world get
251
+ # the running step's traceparent through the Chrome DevTools
252
+ # Protocol's Fetch domain, on a session of the page's own: a header set
253
+ # on the whole context would reach other origins too, and a route
254
+ # turns the browser's cache off. Images, scripts, and stylesheets are
255
+ # left out, since each paused request costs a round trip. A session
256
+ # that cannot be opened leaves the page's requests unstamped.
257
+ #: (untyped) -> void
258
+ def stamp(page)
259
+ session = @context.new_cdp_session(page)
260
+ session.on("Fetch.requestPaused", lambda do |event|
261
+ request = event["request"]
262
+ headers = nil
263
+ unless request["headers"].keys.any? { _1.downcase == "traceparent" }
264
+ traceparent = @boundary&.stamp(request["url"])
265
+ headers = [*request["headers"].map { |name, value| { name: name, value: value } }, { name: "traceparent", value: traceparent }] if traceparent
266
+ end
267
+ # Answered off the thread that delivers the event, which also
268
+ # reads the answer.
269
+ Thread.new do
270
+ session.send_message("Fetch.continueRequest", params: { requestId: event["requestId"], **(headers ? { headers: headers } : {}) })
271
+ rescue StandardError
272
+ nil
273
+ end
274
+ end)
275
+ world = URI(@base_url)
276
+ patterns = ["#{Trace.origin(world).gsub(/[\\*?]/) { "\\#{_1}" }}/*"]
277
+ patterns << "#{world.scheme}://*.localhost:#{world.port}/*" if world.host == "localhost"
278
+ session.send_message("Fetch.enable", params: { patterns: patterns.product(STAMPED_TYPES).map { |url, type| { urlPattern: url, resourceType: type, requestStage: "Request" } } })
279
+ rescue StandardError
280
+ nil
281
+ end
282
+
283
+ # How long a pause waits for each capture of the page's view. A page
284
+ # whose main thread is stuck answers none of them, and without a
285
+ # deadline the pause would never reach the person.
286
+ VIEW_TIMEOUT_MS = 5_000
287
+
288
+ # What `nuka run --step` shows at a pause, taken while the run waits:
289
+ # a viewport screenshot and an ARIA snapshot of the open page, named
290
+ # under `recorded_as` as run.json names them. From now until
291
+ # `release`, the requests the page sends go to the pause's own
292
+ # http.jsonl, never to the step's record. `[]` when no page is open.
293
+ #: (String, String) -> Array[Hash[Symbol, untyped]]
294
+ def hold(dir, recorded_as)
295
+ return [] unless @page
296
+
297
+ log = File.join(dir, "http.jsonl")
298
+ @held = lambda do |req|
299
+ File.open(log, "a") { _1.puts JSON.generate({ method: req.method, url: req.url, via: "page" }) }
300
+ rescue StandardError
301
+ nil
302
+ end
303
+ @page.on("request", @held)
304
+ shot = begin
305
+ @page.screenshot(path: File.join(dir, "page.png"), timeout: VIEW_TIMEOUT_MS)
306
+ "#{recorded_as}/page.png"
307
+ rescue StandardError
308
+ nil
309
+ end
310
+ aria = begin
311
+ tree = @page.aria_snapshot(mode: "ai", timeout: VIEW_TIMEOUT_MS)
312
+ File.write(File.join(dir, "page.aria.yml"), tree.end_with?("\n") ? tree : "#{tree}\n")
313
+ "#{recorded_as}/page.aria.yml"
314
+ rescue StandardError
315
+ nil
316
+ end
317
+ title = (@page.title rescue nil)
318
+ [{ as: nil, page: 1, url: @page.url, title: title, screenshot: shot, aria: aria }]
319
+ end
320
+
321
+ # The pause is answered: the page's requests are the next step's again.
322
+ #: () -> void
323
+ def release
324
+ @page.off("request", @held) if @page && @held
325
+ @held = nil
64
326
  end
65
327
 
66
328
  # Each scenario gets a browser context of its own, so cookies and storage
67
329
  # never carry from one scenario to the next.
68
- def end_scenario
330
+ # The browser the scenario opened a page in, as run.json names it, or
331
+ # nil when it opened none.
332
+ #: () -> Hash[Symbol, untyped]?
333
+ def scenario_browser
334
+ @context && @browser ? { type: "chromium", version: @browser.version } : nil
335
+ end
336
+
337
+ # Closes the scenario's context, and returns the screenshot of its
338
+ # page as the scenario ended, `final.png` in `dir`, when it opened
339
+ # one. A page a failed step left unusable has none, and that costs
340
+ # the screenshot only.
341
+ #: (?String?) -> Array[Hash[Symbol, untyped]]
342
+ def end_scenario(dir = nil)
343
+ shots = [] #: Array[Hash[Symbol, untyped]]
344
+ if dir && @page
345
+ begin
346
+ FileUtils.mkdir_p(dir)
347
+ @page.screenshot(path: File.join(dir, "final.png"))
348
+ shots << { file: "final.png", at: Time.now.utc.iso8601(3) }
349
+ rescue StandardError
350
+ nil
351
+ end
352
+ end
69
353
  @context&.tracing&.stop
70
354
  @context&.close
71
355
  @context = @page = nil
356
+ shots
72
357
  end
73
358
 
359
+ #: () -> void
74
360
  def close
75
361
  @browser&.close
76
362
  @execution&.stop
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "net/http"
5
+
6
+ # Requests a step sends through Net::HTTP itself, without the `request`
7
+ # fixture, measured as the TypeScript engine measures a step's own `fetch`:
8
+ # each lands in the step's http.jsonl with `via: "net/http"`, and one to
9
+ # the world's origin carries the step's traceparent. It records only while
10
+ # a step runs, on the thread that runs it, so a fixture's setup, the
11
+ # engine's own readiness check, and the `request` fixture (which records
12
+ # its requests itself) go through Net::HTTP untouched.
13
+ module Nukadoko
14
+ module Engine
15
+ module HttpRecording
16
+ #: [T] (Array[untyped]) { () -> T } -> T
17
+ def self.collect(log)
18
+ Thread.current[:nukadoko_http] = log
19
+ yield
20
+ ensure
21
+ Thread.current[:nukadoko_http] = nil
22
+ end
23
+
24
+ # Net::HTTP as the engine's own code calls it, recording nothing.
25
+ #: [T] () { () -> T } -> T
26
+ def self.unrecorded
27
+ was = Thread.current[:nukadoko_http_off]
28
+ Thread.current[:nukadoko_http_off] = true
29
+ yield
30
+ ensure
31
+ Thread.current[:nukadoko_http_off] = was
32
+ end
33
+
34
+ # Prepended to Net::HTTP. `request` calls itself once more when the
35
+ # connection was not started, so only the outermost call records.
36
+ # @rbs module-self Net::HTTP
37
+ module Patch
38
+ #: (Net::HTTPGenericRequest, ?String?) ?{ (Net::HTTPResponse) -> void } -> Net::HTTPResponse
39
+ def request(req, body = nil, &block)
40
+ log = Thread.current[:nukadoko_http]
41
+ return super if log.nil? || Thread.current[:nukadoko_http_off] || Thread.current[:nukadoko_http_inside]
42
+
43
+ Thread.current[:nukadoko_http_inside] = true
44
+ url = "#{use_ssl? ? "https" : "http"}://#{address}#{":#{port}" unless port == (use_ssl? ? 443 : 80)}#{req.path}"
45
+ traceparent = req["traceparent"] ? nil : Trace.current&.stamp(url)
46
+ req["traceparent"] = traceparent if traceparent
47
+ stamp = traceparent ? { traceparent: traceparent, traceparent_sent_to: [Trace.origin(URI(url))] } : {}
48
+ sent = body || req.body
49
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
50
+ begin
51
+ res = super
52
+ rescue StandardError => e
53
+ log << { method: req.method, url: url, status: 0, duration_ms: Request.since(started), via: "net/http", **stamp,
54
+ **Request.body(:request_body, sent), error: e.message.lines.first.to_s.chomp }
55
+ raise
56
+ end
57
+ log << { method: req.method, url: url, status: res.code.to_i, duration_ms: Request.since(started), via: "net/http", **stamp,
58
+ **Request.body(:request_body, sent), **(res.body.is_a?(String) ? Request.body(:response_body, res.body) : {}) }
59
+ res
60
+ ensure
61
+ Thread.current[:nukadoko_http_inside] = false if log && !Thread.current[:nukadoko_http_off]
62
+ end
63
+ end
64
+
65
+ Net::HTTP.prepend(Patch)
66
+ end
67
+ end
68
+ end