nukadoko 0.6.0 → 0.7.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 (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +541 -3
  3. data/README.ja.md +20 -5
  4. data/README.md +12 -6
  5. data/docs/ci.ja.md +542 -0
  6. data/docs/ci.md +635 -0
  7. data/docs/commands.ja.md +1524 -0
  8. data/docs/commands.md +1281 -0
  9. data/docs/engines.json +19 -0
  10. data/docs/execution-events.ja.md +336 -0
  11. data/docs/execution-events.md +423 -0
  12. data/docs/glossary.json +1348 -0
  13. data/docs/guide.ja.md +733 -0
  14. data/docs/guide.md +815 -0
  15. data/docs/intent.ja.md +133 -0
  16. data/docs/intent.md +156 -0
  17. data/docs/layout.ja.md +442 -0
  18. data/docs/layout.md +399 -0
  19. data/docs/releasing.ja.md +186 -0
  20. data/docs/releasing.md +237 -0
  21. data/docs/ruby/reference.ja.md +302 -0
  22. data/docs/ruby/reference.md +368 -0
  23. data/docs/spec.ja.md +8916 -0
  24. data/docs/spec.md +11250 -0
  25. data/docs/tutorial.ja.md +451 -0
  26. data/docs/tutorial.md +458 -0
  27. data/docs/typescript/adopting.ja.md +231 -0
  28. data/docs/typescript/adopting.md +251 -0
  29. data/docs/typescript/doors.ja.md +301 -0
  30. data/docs/typescript/doors.md +329 -0
  31. data/docs/typescript/migration-playwright-test.ja.md +189 -0
  32. data/docs/typescript/migration-playwright-test.md +212 -0
  33. data/docs/typescript/migration.ja.md +391 -0
  34. data/docs/typescript/migration.md +505 -0
  35. data/docs/typescript/reference.ja.md +176 -0
  36. data/docs/typescript/reference.md +197 -0
  37. data/docs/typescript/upgrading.ja.md +1774 -0
  38. data/docs/typescript/upgrading.md +2224 -0
  39. data/docs/web-app.ja.md +627 -0
  40. data/docs/web-app.md +659 -0
  41. data/docs/writing-scenarios.ja.md +544 -0
  42. data/docs/writing-scenarios.md +563 -0
  43. data/lib/nukadoko/base.rb +12 -5
  44. data/lib/nukadoko/changed_files.rb +95 -0
  45. data/lib/nukadoko/check.rb +459 -51
  46. data/lib/nukadoko/claim_drops.rb +271 -0
  47. data/lib/nukadoko/claim_line.rb +24 -4
  48. data/lib/nukadoko/claim_rules.rb +143 -1
  49. data/lib/nukadoko/claim_sides.rb +157 -9
  50. data/lib/nukadoko/cli.rb +395 -48
  51. data/lib/nukadoko/codes.json +246 -21
  52. data/lib/nukadoko/codes.rb +21 -4
  53. data/lib/nukadoko/command.rb +120 -13
  54. data/lib/nukadoko/command_help.rb +128 -0
  55. data/lib/nukadoko/compat.rb +469 -0
  56. data/lib/nukadoko/criteria.rb +1 -1
  57. data/lib/nukadoko/definition.rb +157 -7
  58. data/lib/nukadoko/error_frames.rb +6 -3
  59. data/lib/nukadoko/events/count.rb +146 -0
  60. data/lib/nukadoko/events/counted.rb +114 -0
  61. data/lib/nukadoko/events/format.rb +257 -0
  62. data/lib/nukadoko/events/lists.rb +154 -0
  63. data/lib/nukadoko/events/path.rb +285 -0
  64. data/lib/nukadoko/events/read.rb +284 -0
  65. data/lib/nukadoko/events/reader.rb +490 -0
  66. data/lib/nukadoko/events/selection.rb +252 -0
  67. data/lib/nukadoko/events/tally.rb +438 -0
  68. data/lib/nukadoko/features.rb +2 -2
  69. data/lib/nukadoko/fixtures.rb +160 -35
  70. data/lib/nukadoko/http_recording.rb +6 -2
  71. data/lib/nukadoko/intent.rb +364 -0
  72. data/lib/nukadoko/intent_file.rb +81 -0
  73. data/lib/nukadoko/intent_view.rb +190 -0
  74. data/lib/nukadoko/js_json.rb +2 -1
  75. data/lib/nukadoko/judge.rb +2 -2
  76. data/lib/nukadoko/judgment_file.rb +1 -1
  77. data/lib/nukadoko/judgments.rb +4 -4
  78. data/lib/nukadoko/measure_mcp.rb +202 -0
  79. data/lib/nukadoko/parts.rb +8 -2
  80. data/lib/nukadoko/path_view.rb +252 -0
  81. data/lib/nukadoko/place_rows.rb +161 -0
  82. data/lib/nukadoko/program.rb +1265 -51
  83. data/lib/nukadoko/program_log.rb +122 -0
  84. data/lib/nukadoko/program_shape.rb +385 -0
  85. data/lib/nukadoko/project_fixtures.rb +43 -10
  86. data/lib/nukadoko/project_program.rb +5 -4
  87. data/lib/nukadoko/repeated_prefix.rb +310 -0
  88. data/lib/nukadoko/report_run.rb +3 -3
  89. data/lib/nukadoko/run.rb +1148 -159
  90. data/lib/nukadoko/run_record.rb +70 -46
  91. data/lib/nukadoko/scaffold.rb +24 -6
  92. data/lib/nukadoko/schema.rb +15 -2
  93. data/lib/nukadoko/secrets.rb +55 -5
  94. data/lib/nukadoko/states.rb +478 -0
  95. data/lib/nukadoko/step.rb +71 -2
  96. data/lib/nukadoko/step_fixtures.rb +52 -3
  97. data/lib/nukadoko/summary.rb +799 -29
  98. data/lib/nukadoko/table.rb +4 -2
  99. data/lib/nukadoko/text_fit.rb +20 -7
  100. data/lib/nukadoko/trace.rb +152 -45
  101. data/lib/nukadoko/tree_passes.rb +95 -33
  102. data/lib/nukadoko/underneath.rb +311 -0
  103. data/lib/nukadoko/version.rb +1 -1
  104. data/lib/nukadoko/vocabulary.rb +166 -23
  105. data/lib/nukadoko/walk.rb +2 -2
  106. data/lib/nukadoko/walk_step.rb +1 -1
  107. data/lib/nukadoko.rb +23 -0
  108. data/llms.txt +41 -34
  109. data/sig/generated/nukadoko/base.rbs +4 -4
  110. data/sig/generated/nukadoko/changed_files.rbs +42 -0
  111. data/sig/generated/nukadoko/check.rbs +147 -10
  112. data/sig/generated/nukadoko/claim_drops.rbs +135 -0
  113. data/sig/generated/nukadoko/claim_line.rbs +11 -0
  114. data/sig/generated/nukadoko/claim_rules.rbs +49 -4
  115. data/sig/generated/nukadoko/claim_sides.rbs +63 -12
  116. data/sig/generated/nukadoko/cli.rbs +80 -7
  117. data/sig/generated/nukadoko/codes.rbs +19 -4
  118. data/sig/generated/nukadoko/command.rbs +68 -1
  119. data/sig/generated/nukadoko/command_help.rbs +18 -0
  120. data/sig/generated/nukadoko/compat.rbs +392 -0
  121. data/sig/generated/nukadoko/criteria.rbs +1 -1
  122. data/sig/generated/nukadoko/definition.rbs +50 -0
  123. data/sig/generated/nukadoko/error_frames.rbs +1 -1
  124. data/sig/generated/nukadoko/events/count.rbs +69 -0
  125. data/sig/generated/nukadoko/events/counted.rbs +70 -0
  126. data/sig/generated/nukadoko/events/format.rbs +163 -0
  127. data/sig/generated/nukadoko/events/lists.rbs +47 -0
  128. data/sig/generated/nukadoko/events/path.rbs +161 -0
  129. data/sig/generated/nukadoko/events/read.rbs +109 -0
  130. data/sig/generated/nukadoko/events/reader.rbs +226 -0
  131. data/sig/generated/nukadoko/events/selection.rbs +100 -0
  132. data/sig/generated/nukadoko/events/tally.rbs +227 -0
  133. data/sig/generated/nukadoko/features.rbs +6 -4
  134. data/sig/generated/nukadoko/fixtures.rbs +67 -11
  135. data/sig/generated/nukadoko/http_recording.rbs +1 -1
  136. data/sig/generated/nukadoko/intent.rbs +132 -0
  137. data/sig/generated/nukadoko/intent_file.rbs +46 -0
  138. data/sig/generated/nukadoko/intent_view.rbs +69 -0
  139. data/sig/generated/nukadoko/judgment_file.rbs +1 -1
  140. data/sig/generated/nukadoko/judgments.rbs +1 -1
  141. data/sig/generated/nukadoko/measure_mcp.rbs +104 -0
  142. data/sig/generated/nukadoko/parts.rbs +2 -2
  143. data/sig/generated/nukadoko/path_view.rbs +105 -0
  144. data/sig/generated/nukadoko/place_rows.rbs +43 -0
  145. data/sig/generated/nukadoko/program.rbs +627 -23
  146. data/sig/generated/nukadoko/program_log.rbs +67 -0
  147. data/sig/generated/nukadoko/program_shape.rbs +147 -0
  148. data/sig/generated/nukadoko/project_fixtures.rbs +16 -3
  149. data/sig/generated/nukadoko/project_program.rbs +2 -1
  150. data/sig/generated/nukadoko/repeated_prefix.rbs +172 -0
  151. data/sig/generated/nukadoko/report_run.rbs +1 -1
  152. data/sig/generated/nukadoko/run.rbs +286 -41
  153. data/sig/generated/nukadoko/run_record.rbs +20 -12
  154. data/sig/generated/nukadoko/scaffold.rbs +3 -0
  155. data/sig/generated/nukadoko/schema.rbs +5 -0
  156. data/sig/generated/nukadoko/secrets.rbs +26 -3
  157. data/sig/generated/nukadoko/states.rbs +214 -0
  158. data/sig/generated/nukadoko/step.rbs +58 -1
  159. data/sig/generated/nukadoko/step_fixtures.rbs +39 -0
  160. data/sig/generated/nukadoko/summary.rbs +256 -2
  161. data/sig/generated/nukadoko/table.rbs +3 -2
  162. data/sig/generated/nukadoko/trace.rbs +108 -33
  163. data/sig/generated/nukadoko/tree_passes.rbs +36 -8
  164. data/sig/generated/nukadoko/underneath.rbs +141 -0
  165. data/sig/generated/nukadoko/vocabulary.rbs +45 -6
  166. data/skills/nukadoko/SKILL.md +18 -18
  167. data/skills/nukadoko/references/checking-steps.md +16 -83
  168. data/skills/nukadoko/references/diagnosing.md +6 -6
  169. data/skills/nukadoko/references/evidence.md +19 -6
  170. data/skills/nukadoko/references/exploring.md +22 -7
  171. data/skills/nukadoko/references/fixtures.md +12 -32
  172. data/skills/nukadoko/references/judgments.md +12 -0
  173. data/skills/nukadoko/references/maintenance.md +1 -1
  174. data/skills/nukadoko/references/merge-risk.md +1 -1
  175. data/skills/nukadoko/references/parts.md +46 -23
  176. data/skills/nukadoko/references/{perturbed-worlds.md → perturbed-systems.md} +30 -12
  177. data/skills/nukadoko/references/program.md +168 -169
  178. data/skills/nukadoko/references/reviewing.md +20 -20
  179. data/skills/nukadoko/references/ruby/checking-steps.md +106 -0
  180. data/skills/nukadoko/references/ruby/examples/cli.md +212 -0
  181. data/skills/nukadoko/references/ruby/fixtures.md +34 -0
  182. data/skills/nukadoko/references/ruby/program.md +112 -0
  183. data/skills/nukadoko/references/ruby/step-files.md +115 -0
  184. data/skills/nukadoko/references/running.md +34 -34
  185. data/skills/nukadoko/references/scenario-rules.md +7 -6
  186. data/skills/nukadoko/references/states.md +7 -1
  187. data/skills/nukadoko/references/step-files.md +41 -120
  188. data/skills/nukadoko/references/typescript/checking-steps.md +129 -0
  189. data/skills/nukadoko/references/{examples → typescript/examples}/cli.md +1 -1
  190. data/skills/nukadoko/references/{examples → typescript/examples}/http-api.md +6 -6
  191. data/skills/nukadoko/references/{examples → typescript/examples}/workflow.md +1 -1
  192. data/skills/nukadoko/references/typescript/fixtures.md +56 -0
  193. data/skills/nukadoko/references/typescript/program.md +111 -0
  194. data/skills/nukadoko/references/typescript/step-files.md +104 -0
  195. data/skills/nukadoko/references/verdicts.md +10 -10
  196. data/skills/nukadoko/references/writing-steps.md +67 -67
  197. data/skills/nukadoko/references/writing-the-feature.md +1 -1
  198. data/skills/nukadoko-verification/SKILL.md +13 -8
  199. metadata +103 -7
  200. data/skills/nukadoko/references/ruby.md +0 -80
@@ -5,7 +5,7 @@
5
5
  # backtrace. A step record's error message says what went wrong but not
6
6
  # where, so a reader had to call the step again outside nukadoko to find the
7
7
  # line. The frames kept are the ones a reader can open and change: inside
8
- # the project root, and outside the gem and any installed bundle, as the
8
+ # the project root, and outside this gem and every installed gem, as the
9
9
  # TypeScript engine leaves out node_modules.
10
10
  module Nukadoko
11
11
  module Engine
@@ -23,15 +23,18 @@ module Nukadoko
23
23
  def of(error, root)
24
24
  # A root under a symlink (macOS /var) names files by either spelling.
25
25
  roots = [File.expand_path(root), (File.realpath(root) rescue nil)].compact.uniq
26
+ # Gem.path holds every directory gems load from, the bundle's own
27
+ # included, wherever BUNDLE_PATH put it: vendor/bundle, .bundle, or a
28
+ # directory a reader does not expect.
29
+ installed = [GEM_ROOT, *Gem.path.map { File.expand_path(_1) }]
26
30
  frames = [] #: Array[String]
27
31
  (error.backtrace_locations || []).each do |location|
28
32
  file = location.absolute_path || location.path
29
33
  next unless file && File.absolute_path?(file)
30
34
  base = roots.find { file.start_with?("#{_1}/") }
31
- next if file.start_with?("#{GEM_ROOT}/") || base.nil?
35
+ next if base.nil? || installed.any? { file.start_with?("#{_1}/") }
32
36
 
33
37
  relative = file.delete_prefix("#{base}/")
34
- next if relative.split("/").include?("vendor") && relative.include?("/bundle/")
35
38
 
36
39
  frame = "#{relative}:#{location.lineno}"
37
40
  frames << frame unless frames.include?(frame)
@@ -0,0 +1,146 @@
1
+ # frozen_string_literal: true
2
+
3
+ # rbs_inline: enabled
4
+
5
+ module Nukadoko
6
+ module Engine
7
+ module Events
8
+ # Responsibility: what a count of execution events says of a claim:
9
+ # the range the count lies in, and whether a compare holds, breaks, or
10
+ # cannot be known on that range, with the words of the reason. Pure.
11
+ # Boundary: what the lines add up to is the tally's; where the
12
+ # expected value comes from is the claim's.
13
+ #
14
+ # A count is a range, never one number standing for "probably that
15
+ # many". Lines that match raise the lower bound. Lines that may match
16
+ # raise only the upper bound, and a reading that is not whole has
17
+ # none, since more lines may still come. A compare holds, or breaks,
18
+ # only when it gives that answer for every count in the range, so an
19
+ # absence never holds on a reading that was not whole.
20
+ module Count
21
+ COMPARES = %w[equal not-equal greater-than at-least less-than at-most].freeze
22
+
23
+ # The gaps that say nothing was read, rather than that what was
24
+ # read may lack lines.
25
+ UNREAD_GAPS = %w[inlet-unnamed system-unread producer-not-run].freeze
26
+
27
+ CAUSE_WORDS = {
28
+ "unreadable" => ["could not be read", "could not be read"],
29
+ "undefined_kind" => ["is of a kind the format does not define", "are of a kind the format does not define"],
30
+ "unknown_version" => ["is of a later version", "are of a later version"],
31
+ "field_unknown" => ["lacks a selected field or holds an invalid one", "lack a selected field or hold an invalid one"],
32
+ "holds_unknown" => ["may be on a table the count leaves out", "may be on tables the count leaves out"],
33
+ "commit_unknown" => ["has a commit state no line decides", "have a commit state no line decides"],
34
+ "unowned" => ["carries no step's trace id and may be the step's", "carry no step's trace id and may be the step's"]
35
+ }.freeze
36
+
37
+ # The range a selection's count lies in: `[yes, yes + maybe]` on a
38
+ # whole reading, `[yes, unbounded]` on one that is not.
39
+ #: (Integer, Hash[String, Integer], bool) -> Hash[Symbol, Integer?]
40
+ def self.range_of(yes, maybe, whole)
41
+ { at_least: yes, at_most: whole ? yes + maybe_total(maybe) : nil }
42
+ end
43
+
44
+ #: (Hash[String, Integer]) -> Integer
45
+ def self.maybe_total(maybe) = MAYBE_CAUSES.sum { maybe[_1].to_i }
46
+
47
+ # What `compare` gives for every whole count in `range`.
48
+ #: (Hash[Symbol, Integer?], String, Numeric) -> Symbol
49
+ def self.judge_range(range, compare, expected)
50
+ low = range[:at_least].to_i
51
+ high = range[:at_most]
52
+ answer = ->(holds, breaks) { holds ? :held : breaks ? :broken : :unknown }
53
+ # A count is a whole number, so it never equals a fraction.
54
+ within = (expected.is_a?(Integer) || (expected.is_a?(Float) && expected == expected.floor)) && expected >= low && (high.nil? || expected <= high)
55
+ case compare
56
+ when "equal" then answer.(within && high == low, !within)
57
+ when "not-equal" then answer.(!within, within && high == low)
58
+ when "greater-than" then answer.(low > expected, !high.nil? && high <= expected)
59
+ when "at-least" then answer.(low >= expected, !high.nil? && high < expected)
60
+ when "less-than" then answer.(!high.nil? && high < expected, low >= expected)
61
+ else answer.(!high.nil? && high <= expected, low > expected)
62
+ end
63
+ end
64
+
65
+ #: (Integer) -> String
66
+ def self.lines(count) = count == 1 ? "1 line" : "#{count} lines"
67
+
68
+ # The words of one gap, as a reason uses them.
69
+ #: (Hash[Symbol, untyped]) -> String
70
+ def self.describe_gap(gap)
71
+ case gap[:gap]
72
+ when "inlet-unnamed" then "the program names no {events}, so the program has no events file"
73
+ when "system-unread" then "nukadoko did not start the system's program, so it reads no events there"
74
+ when "producer-not-run" then "no earlier line of the scenario ran the step whose events are read"
75
+ when "no-requests" then "the step sent the system no request with a traceparent, ran no process, and sent no MCP call"
76
+ when "mcp-unbounded"
77
+ if gap[:calls] == 1
78
+ "1 MCP call of the step went to its server by a way no line reports the end of (stdio, or another origin than the system's), and the server may still work for it"
79
+ else
80
+ "#{gap[:calls]} MCP calls of the step went to their server by a way no line reports the end of (stdio, or another origin than the system's), and the server may still work for them"
81
+ end
82
+ when "processes-unbounded" then "a process the step ran may still send the system requests, and no line can say that every one reported"
83
+ when "service-unrecorded"
84
+ "nukadoko reads no execution events of service #{gap[:service]}, which the step sent a request to, so no line says where its work ended"
85
+ when "no-lines" then "no line#{service_words(gap)} carries the step's trace id"
86
+ when "request-unreported"
87
+ to = gap[:service] ? " to service #{gap[:service]}" : ""
88
+ if gap[:requests] == 1
89
+ "1 of the step's requests#{to} has no request line"
90
+ else
91
+ "#{gap[:requests]} of the step's requests#{to} have no request line"
92
+ end
93
+ when "jobs-pending"
94
+ ids = gap[:job_ids]
95
+ ids.size == 1 ? "job #{ids[0]}#{service_words(gap)} was enqueued and has not performed" : "jobs #{ids.join(", ")}#{service_words(gap)} were enqueued and have not performed"
96
+ when "kind-unreported" then "the program has reported no #{gap[:kind]} line in this system"
97
+ when "unreadable" then "#{lines(gap[:lines])} of the trace#{service_words(gap)} could not be read"
98
+ when "truncated" then "the lines#{service_words(gap)} came to more than the record's file holds"
99
+ else "the events file#{service_words(gap)} was replaced or made shorter while it was read"
100
+ end
101
+ end
102
+
103
+ # The service a gap is about, as its words name it; nothing for a
104
+ # gap of a record written before a system could hold several
105
+ # services.
106
+ #: (Hash[Symbol, untyped]) -> String
107
+ def self.service_words(gap) = gap[:service] ? " of service #{gap[:service]}" : ""
108
+
109
+ # The lines that may match, by cause.
110
+ #: (Hash[String, Integer]) -> String
111
+ def self.describe_maybe(maybe)
112
+ MAYBE_CAUSES.select { maybe[_1].to_i.positive? }.map { "#{lines(maybe[_1])} #{CAUSE_WORDS.fetch(_1)[maybe[_1] == 1 ? 0 : 1]}" }.join(", ")
113
+ end
114
+
115
+ # The range in words: `exactly 2`, `between 1 and 3`, `at least 1,
116
+ # with no upper bound`.
117
+ #: (Hash[Symbol, Integer?]) -> String
118
+ def self.describe_range(range)
119
+ return "at least #{range[:at_least]}, with no upper bound" if range[:at_most].nil?
120
+
121
+ range[:at_most] == range[:at_least] ? "exactly #{range[:at_least]}" : "between #{range[:at_least]} and #{range[:at_most]}"
122
+ end
123
+
124
+ # `held` or `broken` only when every count in the range gives that
125
+ # answer; `unjudged` with the reason and the gap word otherwise.
126
+ # `of` names the step whose events were read, in the reason.
127
+ #: (Hash[Symbol, untyped], String, Numeric, ?String?) -> Hash[Symbol, untyped]
128
+ def self.judge(reading, compare, expected, of = nil)
129
+ answer = judge_range(reading[:range], compare, expected)
130
+ return { outcome: answer } unless answer == :unknown
131
+
132
+ first = reading[:whole] ? nil : reading[:open].first #: Hash[Symbol, untyped]?
133
+ may = describe_maybe(reading[:maybe])
134
+ events = of.nil? ? "the events" : "the events of #{of}"
135
+ state = first && UNREAD_GAPS.include?(first[:gap]) ? "were not read" : "are not whole"
136
+ why = if first then "#{events} #{state} (#{first[:gap]}): #{describe_gap(first)}"
137
+ elsif !may.empty? then may
138
+ else "#{events} are not whole"
139
+ end
140
+ shown = expected.is_a?(Float) && expected == expected.floor ? expected.to_i : expected
141
+ { outcome: :unjudged, reason: "#{why}, so the count is #{describe_range(reading[:range])}, and #{compare} #{shown} is not known", gap: first&.[](:gap) }
142
+ end
143
+ end
144
+ end
145
+ end
146
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # What a count of execution events counted, grouped so a record names
5
+ # what the lines were and not only how many: the lines of one kind that
6
+ # hold the same values in the fields that tell them apart, and those
7
+ # groups in words. Pure. Which lines a count matches is Tally's.
8
+ module Nukadoko
9
+ module Engine
10
+ module Events
11
+ module Counted
12
+ # The fields a group of each kind is told apart by, in the order its
13
+ # record and its words name them.
14
+ GROUP_FIELDS = {
15
+ "request" => %w[method route status], "db" => %w[op table], "tx" => %w[phase], "job" => %w[name phase],
16
+ "http" => %w[method origin status], "flag" => %w[name side], "error" => %w[class handled]
17
+ }.freeze #: Hash[String, Array[String]]
18
+
19
+ OP_WORDS = { "read" => "read from", "insert" => "insert into", "update" => "update", "delete" => "delete from", "other" => "other on" }.freeze
20
+
21
+ # How many groups a line names before it says how many lines the
22
+ # rest hold.
23
+ GROUPS_NAMED = 3
24
+
25
+ # The lines a count matched, grouped as they are folded.
26
+ class Groups
27
+ #: (String) -> void
28
+ def initialize(kind)
29
+ @kind = kind
30
+ @lines = Hash.new(0) #: Hash[String, Integer]
31
+ end
32
+
33
+ #: (Hash[String, untyped]) -> void
34
+ def add(object) = @lines[Counted.key_of(@kind, object)] += 1
35
+
36
+ # The groups of the lines added and of `more`, most lines first,
37
+ # then by their values; `more` is not added.
38
+ #: (?Array[Hash[String, untyped]]) -> Array[Hash[Symbol, untyped]]
39
+ def groups(more = [])
40
+ all = @lines.dup
41
+ more.each { all[Counted.key_of(@kind, _1)] += 1 }
42
+ names = GROUP_FIELDS.fetch(@kind)
43
+ all.sort { |(left_key, left), (right_key, right)| [right, left_key] <=> [left, right_key] }.map do |key, held|
44
+ values = JSON.parse(key)
45
+ { kind: @kind, fields: names.each_with_index.to_h { |name, index| [name, values[index]] }, lines: held }
46
+ end
47
+ end
48
+ end
49
+
50
+ module_function
51
+
52
+ # The values a group is told apart by, as one key. JSON of the
53
+ # values, compared as text, as the TypeScript engine orders them.
54
+ #: (String, Hash[untyped, untyped]) -> String
55
+ def key_of(kind, fields)
56
+ values = GROUP_FIELDS.fetch(kind).map { fields[_1] || fields[_1.to_sym] }
57
+ JsJson.generate(values)
58
+ end
59
+
60
+ # The groups `after` holds more lines of than `before`, each with
61
+ # how many more.
62
+ #: (Array[Hash[Symbol, untyped]], Array[Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
63
+ def added(before, after)
64
+ earlier = before.to_h { ["#{_1[:kind]}#{key_of(_1[:kind], _1[:fields])}", _1[:lines]] }
65
+ after.filter_map do |group|
66
+ more = group[:lines] - earlier.fetch("#{group[:kind]}#{key_of(group[:kind], group[:fields])}", 0)
67
+ group.merge(lines: more) if more.positive?
68
+ end
69
+ end
70
+
71
+ #: (untyped) -> String
72
+ def text(value) = Selection.value_text(value)
73
+
74
+ # One group in words, by kind: `db insert into events`.
75
+ #: (Hash[Symbol, untyped]) -> String
76
+ def words(group)
77
+ fields = group[:fields].transform_keys(&:to_s)
78
+ case group[:kind]
79
+ when "request" then "request #{text(fields["method"])} #{fields["route"].nil? ? "(no route)" : text(fields["route"])} #{text(fields["status"])}"
80
+ when "db" then "db #{OP_WORDS[fields["op"]] || text(fields["op"])} #{text(fields["table"])}"
81
+ when "tx" then "tx #{text(fields["phase"])}"
82
+ when "job" then "job #{text(fields["name"])} #{text(fields["phase"])}"
83
+ when "http" then "http #{text(fields["method"])} #{text(fields["origin"])} #{fields["status"].nil? ? "(no response)" : text(fields["status"])}"
84
+ when "flag" then "flag #{text(fields["name"])} #{text(fields["side"])}"
85
+ else "error #{text(fields["class"])} (#{fields["handled"] == true ? "handled" : "not handled"})"
86
+ end
87
+ end
88
+
89
+ #: (Integer, bool) -> String
90
+ def lines_text(count, more) = "#{count}#{" more" if more} #{count == 1 ? "line" : "lines"}"
91
+
92
+ # The groups in words: `1 line: db insert into events`, `3 lines: 2
93
+ # db insert into scores, 1 db update rankings`, and past
94
+ # GROUPS_NAMED `..., and 4 more lines in 2 groups`.
95
+ #: (Array[Hash[Symbol, untyped]], ?bool) -> String
96
+ def describe(groups, more = false) = describe_groups(groups, more) { words(_1) }
97
+
98
+ # The groups a count left out, each with what its table holds.
99
+ #: (Array[Hash[Symbol, untyped]]) -> String
100
+ def describe_left_out(groups) = describe_groups(groups, false) { "#{words(_1)} (#{_1[:holds]})" }
101
+
102
+ #: (Array[Hash[Symbol, untyped]], bool) { (Hash[Symbol, untyped]) -> String } -> String
103
+ def describe_groups(groups, more)
104
+ return "" if groups.empty?
105
+
106
+ named = groups.first(GROUPS_NAMED).map { |group| groups.size == 1 ? yield(group) : "#{group[:lines]} #{yield(group)}" }
107
+ rest = groups.drop(GROUPS_NAMED)
108
+ tail = rest.empty? ? [] : ["and #{lines_text(rest.sum { _1[:lines] }, true)} in #{rest.size} #{rest.size == 1 ? "group" : "groups"}"]
109
+ "#{lines_text(groups.sum { _1[:lines] }, more)}: #{[*named, *tail].join(", ")}"
110
+ end
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,257 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "json"
5
+
6
+ # The execution events line format, version 1 (docs/execution-events.md),
7
+ # as data: every kind and every field it defines, and the one function
8
+ # that turns a line of text into what the line is. Pure: no I/O, no
9
+ # secrets, no clock. Which step a line belongs to is decided from the trace
10
+ # id this module reads and the system's prefix the caller passes
11
+ # (`owner_of`); what the lines of one trace add up to is Tally's.
12
+ #
13
+ # A line is an event only when its kind's required fields hold values the
14
+ # format allows. A line that breaks that is unreadable, with the reason,
15
+ # and so is one that is not one JSON object, repeats a key in one object
16
+ # (a parser keeps one of the two values, so a record would show one and
17
+ # say nothing), holds an integer past 2^53 - 1 (the TypeScript engine's
18
+ # parser rounds it, so an id would change silently there), or has no valid
19
+ # `trace` or `kind`. An unreadable line has no owner: no trace id read
20
+ # from it is trusted, so no step's events take data from it.
21
+ module Nukadoko
22
+ module Engine
23
+ module Events
24
+ FORMAT_VERSION = 1
25
+ DB_OPS = %w[read insert update delete other].freeze
26
+ # The most primary keys one `ids` field holds.
27
+ IDS_CAP = 100
28
+ SAFE = 2**53 - 1
29
+ EXTENSION_PREFIX = "x_"
30
+
31
+ # One field of a kind: its type, whether the format requires it,
32
+ # whether it may hold null, and the values a string field may hold.
33
+ Field = Data.define(
34
+ :type, #: Symbol
35
+ :required, #: bool
36
+ :nullable, #: bool
37
+ :values, #: Array[String]?
38
+ )
39
+
40
+ # A Data block's methods are its own, but rbs-inline reads only a
41
+ # class body, so they are written in one.
42
+ class Field
43
+ #: (type: Symbol, required: bool, ?nullable: bool, ?values: Array[String]?) -> Field
44
+ def self.of(type:, required:, nullable: false, values: nil) = new(type:, required:, nullable:, values:)
45
+ end
46
+
47
+ KINDS = {
48
+ "request" => { "method" => Field.of(type: :string, required: true), "route" => Field.of(type: :string, required: true, nullable: true),
49
+ "status" => Field.of(type: :integer, required: true), "calls" => Field.of(type: :strings, required: false) },
50
+ "db" => { "table" => Field.of(type: :string, required: true), "op" => Field.of(type: :string, required: true, values: DB_OPS),
51
+ "rows" => Field.of(type: :integer, required: false, nullable: true), "ids" => Field.of(type: :ids, required: false),
52
+ "committed" => Field.of(type: :boolean, required: false) },
53
+ "tx" => { "id" => Field.of(type: :string, required: true), "phase" => Field.of(type: :string, required: true, values: %w[commit rollback]) },
54
+ "job" => { "name" => Field.of(type: :string, required: true), "queue" => Field.of(type: :string, required: false),
55
+ "phase" => Field.of(type: :string, required: true, values: %w[enqueue perform]), "job_id" => Field.of(type: :string, required: true),
56
+ "calls" => Field.of(type: :strings, required: false) },
57
+ "http" => { "method" => Field.of(type: :string, required: true), "origin" => Field.of(type: :string, required: true),
58
+ "path" => Field.of(type: :string, required: true), "status" => Field.of(type: :integer, required: true, nullable: true) },
59
+ "flag" => { "name" => Field.of(type: :string, required: true), "side" => Field.of(type: :string, required: true),
60
+ "gate" => Field.of(type: :string, required: false, values: %w[boolean actor percentage]) },
61
+ "error" => { "class" => Field.of(type: :string, required: true), "handled" => Field.of(type: :boolean, required: true) }
62
+ }.freeze #: Hash[String, Hash[String, Field]]
63
+
64
+ # What a line's `trace` field says: the trace id, in lowercase, and
65
+ # the span a whole `traceparent` names, nil for a bare trace id.
66
+ TraceRef = Data.define(
67
+ :trace_id, #: String
68
+ :span, #: String?
69
+ )
70
+
71
+ # What one line is: an `event`; an `extension`, a kind the writer
72
+ # made up (`x_`), kept and read for nothing; an `undefined-kind`, a
73
+ # mistake or a later version's kind; an `unknown-version`, whose
74
+ # meaning is not known; or `unreadable`, with why.
75
+ Line = Data.define(
76
+ :state, #: String
77
+ :trace, #: TraceRef?
78
+ :kind, #: String?
79
+ :object, #: Hash[String, untyped]?
80
+ :why, #: String?
81
+ )
82
+
83
+ # A Data block's methods are its own, but rbs-inline reads only a
84
+ # class body, so they are written in one.
85
+ class Line
86
+ #: (state: String, ?trace: TraceRef?, ?kind: String?, ?object: Hash[String, untyped]?, ?why: String?) -> Line
87
+ def self.of(state:, trace: nil, kind: nil, object: nil, why: nil) = new(state:, trace:, kind:, object:, why:)
88
+
89
+ #: () -> bool
90
+ def readable? = state != "unreadable"
91
+
92
+ #: () -> bool
93
+ def event? = state == "event"
94
+ end
95
+
96
+ TRACEPARENT = /\A(\h{2})-(\h{32})-(\h{16})-\h{2}\z/
97
+ BARE_TRACE_ID = /\A\h{32}\z/
98
+ ALL_ZEROS = /\A0+\z/
99
+
100
+ module_function
101
+
102
+ # A W3C `traceparent` (any version but `ff`) or a bare 32-character
103
+ # trace id, in either case, with no id of all zeros; nil otherwise.
104
+ #: (untyped) -> TraceRef?
105
+ def trace_ref_of(value)
106
+ return nil unless value.is_a?(String)
107
+
108
+ text = value.downcase
109
+ return text.match?(ALL_ZEROS) ? nil : TraceRef.new(trace_id: text, span: nil) if text.match?(BARE_TRACE_ID)
110
+
111
+ match = TRACEPARENT.match(text) or return nil
112
+ version, trace_id, span = match.captures.map(&:to_s)
113
+ return nil if version == "ff" || trace_id.to_s.match?(ALL_ZEROS) || span.to_s.match?(ALL_ZEROS)
114
+
115
+ TraceRef.new(trace_id: trace_id.to_s, span: span)
116
+ end
117
+
118
+ # The trace id of the step a line belongs to, in a system whose trace
119
+ # ids start with `prefix`, or nil: an unreadable line, or a trace the
120
+ # program made for a request nukadoko did not stamp.
121
+ #: (Line, String) -> String?
122
+ def owner_of(line, prefix)
123
+ id = line.trace&.trace_id
124
+ id&.start_with?(prefix) ? id : nil
125
+ end
126
+
127
+ # The first key one object of `text` holds twice, or nil. `text` is
128
+ # JSON that parsed, so every string and bracket is whole.
129
+ #: (String) -> String?
130
+ def repeated_key(text)
131
+ frames = [] #: Array[[Hash[String, bool]?, bool]]
132
+ at = 0
133
+ while at < text.size
134
+ char = text[at]
135
+ if char == '"'
136
+ start = at
137
+ at += 1
138
+ until text[at] == '"'
139
+ at += 1 if text[at] == "\\"
140
+ at += 1
141
+ end
142
+ top = frames.last
143
+ if top && top[0] && top[1]
144
+ key = JSON.parse(text[start..at].to_s)
145
+ return key if top[0].key?(key)
146
+
147
+ top[0][key] = true
148
+ top[1] = false
149
+ end
150
+ elsif char == "{" then frames << [{}, true]
151
+ elsif char == "[" then frames << [nil, false]
152
+ elsif char == "}" || char == "]" then frames.pop
153
+ elsif char == ","
154
+ top = frames.last
155
+ top[1] = true if top && top[0]
156
+ end
157
+ at += 1
158
+ end
159
+ nil
160
+ end
161
+
162
+ # Whether `value` is one integer JavaScript holds exactly, as a whole
163
+ # float is in its one number type.
164
+ #: (untyped) -> bool
165
+ def safe_integer?(value)
166
+ return value.abs <= SAFE if value.is_a?(Integer)
167
+
168
+ value.is_a?(Float) && value.finite? && value == value.floor && value.abs <= SAFE
169
+ end
170
+
171
+ # Why `value` does not fit `field`, or nil when it does.
172
+ #: (untyped, Field) -> String?
173
+ def field_problem(value, field)
174
+ return field.nullable ? nil : "is null" if value.nil?
175
+
176
+ case field.type
177
+ when :string
178
+ return "is not a string" unless value.is_a?(String)
179
+
180
+ field.values && !field.values&.include?(value) ? "is #{JSON.generate(value)}, which is not one of #{field.values&.join(", ")}" : nil
181
+ when :integer then safe_integer?(value) ? nil : "is not an integer"
182
+ when :number then value.is_a?(Numeric) ? nil : "is not a number"
183
+ when :boolean then [true, false].include?(value) ? nil : "is not true or false"
184
+ when :strings then value.is_a?(Array) && value.all?(String) ? nil : "is not an array of strings"
185
+ when :ids
186
+ return "is not an array of strings or integers" unless value.is_a?(Array) && value.all? { _1.is_a?(String) || safe_integer?(_1) }
187
+
188
+ value.size > IDS_CAP ? "holds #{value.size} ids, more than #{IDS_CAP}" : nil
189
+ end
190
+ end
191
+
192
+ # An integer literal past 2^53 - 1 anywhere in the parsed value.
193
+ #: (untyped) -> bool
194
+ def unsafe_integer?(value)
195
+ case value
196
+ when Integer then value.abs > SAFE
197
+ when Array then value.any? { unsafe_integer?(_1) }
198
+ when Hash then value.each_value.any? { unsafe_integer?(_1) }
199
+ else false
200
+ end
201
+ end
202
+
203
+ #: (String) -> Line
204
+ def unreadable(why) = Line.of(state: "unreadable", why: why)
205
+
206
+ # Reads one line of a system's events file, without its line feed.
207
+ #: (String) -> Line
208
+ def parse_line(text)
209
+ value = begin
210
+ JsJson.parse(text)
211
+ rescue JSON::ParserError, EncodingError
212
+ return unreadable("is not JSON")
213
+ end
214
+ return unreadable("holds an integer past 2^53 - 1; a writer writes a larger id as a string") if unsafe_integer?(value)
215
+ return unreadable("is not one JSON object") unless value.is_a?(Hash)
216
+
217
+ repeated = repeated_key(text)
218
+ return unreadable("holds the key #{JSON.generate(repeated)} twice in one object") if repeated
219
+
220
+ trace = trace_ref_of(value["trace"]) or return unreadable("has no trace that is a traceparent or a 32-character trace id")
221
+ kind = value["kind"]
222
+ return unreadable("has no kind") unless kind.is_a?(String) && !kind.empty?
223
+ return Line.of(state: "unknown-version", trace: trace, kind: kind, object: value) if value.key?("v") && !(safe_integer?(value["v"]) && value["v"] == FORMAT_VERSION)
224
+ return Line.of(state: "extension", trace: trace, kind: kind, object: value) if kind.start_with?(EXTENSION_PREFIX)
225
+
226
+ fields = KINDS[kind] or return Line.of(state: "undefined-kind", trace: trace, kind: kind, object: value)
227
+ fields.each do |name, field|
228
+ next unless field.required
229
+ return unreadable("is a #{kind} line with no #{name}") unless value.key?(name)
230
+
231
+ problem = field_problem(value[name], field)
232
+ return unreadable("is a #{kind} line whose #{name} #{problem}") if problem
233
+ end
234
+ Line.of(state: "event", trace: trace, kind: kind, object: value)
235
+ end
236
+
237
+ # The flag a `flag` event reports, `{ name:, side:, gate: }` with the
238
+ # gate nil when the line names none as text; nil for any other line.
239
+ #: (Line) -> Hash[Symbol, untyped]?
240
+ def flag_of(line)
241
+ return nil unless line.event? && line.kind == "flag"
242
+
243
+ object = line.object || {}
244
+ { name: object["name"], side: object["side"], gate: object["gate"].is_a?(String) ? object["gate"] : nil }
245
+ end
246
+
247
+ # The request a `request` event reports, `{ method:, route:, status: }`.
248
+ #: (Line) -> Hash[Symbol, untyped]?
249
+ def request_of(line)
250
+ return nil unless line.event? && line.kind == "request"
251
+
252
+ object = line.object || {}
253
+ { method: object["method"], route: object["route"], status: object["status"] }
254
+ end
255
+ end
256
+ end
257
+ end