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
@@ -1,13 +1,24 @@
1
1
  # frozen_string_literal: true
2
2
  # rbs_inline: enabled
3
3
 
4
+ require "json"
4
5
  require "socket"
5
6
  require "shellwords"
6
7
  require "net/http"
8
+ require "securerandom"
9
+ require "timeout"
10
+ require "tmpdir"
11
+ require "fileutils"
12
+ require "open3"
13
+ require "pathname"
14
+ require "digest"
7
15
 
8
16
  # How the program under test starts, once per environment: an environment
9
- # is a world of its own, with its own port, directory, and process, so one
10
- # environment's state never reaches another's scenarios.
17
+ # is a system of its own, with its own port, directory, and process, so one
18
+ # environment's state never reaches another's scenarios. A system goes
19
+ # through the TypeScript engine's phases in its order: build (once per
20
+ # tree per run), prepare, serve or url, then setup. Each phase has a limit,
21
+ # and a phase past it, or one that fails, stops the system and names itself.
11
22
  module Nukadoko
12
23
  module Engine
13
24
  Environment = Data.define(
@@ -17,13 +28,90 @@ module Nukadoko
17
28
  :env_files, #: Array[String]
18
29
  )
19
30
 
31
+ # One service of a system, its environment's layer applied and each
32
+ # limit filled. `root` is the directory its commands run in, as the
33
+ # program writes it: relative to the tree's root (`.` when it writes
34
+ # none), or absolute; nil for a service with `external: true`. Whether
35
+ # it is a directory of the tree or a checkout outside it is known
36
+ # where the tree is (Program.service_code). `reach` is how the system
37
+ # reaches it: `{ kind: "serve", serve: }`, `{ kind: "url", url:,
38
+ # timeout_ms: }`, or `{ kind: "none" }`. `env` is the program's env with
39
+ # the service's own over it, its placeholders not yet filled.
40
+ ServiceRecipe = Data.define(
41
+ :name, #: String
42
+ :root, #: String?
43
+ :build, #: Array[Hash[Symbol, untyped]]
44
+ :prepare, #: Array[Hash[Symbol, untyped]]
45
+ :reach, #: Hash[Symbol, untyped]
46
+ :env, #: Hash[String, String]
47
+ :lists, #: Array[Hash[Symbol, untyped]]
48
+ )
49
+
50
+ # One environment's program, its layer over the top level applied:
51
+ # its services in the program's order, the one the steps reach, and
52
+ # what the system runs once.
53
+ Recipe = Data.define(
54
+ :services, #: Array[ServiceRecipe]
55
+ :primary, #: String
56
+ :setup, #: Hash[Symbol, untyped]?
57
+ :conditions, #: Hash[String, untyped]
58
+ # How far the code that runs with the scenarios may reach into this
59
+ # system's program: "url" refuses Nukadoko.run_command for every
60
+ # process of the system's pass, "any" allows it. The environment's
61
+ # stepsReach, else the top level's, else "any".
62
+ :steps_reach, #: String
63
+ )
64
+
65
+ class Recipe
66
+ # The service the steps reach.
67
+ #: () -> ServiceRecipe
68
+ def primary_service = services.find { _1.name == primary } || raise("no service #{primary} in the recipe")
69
+ end
70
+
20
71
  class Program
72
+ # How long a build or prepare command may run, and a setup or a url
73
+ # function take, unless the program says otherwise: a phase with no
74
+ # limit left a run waiting on a command that never ended.
75
+ DEFAULT_COMMAND_TIMEOUT_MS = 600_000
76
+ DEFAULT_SETUP_TIMEOUT_MS = 60_000
77
+ DEFAULT_URL_TIMEOUT_MS = 60_000
78
+ # How long a `lists` command may run: a list is read while the system
79
+ # waits to run its first scenario.
80
+ DEFAULT_LIST_TIMEOUT_MS = 60_000
81
+ # The most a list command may print; past it the list is not read.
82
+ LIST_OUTPUT_CAP_BYTES = 16 * 1024 * 1024
83
+ # What a placeholder names, as the TypeScript engine names them.
84
+ # `{service.<name>.url}` and `{service.<name>.port}` are another
85
+ # service's address, which every service knows before any of them
86
+ # runs a command, so two that call each other need no order.
87
+ PLACEHOLDER = /\{(port|url|dir|root|system|token|events|condition\.[A-Za-z0-9_.-]+|service\.[a-z0-9_-]+\.(?:url|port))\}/
88
+ # The placeholders an earlier release named differently, each old
89
+ # name with the name it carries now. `{world}` became `{system}` when
90
+ # one pass of a run against one program stopped sharing a word with
91
+ # the compat World. Nothing fills a name nukadoko does not know, so a
92
+ # config that still writes the old one would hand its program those
93
+ # characters as they stand: it is refused by name instead.
94
+ RENAMED_PLACEHOLDERS = { "world" => "system" }.freeze
95
+ RENAMED_PLACEHOLDER = /\{(world)\}/
96
+ # The name of the one service of a program that writes no services.
97
+ MAIN_SERVICE = "main"
98
+
21
99
  #: (Hash[Symbol, untyped]) -> void
22
100
  def initialize(options)
23
101
  @options = options
102
+ # Each tree's build runs once however many systems it serves.
103
+ @builds = {} #: Hash[String, [String, String?]]
24
104
  end
25
105
 
26
- # The worlds a run starts: each --env in the order given; without one,
106
+ # The builds this program already ran, by the directory and the
107
+ # commands: the system that ran each one, as its lines name it, and
108
+ # "failed" when it failed. A `--base` tree's pass runs in a process
109
+ # of its own, so the run hands each pass what ran before it and takes
110
+ # back what the pass ran: a checkout is the same directory in every
111
+ # tree, and builds once a run.
112
+ attr_reader :builds #: Hash[String, [String, String?]]
113
+
114
+ # The systems a run starts: each --env in the order given; without one,
27
115
  # defaultEnvironments in its order, else every environment that
28
116
  # declares conditions, else the top level under the name default.
29
117
  # default is always a name, whether or not the file defines it.
@@ -43,7 +131,7 @@ module Nukadoko
43
131
  end
44
132
  end
45
133
 
46
- # Whether the config gave a program, so each step names its world.
134
+ # Whether the config gave a program, so each step names its system.
47
135
  #: () -> bool
48
136
  def file? = !@options.empty?
49
137
 
@@ -56,6 +144,96 @@ module Nukadoko
56
144
  Environment.new(name, (e[:conditions] || {}).transform_keys(&:to_s), e[:env] || {}, Program.env_files(e))
57
145
  end
58
146
 
