ruby_raider 4.0.0 → 4.1.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 (78) hide show
  1. checksums.yaml +4 -4
  2. data/.github/ffmpeg/build.sh +208 -0
  3. data/.github/ffmpeg/check.sh +72 -0
  4. data/.github/ffmpeg/frames.rb +34 -0
  5. data/.github/ffmpeg/probe.sh +17 -0
  6. data/.github/workflows/ffmpeg.yml +160 -0
  7. data/README.md +226 -33
  8. data/RELEASE.md +19 -0
  9. data/lib/commands/flow_commands.rb +104 -0
  10. data/lib/generators/templates/common/read_me.tt +6 -7
  11. data/lib/generators/templates/flows/flow_helper.tt +42 -0
  12. data/lib/generators/templates/flows/run.tt +332 -0
  13. data/lib/generators/templates/helpers/video_helper.tt +1 -2
  14. data/lib/ruby_raider/ffmpeg.rb +38 -11
  15. data/lib/ruby_raider.rb +16 -0
  16. data/lib/utilities/flows/next_run.rb +61 -0
  17. data/lib/utilities/flows/notifier.rb +76 -0
  18. data/lib/utilities/flows/os/command_runner.rb +73 -0
  19. data/lib/utilities/flows/os/cron.rb +137 -0
  20. data/lib/utilities/flows/os/launchd.rb +164 -0
  21. data/lib/utilities/flows/os/linux.rb +63 -0
  22. data/lib/utilities/flows/os/systemd.rb +178 -0
  23. data/lib/utilities/flows/os/task_scheduler.rb +179 -0
  24. data/lib/utilities/flows/project.rb +170 -0
  25. data/lib/utilities/flows/run_log.rb +61 -0
  26. data/lib/utilities/flows/runner.rb +206 -0
  27. data/lib/utilities/flows/schedule.rb +221 -0
  28. data/lib/utilities/flows/schedule_store.rb +135 -0
  29. data/lib/utilities/flows/scheduler.rb +187 -0
  30. data/lib/version +1 -1
  31. data/sig/commands/flow_commands.rbs +13 -0
  32. data/sig/ruby_raider/ffmpeg.rbs +1 -0
  33. data/sig/ruby_raider.rbs +2 -0
  34. data/sig/utilities/flows/next_run.rbs +15 -0
  35. data/sig/utilities/flows/notifier.rbs +29 -0
  36. data/sig/utilities/flows/os/command_runner.rbs +27 -0
  37. data/sig/utilities/flows/os/cron.rbs +34 -0
  38. data/sig/utilities/flows/os/launchd.rbs +45 -0
  39. data/sig/utilities/flows/os/linux.rbs +27 -0
  40. data/sig/utilities/flows/os/systemd.rbs +43 -0
  41. data/sig/utilities/flows/os/task_scheduler.rbs +53 -0
  42. data/sig/utilities/flows/project.rbs +46 -0
  43. data/sig/utilities/flows/run_log.rbs +22 -0
  44. data/sig/utilities/flows/runner.rbs +35 -0
  45. data/sig/utilities/flows/schedule.rbs +61 -0
  46. data/sig/utilities/flows/schedule_store.rbs +34 -0
  47. data/sig/utilities/flows/scheduler.rbs +42 -0
  48. data/spec/commands/flow_commands_spec.rb +128 -0
  49. data/spec/generators/flow_helper_spec.rb +40 -0
  50. data/spec/generators/video_helper_spec.rb +21 -4
  51. data/spec/integration/content/gemfile_content_spec.rb +2 -2
  52. data/spec/integration/content/readme_content_spec.rb +7 -2
  53. data/spec/integration/end_to_end_spec.rb +83 -8
  54. data/spec/integration/flows/flow_project.rb +62 -0
  55. data/spec/integration/flows/run_command_spec.rb +91 -0
  56. data/spec/integration/flows/run_lifecycle_spec.rb +383 -0
  57. data/spec/utilities/ffmpeg_spec.rb +80 -7
  58. data/spec/utilities/flows/next_run_spec.rb +119 -0
  59. data/spec/utilities/flows/notifier_spec.rb +121 -0
  60. data/spec/utilities/flows/os/command_runner_spec.rb +56 -0
  61. data/spec/utilities/flows/os/cron_spec.rb +287 -0
  62. data/spec/utilities/flows/os/launchd_spec.rb +293 -0
  63. data/spec/utilities/flows/os/linux_spec.rb +149 -0
  64. data/spec/utilities/flows/os/systemd_spec.rb +329 -0
  65. data/spec/utilities/flows/os/task_scheduler_spec.rb +505 -0
  66. data/spec/utilities/flows/project_spec.rb +178 -0
  67. data/spec/utilities/flows/run_log_spec.rb +47 -0
  68. data/spec/utilities/flows/runner_spec.rb +313 -0
  69. data/spec/utilities/flows/schedule_spec.rb +233 -0
  70. data/spec/utilities/flows/schedule_store_spec.rb +137 -0
  71. data/spec/utilities/flows/scheduler_spec.rb +329 -0
  72. data/spec/utilities/video_command_spec.rb +13 -0
  73. metadata +58 -7
  74. data/docs/superpowers/plans/2026-10-25-failure-video-replay.md +0 -400
  75. data/docs/superpowers/plans/2026-10-26-parity-cleanup.md +0 -233
  76. data/docs/superpowers/plans/2026-10-28-failure-card.md +0 -295
  77. data/docs/superpowers/specs/2026-10-25-failure-video-replay-design.md +0 -214
  78. data/docs/superpowers/specs/2026-10-28-failure-card-design.md +0 -210
@@ -0,0 +1,332 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'English'
4
+ require 'fileutils'
5
+ require 'json'
6
+ require 'time'
7
+ require 'tmpdir'
8
+
9
+ # One run of a flow: a per-flow lock, a results folder and one line in .raider/flows/<name>/runs.jsonl.
10
+ # flows/flow_helper.rb starts it, so `raider flow run`, plain rspec, the desktop app and a schedule all
11
+ # leave the same record. Generated by `raider flow init`.
12
+ module RaiderFlows
13
+ module Run
14
+ NAME = /\A[a-z0-9_]{1,60}\z/.freeze
15
+ RESERVED = %w[env].freeze # .raider/flows/env is the secrets file, not a flow's log folder
16
+ INPUT = /\A[a-z][a-z0-9_]{0,39}\z/.freeze
17
+ ENV_KEY = /\A[A-Z_][A-Z0-9_]*\z/.freeze
18
+ RUN_ID = /\A[0-9a-f]{16}\z/.freeze
19
+ RESULTS_STAMP = /\A\d{8}T\d{6}Z(?:-\d+)?\z/.freeze
20
+ TRIGGERS = %w[manual schedule desktop].freeze
21
+ KEEP_LINES = 50
22
+ KEEP_RESULTS = 20
23
+ MAX_RUN_JSON_BYTES = 10 * 1024 * 1024
24
+ MAX_ENV_BYTES = 64 * 1024
25
+ MIN_SECRET = 4
26
+ ENV_FILE = '.raider/flows/env'
27
+ NOFOLLOW = defined?(File::NOFOLLOW) ? File::NOFOLLOW : 0
28
+ NONBLOCK = defined?(File::NONBLOCK) ? File::NONBLOCK : 0
29
+ ROOT = File.expand_path('../..', __dir__)
30
+
31
+ class << self
32
+ attr_reader :name, :results_dir
33
+
34
+ # At require time, before the driver or the reporter start. Exits 3 when the flow is already running.
35
+ def start!
36
+ # `rspec --dry-run` runs nothing, so it takes no lock and leaves no record
37
+ return if @name || RSpec.configuration.dry_run?
38
+
39
+ root = File.realpath(ROOT)
40
+ @name = flow_name
41
+ @root = root
42
+ @started_at = now
43
+ @secrets = []
44
+ busy! unless lock
45
+ stop_on_interrupt
46
+ # Registered as soon as the lock is held, so even a failure below leaves its line. It runs after
47
+ # RSpec and the reporter finished (run.json is written), whatever way the run ended.
48
+ at_exit { finish!(exit_status($ERROR_INFO)) }
49
+ @results_dir = new_results_dir
50
+ load_env_file
51
+ headless
52
+ end
53
+
54
+ # RSpec would finish the whole flow on a first Ctrl-C and exit! (no run log line) on a second. The first
55
+ # one ends the current step instead, so the run is recorded and spec_helper still quits the driver;
56
+ # a second one is ignored while that happens, and a third quits at once (no run log line).
57
+ def stop_on_interrupt
58
+ presses = 0
59
+ trap('INT') do
60
+ presses += 1
61
+ raise Interrupt, 'flow stopped' if presses == 1
62
+
63
+ presses == 2 ? say('stopping: press Ctrl-C again to quit at once') : exit!(130)
64
+ end
65
+ end
66
+
67
+ # RAIDER_FLOW_HEADED=1 drops a HEADLESS left in the shell; config.yml headless: true still wins
68
+ def headless
69
+ if ENV['RAIDER_FLOW_HEADED'] == '1'
70
+ ENV.delete('HEADLESS')
71
+ else
72
+ ENV['HEADLESS'] ||= 'true'
73
+ end
74
+ end
75
+
76
+ # Flow results go to flow-results/<name>/<UTC stamp>, never raider-results, and are never cleaned
77
+ def configure_reporter
78
+ return unless defined?(RaiderReporter)
79
+
80
+ RaiderReporter.configure do |reporter|
81
+ reporter.output_dir = results_dir || (@fallback_dir ||= Dir.mktmpdir('raider-flow-'))
82
+ reporter.clean_output_dir = false
83
+ end
84
+ end
85
+
86
+ def steps_started!
87
+ @steps_started = true
88
+ end
89
+
90
+ def finish!(code)
91
+ return unless @lock
92
+
93
+ append(record(code))
94
+ prune
95
+ rescue StandardError => e
96
+ say("could not write the run log: #{e.class}")
97
+ ensure
98
+ release
99
+ end
100
+
101
+ private
102
+
103
+ def now
104
+ Time.now.utc
105
+ end
106
+
107
+ def say(message)
108
+ $stderr.puts("[raider flow] #{message}") # rubocop:disable Style/StderrPuts -- -W0 must not hide these
109
+ end
110
+
111
+ def flow_name
112
+ flows = RSpec.configuration.files_to_run.select { |file| file.end_with?('_flow.rb') }
113
+ raise ArgumentError, 'run one flow at a time: rspec flows/<name>_flow.rb' unless flows.one?
114
+
115
+ name = File.basename(flows.first, '_flow.rb')
116
+ raise ArgumentError, "invalid flow name #{name.inspect}" unless NAME.match?(name) && !RESERVED.include?(name)
117
+
118
+ wanted = ENV.fetch('RAIDER_FLOW_NAME', name)
119
+ raise ArgumentError, "RAIDER_FLOW_NAME is #{wanted.inspect} but the flow is #{name.inspect}" unless wanted == name
120
+
121
+ name
122
+ end
123
+
124
+ def lock
125
+ file = File.join(private_dir('.raider/flows'), "#{name}.lock")
126
+ handle = File.open(file, File::RDWR | File::CREAT | NOFOLLOW, 0o600)
127
+ return @lock = handle if handle.flock(File::LOCK_EX | File::LOCK_NB)
128
+
129
+ handle.close
130
+ nil
131
+ end
132
+
133
+ def release
134
+ @lock&.close
135
+ @lock = nil
136
+ end
137
+
138
+ def busy!
139
+ append(base_line.merge(finished_at: iso(now), status: 'busy', results_dir: nil))
140
+ say("#{name} is already running")
141
+ exit 3
142
+ end
143
+
144
+ # A 0700 folder inside the project that is not a link
145
+ def private_dir(relative)
146
+ dir = File.join(@root, relative)
147
+ FileUtils.mkdir_p(dir)
148
+ raise IOError, "#{relative} must be a folder, not a link" unless File.lstat(dir).directory?
149
+
150
+ File.chmod(0o700, dir)
151
+ dir
152
+ end
153
+
154
+ def new_results_dir
155
+ base = File.join(@root, 'flow-results', name, now.strftime('%Y%m%dT%H%M%SZ'))
156
+ dir = base
157
+ suffix = 1
158
+ dir = "#{base}-#{suffix += 1}" while File.exist?(dir)
159
+ FileUtils.mkdir_p(dir)
160
+ dir
161
+ end
162
+
163
+ # KEY=value lines, # comments, no interpolation. Loaded only from a regular file you own with mode 600.
164
+ # RAIDER_FLOW_* keys are the wrapper's, so the file can't set them.
165
+ def load_env_file
166
+ content = read_env_file
167
+ return unless content
168
+
169
+ content.each_line.with_index(1) do |raw, number|
170
+ line = raw.dup.force_encoding(Encoding::UTF_8)
171
+ line = line.valid_encoding? ? line.strip : nil
172
+ next if line&.empty? || line&.start_with?('#')
173
+
174
+ key, value = line&.split('=', 2)&.map(&:strip)
175
+ unless value && ENV_KEY.match?(key.to_s) && !key.to_s.start_with?('RAIDER_FLOW_')
176
+ say("#{ENV_FILE} line #{number} ignored: expected KEY=value")
177
+ next
178
+ end
179
+ set_env(key.to_s, unquote(value))
180
+ end
181
+ end
182
+
183
+ def read_env_file
184
+ File.open(File.join(@root, ENV_FILE), File::RDONLY | NONBLOCK | NOFOLLOW) do |file|
185
+ stat = file.stat
186
+ return say("ignored #{ENV_FILE}: it must be a regular file you own") unless owned_file?(stat)
187
+ return say("ignored #{ENV_FILE}: permissions must be 600") unless private_mode?(stat)
188
+
189
+ file.read(MAX_ENV_BYTES).to_s
190
+ end
191
+ rescue Errno::ENOENT
192
+ nil
193
+ rescue SystemCallError
194
+ say("ignored #{ENV_FILE}: it must be a regular file you own")
195
+ end
196
+
197
+ # Windows has no POSIX owner or mode bits, so there the folder's ACLs decide who can read the file:
198
+ # keep the project under your user profile, or restrict the file with icacls
199
+ def owned_file?(stat)
200
+ stat.file? && (Gem.win_platform? || stat.uid == Process.uid)
201
+ end
202
+
203
+ def private_mode?(stat)
204
+ Gem.win_platform? || (stat.mode & 0o077).zero?
205
+ end
206
+
207
+ # A value already in the environment wins; both are kept out of the run log
208
+ def set_env(key, value)
209
+ ENV[key] = value unless ENV.key?(key)
210
+ [value, ENV.fetch(key)].each { |secret| @secrets << secret if secret.length >= MIN_SECRET }
211
+ end
212
+
213
+ def unquote(value)
214
+ quoted = value.length >= 2 && value[0] == value[-1] && ['"', "'"].include?(value[0])
215
+ quoted ? value[1...-1].to_s : value
216
+ end
217
+
218
+ def exit_status(error)
219
+ case error
220
+ when nil then 0
221
+ when SystemExit then error.status
222
+ else 1
223
+ end
224
+ end
225
+
226
+ def base_line
227
+ {
228
+ started_at: iso(@started_at),
229
+ attempt: [Integer(ENV.fetch('RAIDER_FLOW_ATTEMPT', '1'), 10, exception: false) || 1, 1].max,
230
+ trigger: TRIGGERS.include?(ENV.fetch('RAIDER_FLOW_TRIGGER', nil)) ? ENV.fetch('RAIDER_FLOW_TRIGGER') : 'manual',
231
+ run_id: RUN_ID.match?(ENV.fetch('RAIDER_FLOW_RUN_ID', '')) ? ENV.fetch('RAIDER_FLOW_RUN_ID') : nil
232
+ }.compact
233
+ end
234
+
235
+ def record(code)
236
+ status = outcome(code)
237
+ line = base_line.merge(finished_at: iso(now), status: status, results_dir: relative(results_dir))
238
+ line[:failed_step] = failed_step if status == 'failed'
239
+ line
240
+ end
241
+
242
+ def outcome(code)
243
+ statuses = RSpec.world.all_examples.map { |example| example.execution_result.status }
244
+ return 'completed' if code.zero? && statuses.include?(:passed) && !statuses.include?(:failed)
245
+ return 'failed' if @steps_started && statuses.include?(:failed)
246
+
247
+ 'setup_error'
248
+ end
249
+
250
+ # The first failed example: its line in the flow file and the recorded step, when the desktop's sidecar named it
251
+ def failed_step
252
+ example = RSpec.world.all_examples.find { |each| each.execution_result.status == :failed }
253
+ return nil unless example
254
+
255
+ number, title = recorded_step(example)
256
+ { number: number, title: redact(title || example.description), line: flow_line(example) }.compact
257
+ end
258
+
259
+ def flow_line(example)
260
+ file = example.metadata[:absolute_file_path].to_s
261
+ frame = Array(example.exception&.backtrace).find { |each| each.start_with?("#{file}:") }
262
+ frame && frame.delete_prefix("#{file}:").to_i
263
+ end
264
+
265
+ def recorded_step(example)
266
+ return nil unless results_dir
267
+
268
+ report = File.join(results_dir, 'run.json')
269
+ return nil unless File.file?(report) && File.size(report) <= MAX_RUN_JSON_BYTES
270
+
271
+ file = example.metadata[:file_path].to_s.delete_prefix('./')
272
+ result = JSON.parse(File.read(report)).fetch('results', []).find do |each|
273
+ each['file_path'] == file && each['status'] == 'failed' && each['steps'].is_a?(Hash)
274
+ end
275
+ index = result&.dig('steps', 'failed')
276
+ return nil unless index.is_a?(Integer)
277
+
278
+ [index + 1, result.dig('steps', 'items', index, 'title')]
279
+ rescue StandardError
280
+ nil
281
+ end
282
+
283
+ def redact(text)
284
+ @secrets.uniq.sort_by { |secret| -secret.length }.reduce(text.to_s) { |result, secret| result.gsub(secret, '[secret]') }
285
+ end
286
+
287
+ def append(line)
288
+ File.open(log_file, File::WRONLY | File::APPEND | File::CREAT | NOFOLLOW, 0o600) do |file|
289
+ file.flock(File::LOCK_EX)
290
+ file.write("#{JSON.generate(line)}\n")
291
+ end
292
+ end
293
+
294
+ def prune
295
+ File.open(log_file, File::RDWR | NOFOLLOW) do |file|
296
+ file.flock(File::LOCK_EX)
297
+ lines = file.read.lines
298
+ if lines.size > KEEP_LINES
299
+ file.rewind
300
+ file.truncate(0)
301
+ file.write(lines.last(KEEP_LINES).join)
302
+ end
303
+ end
304
+ prune_results
305
+ end
306
+
307
+ # Only stamp-named folders directly under flow-results/<name>, and never this run's
308
+ def prune_results
309
+ dir = File.join(@root, 'flow-results', name)
310
+ return unless File.directory?(dir) && File.realpath(dir) == dir
311
+
312
+ runs = Dir.children(dir).select do |child|
313
+ RESULTS_STAMP.match?(child) && File.lstat(File.join(dir, child)).directory?
314
+ end
315
+ old = runs.sort - runs.sort.last(KEEP_RESULTS) - [results_dir && File.basename(results_dir)]
316
+ old.each { |child| FileUtils.rm_rf(File.join(dir, child)) }
317
+ end
318
+
319
+ def log_file
320
+ File.join(private_dir(".raider/flows/#{name}"), 'runs.jsonl')
321
+ end
322
+
323
+ def relative(path)
324
+ path&.delete_prefix("#{@root}/")
325
+ end
326
+
327
+ def iso(time)
328
+ time.iso8601(3)
329
+ end
330
+ end
331
+ end
332
+ end
@@ -24,8 +24,7 @@ module VideoHelper
24
24
  <%- unless mobile? -%>