147
+ # A read-only environment refuses every step that declares it mutates.
148
+ #: (String) -> String?
149
+ def policy(name) = declared.dig(name, :policy)&.to_s
150
+
151
+ # The environment's version function, whose answer each record names
152
+ # as target_version.
153
+ #: (String) -> untyped
154
+ def version(name) = declared.dig(name, :version)
155
+
156
+ # The environment's fields over the top level's, service by service.
157
+ # A field the environment writes replaces the top level's, except
158
+ # env, whose keys merge with the environment's winning; a service's
159
+ # env is the program's with its own over it. serve and url are one
160
+ # choice, and an environment that writes url keeps none of the top
161
+ # level's build, prepare, or root (Program.layer_service). A program
162
+ # that writes no services is one service, main, which its top level
163
+ # and each environment write the fields of.
164
+ #: (Environment) -> Recipe
165
+ def recipe(environment)
166
+ e = declared[environment.name] || {}
167
+ env = (@options[:env] || {}).merge(environment.env)
168
+ setup = Program.setup_of(e.key?(:setup) ? e[:setup] : @options[:setup])
169
+ # stepsReach is the system's, not a service's: an environment that
170
+ # writes it replaces the top level's.
171
+ steps_reach = (e[:stepsReach] || @options[:stepsReach] || "any").to_s
172
+ services = @options[:services]
173
+ unless services.is_a?(Hash)
174
+ # Its env is the program's, which `env` already layers.
175
+ fields = ->(level) { level.slice(:build, :prepare, :serve, :url, :lists) }
176
+ main = Program.layer_service(MAIN_SERVICE, fields.(@options), fields.(e), env)
177
+ return Recipe.new(services: [main], primary: MAIN_SERVICE, setup: setup, conditions: environment.conditions, steps_reach: steps_reach)
178
+ end
179
+ overlays = (e[:services] || {}).transform_keys(&:to_s)
180
+ layered = services.map { |name, service| Program.layer_service(name.to_s, service, overlays[name.to_s], env) }
181
+ Recipe.new(services: layered, primary: (@options[:primary] || layered.first&.name || MAIN_SERVICE).to_s, setup: setup, conditions: environment.conditions,
182
+ steps_reach: steps_reach)
183
+ end
184
+
185
+ # One service, `overlay` (its environment's fields) over `top`, with
186
+ # `env`, the program's env as its environment layers it, under both.
187
+ # An environment that reaches the service at a url takes none of the
188
+ # top level's build, prepare, or root: they are for the code the top
189
+ # level starts, and a url reaches code nukadoko does not start, so an
190
+ # environment that wants a build there writes its own.
191
+ #: (String, Hash[Symbol, untyped], Hash[Symbol, untyped]?, Hash[untyped, untyped]) -> ServiceRecipe
192
+ def self.layer_service(name, top, overlay, env)
193
+ reach = (overlay && reach_of(overlay)) || reach_of(top) || { kind: "none" }
194
+ return ServiceRecipe.new(name: name, root: nil, build: [], prepare: [], reach: reach, env: {}, lists: []) if top[:external] == true
195
+
196
+ inherited = overlay&.key?(:url) ? {} : top
197
+ pick = ->(key) { overlay&.key?(key) ? overlay[key] : inherited[key] }
198
+ lists = overlay&.key?(:lists) ? overlay[:lists] : top[:lists]
199
+ ServiceRecipe.new(
200
+ name: name,
201
+ root: (pick.(:root) || ".").to_s,
202
+ build: Array(pick.(:build)).map { timed(_1, DEFAULT_COMMAND_TIMEOUT_MS) },
203
+ prepare: Array(pick.(:prepare)).map { timed(_1, DEFAULT_COMMAND_TIMEOUT_MS) },
204
+ reach: reach,
205
+ env: env.merge(top[:env] || {}).merge(overlay&.[](:env) || {}).to_h { |k, v| [k.to_s, v.to_s] },
206
+ # An environment's lists replace the top level's whole.
207
+ lists: Events::LIST_KINDS.filter_map { |kind| (entry = (lists || {})[kind.to_sym]) && { kind: kind, **timed(entry, DEFAULT_LIST_TIMEOUT_MS) } }
208
+ )
209
+ end
210
+
211
+ #: (untyped, Integer) -> Hash[Symbol, untyped]
212
+ def self.timed(entry, timeout_ms)
213
+ return { command: words(entry), timeout_ms: timeout_ms } unless entry.is_a?(Hash)
214
+
215
+ { command: words(entry[:command]), timeout_ms: entry[:timeout_ms] || timeout_ms }
216
+ end
217
+
218
+ #: (Hash[Symbol, untyped]) -> Hash[Symbol, untyped]?
219
+ def self.reach_of(fields)
220
+ return { kind: "serve", serve: fields[:serve] } if fields[:serve]
221
+
222
+ url = fields[:url]
223
+ return nil if url.nil?
224
+ return { kind: "url", url: url[:resolve], timeout_ms: url[:timeout_ms] || DEFAULT_URL_TIMEOUT_MS } if url.is_a?(Hash)
225
+
226
+ { kind: "url", url: url, timeout_ms: DEFAULT_URL_TIMEOUT_MS }
227
+ end
228
+
229
+ #: (untyped) -> Hash[Symbol, untyped]?
230
+ def self.setup_of(setup)
231
+ return nil if setup.nil?
232
+ return { run: setup[:run], timeout_ms: setup[:timeout_ms] || DEFAULT_SETUP_TIMEOUT_MS } if setup.is_a?(Hash)
233
+
234
+ { run: setup, timeout_ms: DEFAULT_SETUP_TIMEOUT_MS }
235
+ end
236
+
59
237
  # The config's envFiles, then the environment's own: later files win.
60
238
  #: (Hash[Symbol, untyped]) -> Array[String]
61
239
  def self.env_files(environment) = [*Nukadoko.config_options[:envFiles], *environment[:envFiles]].map(&:to_s)
@@ -77,82 +255,1118 @@ module Nukadoko
77
255
  end
78
256
  end
79
257
 
80
- #: (Environment, String, String) -> World
81
- def start(environment, dir, project)
82
- port = if @options[:serve]
83
- server = TCPServer.new("127.0.0.1", 0)
84
- server.addr[1].tap { server.close }
258
+ # Each placeholder a system's program names that has no value there,
259
+ # as `<where> names {<name>}, which has no value here: <why>`: build
260
+ # runs before any system exists, a system with neither serve nor url has
261
+ # no port or URL, and a condition must be one the environment declares.
262
+ # `{events}` is the file nukadoko makes only for a system it serves.
263
+ #: (Recipe) -> Array[String]
264
+ def self.placeholder_gaps(recipe) = placeholder_gap_list(recipe).map { "#{_1[:where]} names {#{_1[:name]}}, which has no value here: #{_1[:why]}" }
265
+
266
+ # The same gaps, each as the field, the placeholder, and why, service
267
+ # by service. With more than one service, each gap's field names its
268
+ # service (`services.shop.env.PORT`); a program of one service keeps
269
+ # the field alone.
270
+ #: (Recipe) -> Array[Hash[Symbol, String]]
271
+ def self.placeholder_gap_list(recipe)
272
+ named = recipe.services.size > 1
273
+ peers = recipe.services.to_h { [_1.name, _1.reach[:kind].to_s] }
274
+ recipe.services.flat_map do |service|
275
+ service_gaps(service, recipe.conditions, peers).map { named ? _1.merge(where: "services.#{service.name}.#{_1[:where]}") : _1 }
85
276
  end