25
25
  MAX_FRAME_SECONDS = 2.0
26
26
  ENCODE_TIMEOUT = 120
27
- NO_FFMPEG = 'no ffmpeg available for this platform yet (set RAIDER_FFMPEG_PATH, or run ' \
28
- '`raider u video install` once the ffmpeg release is published)'
27
+ NO_FFMPEG = 'no ffmpeg download for this platform (set RAIDER_FFMPEG_PATH to an ffmpeg with libvpx)'
29
28
  <%- end -%>
30
29
 
31
30
  @disabled = false
@@ -14,16 +14,31 @@ module RubyRaider
14
14
  MAX_REDIRECTS = 5
15
15
  # Seconds for the whole download, redirects included.
16
16
  DOWNLOAD_TIMEOUT = 300
17
+ # The binaries are 3-5 MB; a bigger body is not ours and must not fill the disk before the checksum.
18
+ MAX_DOWNLOAD_BYTES = 64 * 1024 * 1024
17
19
 
18
- # Checksums are filled in when the RaiderHQ `ffmpeg-7.1` release is cut.
20
+ # The RaiderHQ `ffmpeg-7.1` release: FFmpeg 7.1.5, LGPL, built by .github/workflows/ffmpeg.yml
21
+ # (.github/ffmpeg/build.sh), run 42440762165. Each SHA-256 pins the exact bytes of that release's asset.
19
22
  RELEASE_BASE = 'https://github.com/RaiderHQ/ruby_raider/releases/download/ffmpeg-7.1/ffmpeg-7.1-'
20
23
  MANIFEST = {
21
24
  version: '7.1',
22
25
  assets: {
23
- 'darwin-arm64' => { url: "#{RELEASE_BASE}darwin-arm64".freeze, sha256: nil }.freeze,
24
- 'darwin-x64' => { url: "#{RELEASE_BASE}darwin-x64".freeze, sha256: nil }.freeze,
25
- 'linux-x64' => { url: "#{RELEASE_BASE}linux-x64".freeze, sha256: nil }.freeze,
26
- 'windows-x64' => { url: "#{RELEASE_BASE}windows-x64.exe".freeze, sha256: nil }.freeze
26
+ 'darwin-arm64' => {
27
+ url: "#{RELEASE_BASE}darwin-arm64".freeze,
28
+ sha256: 'e6c9240c133f22ced9f1e55fc2d0889991274e1b787c296583cb74f7242ef417'
29
+ }.freeze,
30
+ 'darwin-x64' => {
31
+ url: "#{RELEASE_BASE}darwin-x64".freeze,
32
+ sha256: 'e649ff3c5abe05700a657a12d549ee27ac53e190cd1aaee7a113765d3189e91f'
33
+ }.freeze,
34
+ 'linux-x64' => {
35
+ url: "#{RELEASE_BASE}linux-x64".freeze,
36
+ sha256: '108b685bbfba103c8f25c641fc4c21e5ea79acecd131f9ea964db959e894e7d4'
37
+ }.freeze,
38
+ 'windows-x64' => {
39
+ url: "#{RELEASE_BASE}windows-x64.exe".freeze,
40
+ sha256: 'e27c4d32675e8715a6b3260c87ed3834f959275af0412f501ed5781d5324ac1a'
41
+ }.freeze
27
42
  }.freeze
28
43
  }.freeze