86
- fill = ->(text) { placeholders(text.to_s, port, dir, environment) }
87
- # The world's env is what its program and the steps' env fixture get.
88
- env = (@options[:env] || {}).merge(environment.env).to_h { |k, v| [k.to_s, fill.(v)] }.freeze
277
+ end
278
+
279
+ # Each field of every service of `recipe` that names a renamed
280
+ # placeholder, each as the field, the name it writes, and the name it
281
+ # has now, service by service, the field named the way a gap's is. A
282
+ # name written twice in one field is one entry.
283
+ #: (Recipe) -> Array[Hash[Symbol, String]]
284
+ def self.renamed_placeholder_list(recipe)
285
+ named = recipe.services.size > 1
286
+ recipe.services.flat_map do |service|
287
+ service_fields(service).flat_map do |where, texts, _reach|
288
+ texts.flat_map { _1.scan(RENAMED_PLACEHOLDER).flatten }.uniq.map do |was|
289
+ { where: named ? "services.#{service.name}.#{where}" : where, was: was, now: RENAMED_PLACEHOLDERS.fetch(was) }
290
+ end
291
+ end
292
+ end
293
+ end
294
+
295
+ # One renamed placeholder as a sentence.
296
+ #: (Hash[Symbol, String]) -> String
297
+ def self.describe_renamed_placeholder(renamed) = "#{renamed[:where]} names {#{renamed[:was]}}, which is {#{renamed[:now]}} now"
298
+
299
+ # The edit that closes one renamed placeholder.
300
+ #: (Hash[Symbol, String], String) -> String
301
+ def self.renamed_placeholder_fix(renamed, file) = "Write {#{renamed[:now]}} in #{renamed[:where]} of #{file}, in place of {#{renamed[:was]}}."
302
+
303
+ # Every field of one service that holds text a placeholder can stand
304
+ # in, in the order the system would reach them: build, prepare,
305
+ # serve, lists, then env, each with the reach that decides what a
306
+ # placeholder there can name.
307
+ #: (ServiceRecipe) -> Array[[String, Array[String], String]]
308
+ def self.service_fields(service)
309
+ kind = service.reach[:kind]
310
+ [
311
+ *service.build.each_with_index.map { |entry, i| ["build[#{i}]", entry[:command], "build"] },
312
+ *service.prepare.each_with_index.map { |entry, i| ["prepare[#{i}]", entry[:command], kind] },
313
+ *(kind == "serve" ? [["serve.command", words(service.reach[:serve][:command]), kind]] : []),
314
+ # A lists command runs only in a system nukadoko serves.
315
+ *(kind == "serve" ? service.lists.map { ["lists.#{_1[:kind]}", _1[:command], kind] } : []),
316
+ *service.env.map { |key, value| ["env.#{key}", [value], kind] }
317
+ ]
318
+ end
319
+
320
+ # One service's gaps, in the order the system reaches its fields.
321
+ # `peers` is every service of the system, this one among them, by
322
+ # name, with its reach: what `{service.<name>.url}` can name.
323
+ #: (ServiceRecipe, Hash[String, untyped], ?Hash[String, String]) -> Array[Hash[Symbol, String]]
324
+ def self.service_gaps(service, conditions, peers = {})
325
+ service_fields(service).flat_map do |where, texts, reach|
326
+ texts.flat_map { _1.scan(PLACEHOLDER).flatten }.uniq.filter_map do |name|
327
+ why = absence(name, reach, conditions, peers)
328
+ { where: where, name: name, why: why } if why
329
+ end
330
+ end
331
+ end
332
+
333
+ URL_EVENTS_WHY = "nukadoko does not start this system's program, so it reads no file the program writes"
334
+
335
+ # The edit that closes `gap` in system `system` of `file`: it names only
336
+ # what the system lacks. Outside a build, only a system with neither
337
+ # serve nor url lacks a value, so the edit offers either one; a system
338
+ # that has one of them is never told to add the other, which the file
339
+ # refuses beside it. A condition is declared on the system's
340
+ # environment, and a system that is no entry of `environments` is sent
341
+ # to one that declares it.
342
+ #: (Hash[Symbol, String], String, String, Hash[untyped, untyped]) -> String
343
+ def self.placeholder_gap_fix(gap, system, file, environments)
344
+ where = gap[:where]
345
+ name = gap[:name]
346
+ condition = name.delete_prefix("condition.")
347
+ named = environments.transform_keys(&:to_s)
348
+ # A build field of any service, whose where names the service when
349
+ # the system has more than one.
350
+ in_build = where.match?(/(^|\.)build\[/)
351
+ if name.start_with?("condition.") && !in_build
352
+ unless named.key?(system)
353
+ declaring = named.select { |_, environment| (environment[:conditions] || environment["conditions"] || {}).transform_keys(&:to_s).key?(condition) }.keys
354
+ outside = "The default system declares no conditions, and only an environment can"
355
+ return "#{outside}; none in #{file} declares #{condition}. Declare it under conditions of an environment, or remove {#{name}} from #{where}." if declaring.empty?
356
+
357
+ return "#{outside}: #{declaring.join(", ")} #{declaring.size == 1 ? "declares" : "declare"} #{condition}. Name one with --env, or remove {#{name}} from #{where}."
358
+ end
359
+ return "Declare #{condition} under conditions of system #{system} in #{file}, or remove {#{name}} from #{where}."
360
+ end
361
+ return "Write only {root} in #{where} of #{file}, or move the command to prepare, which runs once per system." if in_build
362
+ return "Remove {#{name}} from #{where} of #{file}, or name a service of system #{system} that has serve or url." if name.start_with?("service.")
363
+ if name == "events"
364
+ # A url system is told to serve in place of its url, never beside it.
365
+ edit = gap[:why] == URL_EVENTS_WHY ? "serve system #{system} in place of its url" : "give system #{system} serve"
366
+ return "Remove {events} from #{where} of #{file}, or #{edit}: nukadoko makes the events file only for a program it starts."
367
+ end
368
+ "Remove {#{name}} from #{where} of #{file}, or give system #{system} serve or url."
369
+ end
370
+
371
+ #: (String, String, Hash[String, untyped], ?Hash[String, String]) -> String?
372
+ def self.absence(name, reach, conditions, peers = {})
373
+ return name == "root" ? nil : "build runs once per tree, before any system exists" if reach == "build"
374
+ if name.start_with?("condition.")
375
+ condition = name.delete_prefix("condition.")
376
+ return conditions.key?(condition) ? nil : %(its environment declares no condition "#{condition}" under conditions)
377
+ end
378
+ if name.start_with?("service.")
379
+ service = name.delete_prefix("service.").sub(/\.(url|port)\z/, "")
380
+ names = peers.keys
381
+ return %(the program has no service "#{service}" (#{names.size == 1 ? "its one service is" : "its services are"} #{names.join(", ")})) unless peers.key?(service)
382
+ return "service #{service} has neither serve nor url" if peers[service] == "none"
383
+
384
+ return nil
385
+ end
386
+ return "this system has neither serve nor url" if %w[port url events].include?(name) && reach == "none"
387
+ return URL_EVENTS_WHY if name == "events" && reach == "url"
388
+
389
+ nil
390
+ end
391
+
392
+ # Whether a system of the environment writes execution events:
393
+ # nukadoko serves a service of it, and that service names {events}.
394
+ #: (Environment) -> bool
395
+ def writes_events?(environment)
396
+ recipe(environment).services.any? { _1.reach[:kind] == "serve" && Program.names_placeholder?(_1, "events") }
397
+ end
398
+
399
+ # Whether a field of the service's commands or env names `{name}`.
400
+ #: (ServiceRecipe, String) -> bool
401
+ def self.names_placeholder?(service, name)
402
+ texts = [*service.prepare.flat_map { _1[:command] }, *(service.reach[:kind] == "serve" ? words(service.reach[:serve][:command]) : []), *service.env.values]
403
+ texts.any? { _1.to_s.include?("{#{name}}") }
404
+ end
405
+
406
+ # The file a served system's program appends its execution events to,
407
+ # made before its first command runs. The program writes it directly,
408
+ # so it holds whatever the program wrote, secrets included, until
409
+ # nukadoko reads and redacts it: it lives in a directory of its own
410
+ # in the machine's temporary directory, made with mode 0700, and the
411
+ # file with mode 0600, never in the run directory, which CI uploads.
412
+ # Only the redacted copies reach the run directory. The file exists
413
+ # before the program starts, so every reader opens the same file, and
414
+ # a reader can tell when the program replaced it.
415
+ #: () -> String
416
+ def self.open_events
417
+ dir = Dir.mktmpdir("nukadoko-events-")
418
+ File.chmod(0o700, dir)
419
+ path = File.join(dir, "events.jsonl")
420
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600, &:close)
421
+ EVENTS_DIRS << dir
422
+ path
423
+ end
424
+
425
+ # What a step reads as the service's env: a variable whose value names
426
+ # the events file is left out, and so is it for what `setup` reads
427
+ # with it. A step that could find that file could append a line the
428
+ # program never wrote, and a claim would read it as the program's.
429
+ #: (Service) -> Hash[String, String]
430
+ def self.step_env(service)
431
+ service.env.reject { |_, value| service.events_path && value.to_s.include?(service.events_path.to_s) }
432
+ end
433
+
434
+ # The path of the first part of `value` that JSON cannot carry, or nil
435
+ # when every part of it can. A setup's answer crosses a process
436
+ # boundary as JSON (a `--concurrency` worker reads it from the system
437
+ # it was handed), so a value that cannot make the crossing is named
438
+ # where it sits, not at the top level.
439
+ #: (untyped, ?String, ?Array[untyped]) -> String?
440
+ def self.not_json_at(value, path = "", seen = [])
441
+ case value
442
+ when nil, true, false, String then nil
443
+ when Integer then nil
444
+ when Float then value.finite? ? nil : (path.empty? ? "its top level" : path)
445
+ when Array, Hash
446
+ here = path.empty? ? "its top level" : path
447
+ return here if seen.any? { _1.equal?(value) }
448
+ return here if value.is_a?(Hash) && value.keys.any? { !_1.is_a?(String) && !_1.is_a?(Symbol) }
449
+
450
+ parts = if value.is_a?(Array)
451
+ value.each_with_index.map { |item, index| [item, "#{path}[#{index}]"] }
452
+ else
453
+ value.map { |key, item| [item, "#{path}#{key_step(key)}"] }
454
+ end
455
+ parts.each do |item, at|
456
+ found = not_json_at(item, at, [*seen, value])
457
+ return found if found
458
+ end
459
+ nil
460
+ else path.empty? ? "its top level" : path
461
+ end
462
+ end
463
+
464
+ # `.key` for a name a reader can write back, `["..."]` for one it
465
+ # cannot: the path is meant to be pasted into the setup that wrote it.
466
+ #: (untyped) -> String
467
+ def self.key_step(key)
468
+ name = key.to_s
469
+ name.match?(/\A[A-Za-z_$][A-Za-z0-9_$]*\z/) ? ".#{name}" : "[#{name.inspect}]"
470
+ end
471
+
472
+ # The message a setup gets when its answer is not JSON, or nil when it
473
+ # is.
474
+ #: (untyped) -> String?
475
+ def self.setup_result_problem(value)
476
+ at = not_json_at(value)
477
+ at && "setup returned a value that is not JSON at #{at}"
478
+ end
479
+
480
+ # A copy of the setup's answer that no later write of the setup's own
481
+ # object can change, in the shape a worker reads it in: the JSON round
482
+ # trip is the crossing itself, so a step and a worker read one value.
483
+ #: (untyped) -> untyped
484
+ def self.frozen_setup_result(value) = JSON.parse(JSON.generate(value))
485
+
486
+ # The events directories still to remove, however nukadoko ends.
487
+ EVENTS_DIRS = [] #: Array[String]
488
+ at_exit { EVENTS_DIRS.each { FileUtils.rm_rf(_1) } }
489
+
490
+ # Started, or StartFailed with the system as far as it got, and the
491
+ # message the run reports as program-start-failed. A base system that
492
+ # has no URL of its own raises Unavailable.
493
+ # `lists` reads the program's routes and flags lists in head's systems,
494
+ # as `nuka run` does; `tables` reads its tables list in a system of any
495
+ # tree, which `nuka do` leaves out when its step reads no events.
496
+ # `progress` gets one line per phase as it starts, and one when the
497
+ # system is ready, redacted, since a `{token}` can be in a command.
498
+ # `secrets` are the environment's: each service's program.log, and
499
+ # what setup and a url function print, are redacted with them and
500
+ # with the system's own.
501
+ # Each service keeps its state and its log in a directory of its own
502
+ # under `dir`. Every service's port and URL are known before any of
503
+ # them runs a command, so each can name the others in its env; every
504
+ # served service starts at once, and each waits for its own ready.
505
+ # `head_root` is head's project root, which a service's root is read
506
+ # from in every tree: `project` when absent. A base or an old tree
507
+ # sits in the run's own directory, so a checkout written as `../shop`
508
+ # names head's neighbour there too, not a directory beside the tree.
509
+ # `repository_root` is the root of the repository `head_root` is in,
510
+ # which decides whether a service's root is a directory of the tree
511
+ # or a checkout (Program.service_code): found with git when absent.
512
+ # `env_vars` is what the environment's env files define, which setup
513
+ # reads under the program's own env, so setup and a step read one env.
514
+ # `head_urls` is the key (Program.url_key) of the URL each service of
515
+ # head's system of this environment reached: a base service of the
516
+ # tree whose url function answers with head's URL is unavailable, since
517
+ # the base's code runs nowhere.
518
+ #: (Environment, String, String, ?secrets: Secrets, ?tree: String, ?lists: bool, ?tables: bool, ?progress: untyped, ?head_root: String?, ?repository_root: String?, ?env_vars: Hash[String, String], ?head_urls: Hash[String, String]) -> System
519
+ def start(environment, dir, project, secrets: Secrets.new, tree: "head", lists: false, tables: true, progress: nil, head_root: nil, repository_root: nil, env_vars: {},
520
+ head_urls: {})
521
+ recipe = self.recipe(environment)
522
+ head_root ||= project
523
+ repository_root ||= Program.repository_root_of(head_root)
524
+ label = tree == "head" ? environment.name : "#{environment.name} (#{tree})"
525
+ token = SecureRandom.hex(16)
89
526
  prefix = Trace.new_prefix
90
- unless @options[:serve]
91
- return World.new(base_url: @options[:base_url], pid: nil, log: nil, env: env, trace_prefix: prefix, log_path: nil, commands: [], timings: {})
527
+ own = Secrets.new({ "SYSTEM_TOKEN" => token }, [prefix])
528
+ shown = secrets.with(own)
529
+ # A system of one service reads as a system: its lines and its errors
530
+ # name no service.
531
+ named = recipe.services.size > 1
532
+ announce = lambda do |service, text|
533
+ line = "system #{label}: #{"#{service.name}: " if named && service}#{text}"
534
+ progress&.puts shown.redact_string(line).gsub("#{project}/", "")
535
+ end
536
+ runs = recipe.services.map do |service|
537
+ service_dir = File.join(dir, service.name)
538
+ FileUtils.mkdir_p(service_dir)
539
+ # Read in head's terms whatever the tree, so a service is the
540
+ # same kind in every system, and a checkout the same directory.
541
+ code = Program.service_code(service.root, head_root, repository_root)
542
+ # A checkout's commit, read as the system starts, before its
543
+ # build: the code the system ran, which the run's own commit does
544
+ # not name.
545
+ code = code.merge(Program.checkout_state(code[:path].to_s)) if code[:kind] == "checkout"
546
+ Service.new(name: service.name, code: code, root: Program.service_directory(code, project), dir: service_dir, base_url: nil, port: nil, pid: nil,
547
+ log: ProgramLog.new(File.join(service_dir, "program.log"), shown), env: {}, events_path: nil, commands: [], timings: {}, places: {}, listed: {},
548
+ tables: Events::NO_MARKED_TABLES, error: nil)
549
+ end
550
+ system = System.new(trace_prefix: prefix, timings: {}, secrets: own, primary: recipe.primary, services: runs, setup_result: nil, steps_reach: recipe.steps_reach)
551
+ failing = nil #: Service?
552
+ # A phase of one service: what fails names the service.
553
+ # @type var in_service: ^(Service) { () -> untyped } -> untyped
554
+ in_service = lambda do |service, &work|
555
+ failing = service
556
+ result = work.call
557
+ failing = nil
558
+ result
92
559
  end
560
+ begin
561
+ # A field that still writes a placeholder of an earlier release
562
+ # has no gap, since nukadoko fills no such name, so the program
563
+ # would be handed those characters as they stand.
564
+ old = Program.renamed_placeholder_list(recipe).first
565
+ raise StartError, Program.describe_renamed_placeholder(old) if old
93
566
 
94
- log_path = File.join(dir, "program.log")
95
- log = File.open(log_path, "w")
96
- command = fill.(@options[:serve][:command])
97
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
98
- pid = Process.spawn(env, command, out: log, err: log, pgroup: true, chdir: project)
99
- world = World.new(base_url: "http://localhost:#{port}", pid: pid, log: log, env: env, trace_prefix: prefix, log_path: log_path,
100
- commands: [{ phase: "serve", argv: Shellwords.split(command) }], timings: {})
101
- world.wait_ready(@options[:serve][:ready])
102
- world.timings[:serve_ms] = Request.since(started)
103
- world
567
+ gap = Program.placeholder_gap_list(recipe).first
568
+ raise StartError, "#{gap[:where]} names {#{gap[:name]}}, which has no value here: #{gap[:why]}" if gap
569
+
570
+ recipe.services.each_with_index do |service, index|
571
+ reach = service.reach
572
+ next unless tree == "base" && runs[index].code[:kind] == "tree" && reach[:kind] == "url" && !reach[:url].respond_to?(:call)
573
+
574
+ in_service.(runs[index]) do
575
+ raise Unavailable, "its url is a fixed URL, where head's code runs, and only a url function can say where the base's code runs"
576
+ end
577
+ end
578
+
579
+ recipe.services.each_with_index do |service, index|
580
+ run = runs[index]
581
+ in_service.(run) do
582
+ built = build(service, run, label, ->(text) { announce.(run, text) })
583
+ run.timings[:build_ms] = built if built
584
+ end
585
+ end
586
+
587
+ # The address book: the free ports are held open together, so no
588
+ # two services get the same one.
589
+ autos = recipe.services.each_index.select { recipe.services[_1].reach[:kind] == "serve" && recipe.services[_1].reach[:serve][:port] == "auto" }
590
+ autos.zip(Program.free_ports(autos.size)).each { |index, port| runs[index] = runs[index].with(port: port) }
591
+ recipe.services.each_with_index do |service, index|
592
+ next unless service.reach[:kind] == "serve"
593
+
594
+ port = service.reach[:serve][:port]
595
+ in_service.(runs[index]) { runs[index] = runs[index].with(port: Program.unanswered(port.to_i)) } unless port == "auto"
596
+ runs[index] = runs[index].with(base_url: "http://localhost:#{runs[index].port}")
597
+ end
598
+ recipe.services.each_with_index do |service, index|
599
+ next unless service.reach[:kind] == "url"
600
+
601
+ run = runs[index]
602
+ place = SetupSystem.new(name: environment.name, service: run.name, root: run.root, dir: run.dir, tree: tree, url: nil, port: nil, env: {}, services: {}, conditions: recipe.conditions.dup)
603
+ in_service.(run) do
604
+ url = reach_url(service.reach, place, tree, run.log, progress)
605
+ # Only a service of the tree runs other code for the base: a
606
+ # checkout's and an external service's are the same for both.
607
+ if tree == "base" && run.code[:kind] == "tree" && head_urls[run.name] == Program.url_key(url)
608
+ raise Unavailable, "the url function returned head's URL for the base tree; branch on `tree`"
609
+ end
610
+
611
+ runs[index] = run.with(base_url: url, port: Program.url_port(url))
612
+ end
613
+ end
614
+ # Before prepare, which may name it too.
615
+ recipe.services.each_with_index do |service, index|
616
+ runs[index] = runs[index].with(events_path: Program.open_events) if service.reach[:kind] == "serve" && Program.names_placeholder?(service, "events")
617
+ end
618
+ # Every service's address, which {service.<name>.url} and .port
619
+ # fill in any service's fields.
620
+ addresses = {} #: Hash[String, String]
621
+ runs.each do |run|
622
+ url = run.base_url
623
+ port = run.port
624
+ addresses["service.#{run.name}.url"] = url if url
625
+ addresses["service.#{run.name}.port"] = port.to_s if port
626
+ end
627
+ fills = recipe.services.each_with_index.map do |service, index|
628
+ run = runs[index]
629
+ values = addresses.merge({ "root" => run.root, "dir" => run.dir, "system" => environment.name, "token" => token, "port" => run.port&.to_s, "url" => run.base_url, "events" => run.events_path }.compact)
630
+ fill = ->(text) { Program.filled(text.to_s, values, recipe.conditions) }
631
+ runs[index] = run.with(env: service.env.transform_values { fill.(_1) }.freeze)
632
+ fill
633
+ end
634
+ system = system.with(services: runs.dup)
635
+
636
+ recipe.services.each_with_index do |service, index|
637
+ next if service.prepare.empty?
638
+
639
+ run = runs[index]
640
+ in_service.(run) do
641
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
642
+ prepares = service.prepare.map { [_1[:command].map { |word| fills[index].(word) }, _1[:timeout_ms]] }
643
+ announce.(run, "prepare started: #{prepares.map { |argv, _| Program.display(argv) }.join("; ")}")
644
+ prepares.each do |argv, timeout_ms|
645
+ run.commands << { phase: "prepare", argv: argv }
646
+ Program.run_to_end("prepare", argv, timeout_ms, run.env, run.root, run.log)
647
+ end
648
+ run.timings[:prepare_ms] = Request.since(started)
649
+ end
650
+ end
651
+
652
+ # A command is an argv array, or a string split on whitespace, as
653
+ # in the TypeScript engine; neither goes through a shell, so what
654
+ # runs does not depend on the host's shell. A program that needs
655
+ # one writes ["sh", "-c", "..."].
656
+ served = recipe.services.each_index.select { recipe.services[_1].reach[:kind] == "serve" }
657
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
658
+ served.each do |index|
659
+ run = runs[index]
660
+ serve = recipe.services[index].reach[:serve]
661
+ argv = Program.words(serve[:command]).map { fills[index].(_1) }
662
+ run.commands << { phase: "serve", argv: argv }
663
+ run.log.note "$ #{Program.display(argv)}"
664
+ announce.(run, "serve started: #{Program.display(argv)}, waiting for #{URI.join(run.base_url.to_s, serve[:ready].to_s)}")
665
+ # The program's streams stay open until the system stops, which
666
+ # waits for them.
667
+ out, = run.log.pipe
668
+ err, = run.log.pipe
669
+ begin
670
+ pid = Process.spawn(run.env, [argv.first, argv.first], *argv.drop(1), out: out, err: err, pgroup: true, chdir: run.root)
671
+ rescue SystemCallError => e
672
+ in_service.(run) { raise StartError, "serve command #{Program.display(argv)} could not start: #{e.message}" }
673
+ ensure
674
+ out.close
675
+ err.close
676
+ end
677
+ runs[index] = run.with(pid: pid)
678
+ system = system.with(services: runs.dup)
679
+ end
680
+ # Each served service waits for its own ready at once; the first
681
+ # that fails stops the start, and the rest with it.
682
+ waits = Queue.new
683
+ threads = served.map do |index|
684
+ run = runs[index]
685
+ serve = recipe.services[index].reach[:serve]
686
+ argv = Program.words(serve[:command]).map { fills[index].(_1) }
687
+ Thread.new do
688
+ run.wait_ready(serve[:ready], serve[:timeout_ms], argv)
689
+ run.timings[:serve_ms] = Request.since(started)
690
+ waits << [index, nil]
691
+ rescue StandardError => e
692
+ waits << [index, e]
693
+ end
694
+ end
695
+ served.size.times do
696
+ index, error = waits.pop
697
+ next unless error
698
+
699
+ threads.each(&:kill)
700
+ in_service.(runs[index]) { raise error }
701
+ end
702
+
703
+ if (setup = recipe.setup)
704
+ primary = system.primary_service
705
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
706
+ announce.(nil, "setup started")
707
+ primary.log.note "# setup"
708
+ # The rule holds from the start of setup, the system's first
709
+ # client, so a setup that reaches for the program's command
710
+ # line is refused where a step would be. The pass that follows
711
+ # declares it again, for the process that runs the steps.
712
+ release_reach = Reach.declare(recipe.steps_reach, environment.name)
713
+ setup_result = nil #: untyped
714
+ begin
715
+ within("setup", setup[:timeout_ms]) do
716
+ printing_to(primary.log, progress) do
717
+ services = system.services.to_h { [_1.name, Address.new(url: _1.base_url, port: _1.port, root: _1.root, dir: _1.dir, env: _1.env.dup)] }
718
+ answer = Reach.at("in setup") do
719
+ setup[:run].call(SetupSystem.new(name: environment.name, service: primary.name, root: primary.root, dir: primary.dir, tree: tree, url: primary.base_url,
720
+ port: primary.port, env: env_vars.merge(Program.step_env(primary)), services: services,
721
+ conditions: recipe.conditions.dup))
722
+ end
723
+ next if answer.nil?
724
+
725
+ problem = Program.setup_result_problem(answer)
726
+ raise StartError, problem if problem
727
+
728
+ setup_result = Program.frozen_setup_result(answer)
729
+ end
730
+ rescue StartError, Timeout::Error
731
+ raise
732
+ rescue StandardError => e
733
+ raise StartError, "setup threw: #{e.message}"
734
+ end
735
+ ensure
736
+ release_reach.call
737
+ end
738
+ system = system.with(setup_result: setup_result)
739
+ system.timings[:setup_ms] = Request.since(started)
740
+ end
741
+
742
+ # A list command that fails, passes its limit, or prints what is
743
+ # not a list fails no system: the record names why its list was not
744
+ # read, and nothing of it counts.
745
+ recipe.services.each_with_index do |service, index|
746
+ run = runs[index]
747
+ wanted = service.lists.select { _1[:kind] == "tables" ? tables : lists && tree == "head" }
748
+ next unless run.events_path && wanted.any?
749
+
750
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
751
+ places = {} #: Hash[String, Array[Hash[Symbol, untyped]]]
752
+ listed = {} #: Hash[String, Hash[Symbol, untyped]]
753
+ announce.(run, "lists started: #{wanted.map { |list| Program.display(list[:command].map { fills[index].(_1) }) }.join("; ")}")
754
+ wanted.each do |list|
755
+ list_argv = list[:command].map { fills[index].(_1) }
756
+ run.commands << { phase: "lists", argv: list_argv }
757
+ read = Program.read_list(list[:kind], list_argv, list[:timeout_ms], run.env, run.root, run.log)
758
+ if read[:problem]
759
+ listed[list[:kind]] = { entries: nil, error: read[:problem] }
760
+ else
761
+ listed[list[:kind]] = { entries: read[:entries].size, error: nil }
762
+ places[list[:kind]] = read[:entries]
763
+ end
764
+ end
765
+ run.timings[:lists_ms] = Request.since(started)
766
+ # A tables list the system did not read leaves every table's
767
+ # holding unknown, never state.
768
+ marked = if places["tables"] then Events::Lists.tables_of(places["tables"])
769
+ elsif listed["tables"] then { unread: true }
770
+ else Events::NO_MARKED_TABLES
771
+ end
772
+ runs[index] = run.with(places: places, listed: listed, tables: marked)
773
+ end
774
+ system = system.with(services: runs.dup)
775
+ if runs.any? { _1.commands.any? } || recipe.setup
776
+ if named
777
+ announce.(nil, "#{runs.map { "#{_1.name} #{_1.base_url || "with no url"}" }.join(", ")} (#{dir.delete_prefix("#{project}/")})")
778
+ else
779
+ main = runs.first
780
+ timings = main.timings.merge(system.timings)
781
+ phases = %w[build prepare serve setup lists].filter_map { |phase| (ms = timings[:"#{phase}_ms"]) && format("%s %.1fs", phase, ms / 1000.0) }
782
+ log_shown = (" (log #{main.log.path.delete_prefix("#{project}/")})" if main.log.written?)
783
+ announce.(nil, "#{[*phases, *main.base_url].join(", ")}#{log_shown}")
784
+ end
785
+ end
786
+ system
787
+ rescue Unavailable => e
788
+ system = system.with(services: runs.dup)
789
+ system.stop
790
+ system.remove_events
791
+ raise Unavailable, "#{"service #{failing.name}: " if named && failing}#{e.message}"
792
+ rescue StartError, Timeout::Error => e
793
+ system = system.with(services: runs.dup)
794
+ system.stop
795
+ # A system that did not start keeps no events: no step read any.
796
+ system.remove_events
797
+ # The log of the service that failed, or the primary's, which
798
+ # holds what setup printed.
799
+ log = (failing || system.primary_service).log
800
+ tail = log.written? ? File.readlines(log.path).last(20).join.chomp : ""
801
+ # A command the message names can hold the system's {token}.
802
+ cause = shown.redact_string(e.message)
803
+ if failing
804
+ index = runs.index { _1.name == failing.name }.to_i
805
+ runs[index] = runs[index].with(error: cause)
806
+ system = system.with(services: runs.dup)
807
+ end
808
+ cause = "service #{failing.name}: #{cause}" if named && failing
809
+ message = "the program did not start for system #{environment.name}: #{cause}#{". The end of #{log.path.delete_prefix("#{project}/")}:\n#{tail}" unless tail.empty?}"
810
+ raise StartFailed.new(message, system, cause)
811
+ end
812
+ end
813
+
814
+ # Where `root` puts a service's code, as the TypeScript engine says
815
+ # it: a directory inside the repository is part of the tree, which
816
+ # `nuka run --base` builds again from the base's tree, and one
817
+ # outside it is a checkout, the same directory whichever tree a system
818
+ # runs. Where the code is decides, rather than how the config is
819
+ # written. `root` is as the program writes it, relative to
820
+ # `tree_root` (head's project root, whichever tree a system runs, so
821
+ # a checkout is head's directory and a tree directory keeps its place
822
+ # in the tree: Program.service_directory) or absolute; nil is a
823
+ # service with `external: true`. `repository_root` is in the same
824
+ # terms as `tree_root`. A tree service's path is relative to
825
+ # `tree_root`, "." for the root itself; a checkout's is absolute.
826
+ # Pure.
827
+ #: (String?, String, String) -> Hash[Symbol, untyped]
828
+ def self.service_code(root, tree_root, repository_root)
829
+ return { kind: "external" } if root.nil?
830
+
831
+ absolute = File.expand_path(root, tree_root)
832
+ from_repository = Pathname(absolute).relative_path_from(Pathname(repository_root)).to_s
833
+ return { kind: "checkout", path: absolute } if from_repository == ".." || from_repository.start_with?("../")
834
+
835
+ from_tree = Pathname(absolute).relative_path_from(Pathname(tree_root)).to_s
836
+ { kind: "tree", path: from_tree }
837
+ end
838
+
839
+ # A checkout's commit and whether it had an uncommitted change, an
840
+ # untracked file included, from `git status --porcelain=v2 --branch`
841
+ # in it, as the TypeScript engine reads it: both nil in no
842
+ # repository, before the first commit, or when git does not answer.
843
+ # A dirty checkout fails nothing; the summary says so.
844
+ #: (String) -> Hash[Symbol, untyped]
845
+ def self.checkout_state(dir)
846
+ status, ok = Open3.capture2("git", "-C", dir, "status", "--porcelain=v2", "--branch", "--untracked-files=normal", err: File::NULL)
847
+ ok.success? ? checkout_state_of(status) : { commit: nil, dirty: nil }
848
+ rescue SystemCallError
849
+ { commit: nil, dirty: nil }
850
+ end
851
+
852
+ # The commit git's status header names, and whether a line other than
853
+ # a header follows. Pure.
854
+ #: (String) -> Hash[Symbol, untyped]
855
+ def self.checkout_state_of(status)
856
+ lines = status.lines.map(&:chomp).reject(&:empty?)
857
+ oid = lines.find { _1.start_with?("# branch.oid ") }&.delete_prefix("# branch.oid ")&.strip
858
+ return { commit: nil, dirty: nil } if oid.nil? || oid == "(initial)"
859
+
860
+ { commit: oid, dirty: lines.any? { !_1.start_with?("#") } }
861
+ end
862
+
863
+ # The directory a service's commands run in, absolute, in the tree at
864
+ # `tree_root`: a tree service's place in it, or the checkout every
865
+ # tree shares. A service nukadoko only reaches runs no command, so
866
+ # the tree's root stands in.
867
+ #: (Hash[Symbol, untyped], String) -> String
868
+ def self.service_directory(code, tree_root)
869
+ case code[:kind]
870
+ when "checkout" then code[:path].to_s
871
+ when "tree" then File.expand_path(code[:path].to_s, tree_root)
872
+ else tree_root
873
+ end
874
+ end
875
+
876
+ # The root of the git repository `tree_root` is in, in `tree_root`'s
877
+ # own terms (not resolved through a link where `tree_root` is not), or
878
+ # `tree_root` when it is in none: then every directory outside the
879
+ # tree is a checkout.
880
+ #: (String) -> String
881
+ def self.repository_root_of(tree_root)
882
+ top, status = Open3.capture2("git", "rev-parse", "--show-toplevel", chdir: tree_root, err: File::NULL)
883
+ top = top.strip
884
+ return tree_root if !status.success? || top.empty?
885
+
886
+ real = File.realpath(tree_root)
887
+ File.expand_path(Pathname(top).relative_path_from(Pathname(real)).to_s, tree_root)
888
+ rescue SystemCallError
889
+ tree_root
890
+ end
891
+
892
+ # A service of a system whose root names no directory: a checkout a
893
+ # run needs and does not have is named before anything builds, so a
894
+ # missing clone reads as one rather than as a build that failed in a
895
+ # directory that is not there.
896
+ #: (Array[[String, Recipe]], String) -> Array[Hash[Symbol, String]]
897
+ def self.missing_service_roots(systems, tree_root)
898
+ systems.flat_map do |name, recipe|
899
+ recipe.services.filter_map do |service|
900
+ root = service.root
901
+ next if root.nil? || root == "." || File.directory?(File.expand_path(root, tree_root))
902
+
903
+ { system: name, service: service.name, root: root }
904
+ end
905
+ end
906
+ end
907
+
908
+ #: (Hash[Symbol, String]) -> String
909
+ def self.describe_missing_service_root(missing) = "system #{missing[:system]}: service #{missing[:service]} runs in #{missing[:root]}, which is no directory"
910
+
911
+ #: (Hash[Symbol, String], String) -> String
912
+ def self.missing_service_root_fix(missing, file)
913
+ "Check out service #{missing[:service]}'s code at #{missing[:root]}, or point its root in #{file} at the directory that holds it."
914
+ end
915
+
916
+ # The refusal for the systems a command is about to start, before any
917
+ # of them builds: every missing root in one message, and the edit for
918
+ # the first. nil when every root is there.
919
+ #: (Array[[String, Recipe]], String, String) -> Refusal?
920
+ def self.service_root_refusal(systems, tree_root, file)
921
+ missing = missing_service_roots(systems, tree_root)
922
+ return nil if missing.empty?
923
+
924
+ Refusal.new("program-service-root-missing", "#{missing.map { describe_missing_service_root(_1) }.join("; ")}; nothing ran",
925
+ fix: missing_service_root_fix(missing.first, file))
926
+ end
927
+
928
+ # One service as setup and a step's `services` read it, its entry in
929
+ # the system's address book: where it answers, the directory its
930
+ # commands run in, its own directory, and its env, placeholders
931
+ # filled. The TypeScript engine names it ProgramService.
932
+ Address = Data.define(
933
+ :url, #: String?
934
+ :port, #: Integer?
935
+ :root, #: String
936
+ :dir, #: String
937
+ :env, #: Hash[String, String]
938
+ )
939
+
940
+ # What setup receives once its program answers, and a url function
941
+ # as it is asked, as the TypeScript engine's ProgramSystem names it.
942
+ # `service` is the service it answers for: the primary for setup.
943
+ # `services` is every service of the system by name, empty for a url
944
+ # function, which runs before every address is known.
945
+ # `env` is what the steps' env fixture holds: the environment's env
946
+ # files, then the primary service's env with its placeholders filled,
947
+ # minus the variables whose value names {events}. setup is the
948
+ # program's first client, so it reads what a step reads, down to a
949
+ # test API key an env file keeps for a shared environment.
950
+ # `conditions` are the facts a scenario's @with: and @without: tags
951
+ # name, which setup switches for the system it is making, so a
952
+ # scenario names a switch with a tag and no step branches on the
953
+ # environment.
954
+ SetupSystem = Data.define(
955
+ :name, #: String
956
+ :service, #: String
957
+ :root, #: String
958
+ :dir, #: String
959
+ :tree, #: String
960
+ :url, #: String?
961
+ :port, #: Integer?
962
+ :env, #: Hash[String, String]
963
+ :services, #: Hash[String, Address]
964
+ :conditions, #: Hash[String, untyped]
965
+ )
966
+
967
+ # Why a system did not start, in the TypeScript engine's words.
968
+ class StartError < StandardError; end
969
+
970
+ # A base system with no URL to reach: it runs no cell, and nothing failed.
971
+ class Unavailable < StandardError; end
972
+
973
+ # A system that did not start: the message program-start-failed
974
+ # carries, and the system as far as it got, which run.json names with
975
+ # its cause.
976
+ class StartFailed < StandardError
977
+ attr_reader :system #: System
978
+ attr_reader :cause_text #: String
979
+
980
+ #: (String, System, String) -> void
981
+ def initialize(message, system, cause_text)
982
+ super(message)
983
+ @system = system
984
+ @cause_text = cause_text
985
+ end
986
+ end
987
+
988
+ # argv as a shell would read it back, for a message and the log.
989
+ #: (Array[String]) -> String
990
+ def self.display(argv) = argv.map { Selection.shell_word(_1) }.join(" ")
991
+
992
+ # A command's words: an Array as written, a String split on whitespace.
993
+ #: (String | Array[String]) -> Array[String]
994
+ def self.words(command) = command.is_a?(Array) ? command.map(&:to_s) : command.to_s.split
995
+
996
+ # Each placeholder with its value; one with none is left as written,
997
+ # which placeholder_gaps has already refused.
998
+ #: (String, Hash[String, String], Hash[String, untyped]) -> String
999
+ def self.filled(text, values, conditions)
1000
+ text.gsub(PLACEHOLDER) do
1001
+ name = Regexp.last_match(1).to_s
1002
+ name.start_with?("condition.") ? conditions.fetch(name.delete_prefix("condition."), "").to_s : values.fetch(name, "{#{name}}")
1003
+ end
1004
+ end
1005
+
1006
+ # Runs one list command to its end and reads what it printed: the
1007
+ # list's entries (`{ entries: }`), or why it was not read
1008
+ # (`{ problem: }`). A failure is the list's and never the system's.
1009
+ #: (String, Array[String], Integer, Hash[String, String], String, ProgramLog) -> Hash[Symbol, untyped]
1010
+ def self.read_list(kind, argv, timeout_ms, env, root, log)
1011
+ phase = "lists.#{kind}"
1012
+ reader, writer = IO.pipe
1013
+ bytes = 0
1014
+ chunks = [] #: Array[String]
1015
+ drain = Thread.new do
1016
+ loop do
1017
+ chunk = reader.readpartial(65_536)
1018
+ bytes += chunk.bytesize
1019
+ chunks << chunk if bytes <= LIST_OUTPUT_CAP_BYTES
1020
+ end
1021
+ rescue EOFError, IOError
1022
+ nil
1023
+ end
1024
+ begin
1025
+ run_to_end(phase, argv, timeout_ms, env, root, log, out: writer)
1026
+ rescue StartError => e
1027
+ return { problem: e.message }
1028
+ ensure
1029
+ writer.close
1030
+ drain.join
1031
+ reader.close
1032
+ end
1033
+ return { problem: "#{phase} command #{display(argv)} printed more than 16 MiB" } if bytes > LIST_OUTPUT_CAP_BYTES
1034
+
1035
+ read = Events::Lists.parse(kind, chunks.join.force_encoding(Encoding::UTF_8).scrub)
1036
+ read[:problem] ? { problem: "#{phase} command #{display(argv)} printed a line that is not one entry of the list: #{read[:problem]}" } : read
1037
+ end
1038
+
1039
+ # Runs one build, prepare, or list command to its end in the tree's
1040
+ # root, its stderr in the system's log and its stdout in `out` (the
1041
+ # log unless a list reads it), its process group stopped at its limit.
1042
+ # It returns once what it printed is in the log, so the next
1043
+ # command's line comes after it.
1044
+ #: (String, Array[String], Integer, Hash[String, String], String, ProgramLog, ?out: IO?) -> void
1045
+ def self.run_to_end(phase, argv, timeout_ms, env, root, log, out: nil)
1046
+ shown = display(argv)
1047
+ log.note "$ #{shown}"
1048
+ stdout, stdout_drain = out ? [out, nil] : log.pipe
1049
+ stderr, stderr_drain = log.pipe
1050
+ begin
1051
+ begin
1052
+ pid = Process.spawn(env, [argv.first, argv.first], *argv.drop(1), out: stdout, err: stderr, pgroup: true, chdir: root)
1053
+ rescue SystemCallError => e
1054
+ raise StartError, "#{phase} command #{shown} could not start: #{e.message}"
1055
+ ensure
1056
+ stdout.close unless out
1057
+ stderr.close
1058
+ end
1059
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + (timeout_ms / 1000.0)
1060
+ loop do
1061
+ _, status = Process.waitpid2(pid, Process::WNOHANG)
1062
+ if status
1063
+ return if status.success?
1064
+
1065
+ exit = status.signaled? ? "on SIG#{Signal.signame(status.termsig.to_i)}" : "with code #{status.exitstatus}"
1066
+ raise StartError, "#{phase} command #{shown} exited #{exit}"
1067
+ end
1068
+ if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
1069
+ begin
1070
+ Process.kill("TERM", -pid)
1071
+ Process.wait(pid)
1072
+ rescue Errno::ESRCH, Errno::ECHILD, Errno::EPERM
1073
+ nil
1074
+ end
1075
+ raise StartError, "#{phase} command #{shown} did not finish within #{timeout_ms} ms (timeout_ms)"
1076
+ end
1077
+ sleep 0.05
1078
+ end
1079
+ ensure
1080
+ log.settle([stdout_drain, stderr_drain].compact)
1081
+ end
1082
+ end
1083
+
1084
+ # The port a request to `url` goes to: the one it writes, or its scheme's.
1085
+ #: (String) -> Integer
1086
+ def self.url_port(url) = URI(url).port || (url.start_with?("https:") ? 443 : 80)
1087
+
1088
+ # Why `url` cannot be a system's URL: only http: and https: reach the
1089
+ # system, and a user or a password in it would print in every record.
1090
+ # The reason never quotes the URL, for that password.
1091
+ #: (String) -> String?
1092
+ def self.url_problem(url)
1093
+ http = 'must be an http: or https: URL, such as "http://localhost:3000"'
1094
+ parsed = URI.parse(url)
1095
+ return http unless %w[http https].include?(parsed.scheme) && parsed.host && !parsed.host.empty?
1096
+ return nil unless parsed.userinfo
1097
+
1098
+ "must not hold a user or a password: every record names the system's URL; a step sends credentials itself, from an env file"
1099
+ rescue URI::InvalidURIError
1100
+ http
1101
+ end
1102
+
1103
+ # A URL as another tree's pass compares it: the same URL written two
1104
+ # ways reads as one key, and the key says nothing of what the URL
1105
+ # holds. A base tree learns head's URLs through a file in the run
1106
+ # directory, and a URL can carry a token in its query, which every
1107
+ # record redacts, so the key is a digest: the base needs only to know
1108
+ # whether its own url function answered with head's.
1109
+ #: (String) -> String
1110
+ def self.url_key(url)
1111
+ Digest::SHA256.hexdigest(URI.parse(url).normalize.to_s)
1112
+ rescue URI::InvalidURIError
1113
+ Digest::SHA256.hexdigest(url)
1114
+ end
1115
+
1116
+ # `count` free ports, each held open until all are taken, so no two
1117
+ # are the same.
1118
+ #: (Integer) -> Array[Integer]
1119
+ def self.free_ports(count)
1120
+ servers = Array.new(count) { TCPServer.new("127.0.0.1", 0) }
1121
+ servers.map { _1.addr[1] }.tap { servers.each(&:close) }
1122
+ end
1123
+
1124
+ # A port the program names is checked before it starts: one something
1125
+ # already answers on would send every request to a server nukadoko
1126
+ # did not start.
1127
+ #: (Integer) -> Integer
1128
+ def self.unanswered(port)
1129
+ begin
1130
+ TCPSocket.new("localhost", port).close
1131
+ rescue SystemCallError
1132
+ return port
1133
+ end
1134
+ raise StartError, %(something already answers on port #{port}, so every request would reach a server nukadoko did not start; stop it, or write port: "auto")
104
1135
  end
105
1136
 
106
1137
  private
107
1138
 
108
- #: (String, Integer?, String, Environment) -> String
109
- def placeholders(text, port, dir, environment)
110
- text.gsub("{port}", port.to_s).gsub("{dir}", dir).gsub(/\{condition\.([\w.-]+)\}/) do
111
- environment.conditions.fetch(Regexp.last_match(1), "").to_s
1139
+ # A service's build, once per run for its root and commands: a system
1140
+ # whose build already ran for another system waits on nothing and
1141
+ # notes it in the service's log.
1142
+ #: (ServiceRecipe, Service, String, ^(String) -> void) -> Integer?
1143
+ def build(service, run, name, announce)
1144
+ return if service.build.empty?
1145
+
1146
+ commands = service.build.map { |entry| [entry[:command].map { Program.filled(_1, { "root" => run.root }, {}) }, entry[:timeout_ms]] }
1147
+ key = JSON.generate([run.root, commands.map(&:first)])
1148
+ if (earlier = @builds[key])
1149
+ run.log.note "# build: the same commands already ran for system #{earlier[0]}"
1150
+ raise StartError, "the build failed in system #{earlier[0]}" if earlier[1]
1151
+
1152
+ return
112
1153
  end
1154
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1155
+ announce.("build started: #{commands.map { |argv, _| Program.display(argv) }.join("; ")}")
1156
+ begin
1157
+ commands.each do |argv, timeout_ms|
1158
+ run.commands << { phase: "build", argv: argv }
1159
+ Program.run_to_end("build", argv, timeout_ms, ENV.to_h, run.root, run.log)
1160
+ end
1161
+ rescue StartError
1162
+ @builds[key] = [name, "failed"]
1163
+ raise
1164
+ end
1165
+ @builds[key] = [name, nil]
1166
+ Request.since(started)
1167
+ end
1168
+
1169
+ # A url function's answer, under its limit, checked by the rule a
1170
+ # written url is checked by when the file is read. What it prints
1171
+ # goes to the log and to `progress`.
1172
+ #: (Hash[Symbol, untyped], SetupSystem, String, ProgramLog, untyped) -> String
1173
+ def reach_url(reach, place, tree, log, progress)
1174
+ url = reach[:url]
1175
+ return url.to_s unless url.respond_to?(:call)
1176
+
1177
+ answer = within("the url function", reach[:timeout_ms]) { printing_to(log, progress) { url.call(place) } }
1178
+ if answer.nil? || answer.to_s.empty?
1179
+ raise Unavailable, "its url function gave no URL for the base" if tree == "base"
1180
+
1181
+ raise StartError, "the url function gave no URL"
1182
+ end
1183
+ problem = Program.url_problem(answer.to_s)
1184
+ raise StartError, "the url function's answer #{problem}" if problem
1185
+
1186
+ answer.to_s
1187
+ end
1188
+
1189
+ # Runs a setup or a url function under its limit. Ruby's Timeout stops
1190
+ # it where it is, which the TypeScript engine cannot do.
1191
+ #: [T] (String, Integer) { (Numeric) -> T } -> T
1192
+ def within(what, timeout_ms, &)
1193
+ Timeout.timeout(timeout_ms / 1000.0, &)
1194
+ rescue Timeout::Error
1195
+ raise StartError, "#{what} did not finish within #{timeout_ms} ms (timeout_ms)"
1196
+ end
1197
+
1198
+ # Runs a setup or a url function with what it prints on $stdout and
1199
+ # $stderr sent to the log and to `progress`, line by line and
1200
+ # redacted, as the TypeScript engine sends it: the function runs in
1201
+ # nukadoko's own process, where a `{token}` it prints would reach the
1202
+ # terminal as it is, and `nuka run --json`'s stdout is the envelope.
1203
+ # A write straight to STDOUT or STDERR is not seen.
1204
+ #: [T] (ProgramLog, untyped) { () -> T } -> T
1205
+ def printing_to(log, progress)
1206
+ writer, drain = log.pipe(echo: progress)
1207
+ out = $stdout
1208
+ err = $stderr
1209
+ $stdout = writer
1210
+ $stderr = writer
1211
+ yield
1212
+ ensure
1213
+ $stdout = out if out
1214
+ $stderr = err if err
1215
+ writer&.close
1216
+ log.settle([drain]) if drain
113
1217
  end
114
1218
  end
115
1219
 
116
- # A started program: where it answers, its env, the prefix of every
117
- # trace id its steps carry, and its log. `timings` gains stop_ms at its stop.
118
- World = Data.define(
119
- :base_url, #: String
1220
+ # One started service of a system: where it answers, its env, its log,
1221
+ # and what it ran. `timings` gains each phase as it ends. `pid` is the
1222
+ # process group nukadoko serves; `events_path` the file it appends its
1223
+ # execution events to when it names {events}.
1224
+ Service = Data.define(
1225
+ :name, #: String
1226
+ :code, #: Hash[Symbol, untyped]
1227
+ :root, #: String
1228
+ :dir, #: String
1229
+ :base_url, #: String?
1230
+ :port, #: Integer?
120
1231
  :pid, #: Integer?
121
- :log, #: File?
1232
+ :log, #: ProgramLog
122
1233
  :env, #: Hash[String, String]
123
- :trace_prefix, #: String
124
- :log_path, #: String?
1234
+ :events_path, #: String?
125
1235
  :commands, #: Array[Hash[Symbol, untyped]]
126
1236
  :timings, #: Hash[Symbol, Integer]
1237
+ :places, #: Hash[String, Array[Hash[Symbol, untyped]]]
1238
+ :listed, #: Hash[String, Hash[Symbol, untyped]]
1239
+ :tables, #: Hash[Symbol, untyped]
1240
+ :error, #: String?
127
1241
  )
128
1242
 
129
- class World
130
- #: (String) -> void
131
- def wait_ready(path)
132
- uri = URI.join(base_url, path)
133
- deadline = Time.now + 30
134
- begin
135
- Net::HTTP.get_response(uri)
136
- rescue SystemCallError
137
- raise "the program did not answer #{uri} within 30s" if Time.now > deadline
1243
+ class Service
1244
+ # The service's program.log, once anything was written to it.
1245
+ #: () -> String?
1246
+ def log_path = (log.path if log.written?)
1247
+
1248
+ # Ready once `path` answers 2xx, as in the TypeScript engine: a 404 or
1249
+ # a 503 from a server still starting is not a program that can take
1250
+ # requests. A program that exits first, or never answers 2xx within
1251
+ # `timeout_ms`, stops the system.
1252
+ # A redirect is an answer, not ready: following one would let a ready
1253
+ # path that sends the check elsewhere answer for the program.
1254
+ #: (String, Integer, Array[String]) -> void
1255
+ def wait_ready(path, timeout_ms, argv)
1256
+ uri = URI.join(base_url.to_s, path)
1257
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + (timeout_ms / 1000.0)
1258
+ last = nil #: String?
1259
+ shown = Program.display(argv)
1260
+ loop do
1261
+ if pid && (status = Process.waitpid2(pid, Process::WNOHANG)&.last)
1262
+ exit = status.signaled? ? "on #{Signal.signame(status.termsig.to_i).then { "SIG#{_1}" }}" : "with code #{status.exitstatus}"
1263
+ raise Program::StartError, "serve command #{shown} exited #{exit} before #{uri} answered"
1264
+ end
1265
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
1266
+ if remaining <= 0
1267
+ raise Program::StartError, "serve command #{shown} did not answer #{uri} with a 2xx status within #{timeout_ms} ms (timeout_ms)#{"; #{last}" if last}"
1268
+ end
1269
+ begin
1270
+ response = Net::HTTP.start(uri.host.to_s, uri.port, open_timeout: [remaining, 2].min, read_timeout: [remaining, 2].min) { _1.get("#{uri.path}#{"?#{uri.query}" if uri.query}") }
1271
+ return if response.code.start_with?("2")
138
1272
 
1273
+ location = response["location"]
1274
+ last = if response.code.start_with?("3") && location
1275
+ "the last answer was #{response.code}, a redirect to #{location}, which the ready check does not follow"
1276
+ else "the last answer was #{response.code}"
1277
+ end
1278
+ rescue SystemCallError, IOError, Net::OpenTimeout, Net::ReadTimeout
1279
+ nil
1280
+ end
139
1281
  sleep 0.1
140
- retry
141
1282
  end
142
1283
  end
143
1284
 
1285
+ # Sends the service's process group SIGTERM, the first half of a stop.
144
1286
  #: () -> void
145
- def stop
146
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1287
+ def terminate
1288
+ Process.kill("TERM", -pid) if pid
1289
+ rescue Errno::ESRCH, Errno::EPERM
1290
+ nil
1291
+ end
1292
+
1293
+ # Waits for the service's process, then puts what it printed last in
1294
+ # the log before anything reads it, and closes the log.
1295
+ #: () -> void
1296
+ def finish
147
1297
  begin
148
- Process.kill("TERM", -pid) if pid
149
1298
  Process.wait(pid) if pid
150
- rescue Errno::ESRCH, Errno::ECHILD
1299
+ rescue Errno::ECHILD
151
1300
  nil
152
1301
  end
153
- log&.close
154
- timings[:stop_ms] = Request.since(started) if pid
1302
+ log.settle
1303
+ log.close
155
1304
  end
1305
+
1306
+ # Removes the events file and its directory, once its lines are read.
1307
+ #: () -> void
1308
+ def remove_events
1309
+ return unless events_path
1310
+
1311
+ dir = File.dirname(events_path.to_s)
1312
+ Program::EVENTS_DIRS.delete(dir)
1313
+ FileUtils.rm_rf(dir)
1314
+ end
1315
+ end
1316
+
1317
+ # A started program: the prefix of every trace id its steps carry, its
1318
+ # services, and the one the steps reach. `timings` gains setup_ms, and
1319
+ # stop_ms at its stop. `secrets` are the system's own, its {token} as
1320
+ # SYSTEM_TOKEN and its trace ids kept, which every record redacts with.
1321
+ System = Data.define(
1322
+ :trace_prefix, #: String
1323
+ :timings, #: Hash[Symbol, Integer]
1324
+ :secrets, #: Secrets
1325
+ :primary, #: String
1326
+ :services, #: Array[Service]
1327
+ # What the system's setup gave back, which the setup_result fixture
1328
+ # hands a step; nil for a system whose program declares no setup, or
1329
+ # whose setup gave nothing back. One value per system.
1330
+ :setup_result, #: untyped
1331
+ # What the system declares with stepsReach, which the pass holds every
1332
+ # step, fixture, and hook to: "url" or "any".
1333
+ :steps_reach, #: String
1334
+ )
1335
+
1336
+ class System
1337
+ # The service the steps reach.
1338
+ #: () -> Service
1339
+ def primary_service = services.find { _1.name == primary } || raise("no service #{primary} in the system")
1340
+
1341
+ # Each service with a URL as a step's trace reaches it, in the
1342
+ # program's order: a request to a stamped one gets the step's
1343
+ # traceparent. A service with `external: true` is a third party's,
1344
+ # which nukadoko sends no header it did not expect.
1345
+ #: () -> Array[Hash[Symbol, untyped]]
1346
+ def trace_origins = services.select(&:base_url).map { { url: _1.base_url.to_s, service: _1.name, stamped: _1.code[:kind] != "external" } }
1347
+
1348
+ # Each service with a URL by name: the reader of its log, or nil for
1349
+ # one at a `url`, whose log nukadoko does not read.
1350
+ #: () -> Hash[String, Trace::Log?]
1351
+ def program_logs
1352
+ services.select(&:base_url).to_h do |service|
1353
+ path = service.pid && service.log_path
1354
+ [service.name, path ? Trace::Log.new(path, trace_prefix, service.name) : nil]
1355
+ end
1356
+ end
1357
+
1358
+ # Every service's process group gets SIGTERM at once, and the stop
1359
+ # waits for each.
1360
+ #: () -> void
1361
+ def stop
1362
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1363
+ services.each(&:terminate)
1364
+ services.each(&:finish)
1365
+ timings[:stop_ms] = Request.since(started) if services.any?(&:pid)
1366
+ end
1367
+
1368
+ #: () -> void
1369
+ def remove_events = services.each(&:remove_events)
156
1370
  end
157
1371
  end
158
1372
  end