29
44
 
@@ -115,12 +130,8 @@ module RubyRaider
115
130
  def handle_response(response, destination, deadline, timeout)
116
131
  case response
117
132
  when Net::HTTPSuccess
118
- File.open(destination, 'wb') do |file|
119
- response.read_body do |chunk|
120
- check_deadline(deadline, timeout)
121
- file.write(chunk)
122
- end
123
- end
133
+ check_size(response['content-length'].to_i)
134
+ write_body(response, destination, deadline, timeout)
124
135
  nil
125
136
  when Net::HTTPRedirection
126
137
  response['location'] || raise(IOError, 'redirect without Location header')
@@ -129,6 +140,22 @@ module RubyRaider
129
140
  end
130
141
  end
131
142
 
143
+ def write_body(response, destination, deadline, timeout)
144
+ written = 0
145
+ File.open(destination, 'wb') do |file|
146
+ response.read_body do |chunk|
147
+ check_deadline(deadline, timeout)
148
+ written += chunk.bytesize
149
+ check_size(written)
150
+ file.write(chunk)
151
+ end
152
+ end
153
+ end
154
+
155
+ def check_size(bytes)
156
+ raise IOError, "download larger than #{MAX_DOWNLOAD_BYTES} bytes" if bytes > MAX_DOWNLOAD_BYTES
157
+ end
158
+
132
159
  def socket_timeouts(deadline, timeout)
133
160
  left = check_deadline(deadline, timeout)
134
161
  { open_timeout: [10, left].min, read_timeout: [60, left].min }
data/lib/ruby_raider.rb CHANGED
@@ -5,11 +5,23 @@ require 'thor'
5
5
  # Lazy-load top-level command classes to reduce CLI startup time.
6
6
  autoload :ScaffoldingCommands, File.expand_path('commands/scaffolding_commands', __dir__)
7
7
  autoload :UtilityCommands, File.expand_path('commands/utility_commands', __dir__)
8
+ autoload :FlowCommands, File.expand_path('commands/flow_commands', __dir__)
8
9
 
9
10
  module RubyRaider
10
11
  class Raider < Thor
11
12
  def self.exit_on_failure? = true
12
13
 
14
+ # Thor runs a regex on every argument before any command, so invalid UTF-8 would crash it with a
15
+ # backtrace; a flow command says which argument instead and exits 2 like its other refusals
16
+ def self.start(given_args = ARGV, config = {})
17
+ bad = given_args.find { |arg| arg.is_a?(String) && !arg.valid_encoding? }
18
+ if bad && %w[flow f].include?(given_args.first)
19
+ warn("Invalid argument #{bad.inspect}: use valid UTF-8")
20
+ exit(2)
21
+ end
22
+ super
23
+ end
24
+
13
25
  no_tasks do
14
26
  def current_version = File.read(File.expand_path('version', __dir__)).strip
15
27
  end
@@ -51,6 +63,10 @@ module RubyRaider
51
63
  subcommand 'utility', UtilityCommands
52
64
  map 'u' => 'utility'
53
65
 
66
+ desc 'flow', 'Runs flows: recordings without assertions (init, run, list, schedule)'
67
+ subcommand 'flow', FlowCommands
68
+ map 'f' => 'flow'
69
+
54
70
  no_tasks do
55
71
  # -p values arrive as strings; examples must be true or false, in any case
56
72
  def generate_from_parameters(params)
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+ require_relative 'schedule'
5
+
6
+ module RubyRaider
7
+ module Flows
8
+ # When a schedule next runs, in local time, as launchd, schtasks, systemd and cron count it.
9
+ # A day, weekday or week rule whose time falls in a spring-forward gap runs at the first minute
10
+ # after the gap; one that falls in a fall-back hour runs at its first occurrence only.
11
+ # An hour rule runs at every real instant whose local minute matches, so twice in a fall-back hour.
12
+ module NextRun
13
+ WDAYS = %w[sun mon tue wed thu fri sat].freeze
14
+ # The longest stretch to search: a week rule, plus a day of slack
15
+ SEARCH_DAYS = 8
16
+ # The minutes to search for an hour rule: an hour, plus an hour of offset change
17
+ SEARCH_MINUTES = 120
18
+
19
+ module_function
20
+
21
+ def after(schedule, now)
22
+ local_now = now.getlocal
23
+ schedule.every == 'hour' ? next_minute(schedule.minute, local_now) : next_day(schedule, local_now)
24
+ end
25
+
26
+ def next_minute(minute, now)
27
+ time = Time.at(now.to_i - now.sec + 60).localtime
28
+ SEARCH_MINUTES.times do
29
+ return time if time.min == minute
30
+
31
+ time += 60
32
+ end
33
+ raise Error, "No local time with minute #{minute} after #{now}"
34
+ end
35
+
36
+ def next_day(schedule, now)
37
+ today = Date.new(now.year, now.month, now.day)
38
+ (0..SEARCH_DAYS).each do |offset|
39
+ date = today + offset
40
+ next unless schedule.days.include?(WDAYS[date.wday])
41
+
42
+ time = local(date, schedule.hour, schedule.minute)
43
+ return time if time > now
44
+ end
45
+ raise Error, "No run for #{schedule.rule_text} after #{now}"
46
+ end
47
+
48
+ # The first instant whose local wall clock reaches date hour:minute
49
+ def local(date, hour, minute)
50
+ wanted = [date.year, date.month, date.day, hour, minute]
51
+ time = Time.local(*wanted)
52
+ time += 60 while (wall(time) <=> wanted).negative?
53
+ time -= 60 until (wall(time - 60) <=> wanted).negative?
54
+ earlier = time - 3600
55
+ wall(earlier) == wanted ? earlier : time
56
+ end
57
+
58
+ def wall(time) = [time.year, time.month, time.day, time.hour, time.min]
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rbconfig'
4
+ require_relative 'project'
5
+ require_relative 'os/command_runner'
6
+
7
+ module RubyRaider
8
+ module Flows
9
+ # A desktop notification for `raider flow run --notify`. The title and message only ever travel as argv
10
+ # items after `--` (osascript, notify-send: so a title like -e is not read as an option or a script) or as
11
+ # environment values (PowerShell), so a hostile flow name or step title can't run as AppleScript or PowerShell. Never raises: a notification
12
+ # that can't be shown must not change how the run ends.
13
+ # :reek:TooManyConstants { max_constants: 7 } -- the fixed command of each OS, the message cap and the timeout
14
+ # :reek:TooManyInstanceVariables { max_instance_variables: 5 } -- the injected runner, OS, stream and PowerShell path, and the warned flag
15
+ class Notifier
16
+ MAX = 200
17
+ TIMEOUT = 15
18
+ OSASCRIPT = ['/usr/bin/osascript', '-e', 'on run argv', '-e',
19
+ 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', '--'].freeze
20
+ NOTIFY_SEND = ['notify-send', '--app-name=Ruby Raider', '--'].freeze
21
+ MARKUP = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;' }.freeze
22
+ # Reads the text from the environment and sets it as XML text nodes; one line with no double quotes, so
23
+ # Windows command-line quoting can't split it. Shown under PowerShell's own app id, which Windows accepts.
24
+ TOAST_SCRIPT = [
25
+ "$ErrorActionPreference = 'Stop'",
26
+ '$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]',
27
+ '$xml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)',
28
+ "$texts = $xml.GetElementsByTagName('text')",
29
+ '$null = $texts.Item(0).AppendChild($xml.CreateTextNode($env:RAIDER_NOTIFY_TITLE))',
30
+ '$null = $texts.Item(1).AppendChild($xml.CreateTextNode($env:RAIDER_NOTIFY_MESSAGE))',
31
+ '$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)',
32
+ "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe').Show($toast)"
33
+ ].join('; ').freeze
34
+ POWERSHELL_ARGS = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', TOAST_SCRIPT].freeze
35
+
36
+ def self.powershell = File.join(ENV.fetch('SystemRoot', 'C:\\Windows'), 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
37
+
38
+ def initialize(runner: Os::CommandRunner.new, host_os: RbConfig::CONFIG['host_os'], err: $stderr, powershell: Notifier.powershell)
39
+ @runner = runner
40
+ @host_os = host_os
41
+ @err = err
42
+ @powershell = powershell
43
+ @warned = false
44
+ end
45
+
46
+ # True when the notification was handed to the desktop
47
+ def notify(title, message)
48
+ title = clean(title)
49
+ message = clean(message)
50
+ result = case @host_os
51
+ when /darwin/ then @runner.call(*OSASCRIPT, title, message, timeout: TIMEOUT)
52
+ when /linux/ then @runner.call(*NOTIFY_SEND, title, message.gsub(/[&<>]/, MARKUP), timeout: TIMEOUT)
53
+ when /mswin|mingw|cygwin/
54
+ @runner.call(@powershell, *POWERSHELL_ARGS, env: { 'RAIDER_NOTIFY_TITLE' => title, 'RAIDER_NOTIFY_MESSAGE' => message },
55
+ timeout: TIMEOUT)
56
+ end
57
+ return false unless result
58
+ return true if result.success?
59
+
60
+ failed(result.stderr)
61
+ rescue StandardError => e
62
+ failed(e.message)
63
+ end
64
+
65
+ private
66
+
67
+ def clean(text) = Flows.printable(text)[0, MAX].to_s
68
+
69
+ def failed(reason)
70
+ @err.puts("Could not show a desktop notification: #{Flows.printable(reason.strip)}") unless @warned
71
+ @warned = true
72
+ false
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'open3'
4
+
5
+ module RubyRaider
6
+ module Flows
7
+ module Os
8
+ # Runs an OS scheduler command (launchctl, schtasks, systemctl, crontab) with no shell. Adapters
9
+ # take one, so tests pass a double and never touch the real scheduler.
10
+ class CommandRunner
11
+ MISSING = 127
12
+ TIMED_OUT = 124
13
+
14
+ # What a command printed and how it exited
15
+ class Result
16
+ attr_reader :stdout, :stderr, :exitstatus
17
+
18
+ def initialize(stdout:, stderr:, exitstatus:)
19
+ @stdout = stdout
20
+ @stderr = stderr
21
+ @exitstatus = exitstatus
22
+ freeze
23
+ end
24
+
25
+ def success? = exitstatus.zero?
26
+ end
27
+
28
+ # [command, command] as the first item keeps even a lone string out of a shell; env adds to the inherited
29
+ # one. With a timeout (seconds) a command still running then is killed and fails.
30
+ def call(*argv, stdin_data: nil, env: {}, timeout: nil)
31
+ command = argv.first.to_s
32
+ Open3.popen3(env, [command, command], *argv.drop(1).map(&:to_s)) do |stdin, stdout, stderr, wait|
33
+ readers = [stdout, stderr].map { |io| reader(io) }
34
+ feed(stdin, stdin_data)
35
+ next timed_out(command, timeout, wait) unless wait.join(timeout)
36
+
37
+ status = wait.value
38
+ Result.new(stdout: readers[0].value, stderr: readers[1].value, exitstatus: status.exitstatus || (128 + status.termsig.to_i))
39
+ end
40
+ rescue SystemCallError => e
41
+ Result.new(stdout: '', stderr: "Could not run #{command}: #{e.message}", exitstatus: MISSING)
42
+ end
43
+
44
+ private
45
+
46
+ # Read in a thread, so a full pipe can't block the command; quiet when the pipe is closed under it
47
+ def reader(io)
48
+ thread = Thread.new { io.read.to_s }
49
+ thread.report_on_exception = false
50
+ thread
51
+ end
52
+
53
+ def feed(stdin, data)
54
+ stdin.write(data.to_s)
55
+ rescue Errno::EPIPE
56
+ nil
57
+ ensure
58
+ stdin.close
59
+ end
60
+
61
+ def timed_out(command, timeout, wait)
62
+ begin
63
+ Process.kill('KILL', wait.pid)
64
+ rescue SystemCallError
65
+ nil
66
+ end
67
+ wait.join
68
+ Result.new(stdout: '', stderr: "#{command} took longer than #{timeout} s", exitstatus: TIMED_OUT)
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end