ruby_raider 4.0.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/e2e_tests.yml +3 -0
  3. data/README.md +58 -1
  4. data/RELEASE.md +25 -0
  5. data/lib/commands/schedule_commands.rb +84 -0
  6. data/lib/generators/templates/common/git_ignore.tt +1 -0
  7. data/lib/ruby_raider/runtime/retry_reset.rb +32 -0
  8. data/lib/ruby_raider/runtime/rspec.rb +1 -0
  9. data/lib/ruby_raider/runtime/show_browser.rb +53 -0
  10. data/lib/ruby_raider/runtime.rb +2 -0
  11. data/lib/ruby_raider.rb +31 -0
  12. data/lib/utilities/schedules/adapter.rb +22 -0
  13. data/lib/utilities/schedules/base.rb +27 -0
  14. data/lib/utilities/schedules/kind.rb +74 -0
  15. data/lib/utilities/schedules/legacy.rb +196 -0
  16. data/lib/utilities/schedules/legacy_stub.rb +62 -0
  17. data/lib/utilities/schedules/next_run.rb +61 -0
  18. data/lib/utilities/schedules/notifier.rb +76 -0
  19. data/lib/utilities/schedules/os/command_runner.rb +73 -0
  20. data/lib/utilities/schedules/os/cron.rb +147 -0
  21. data/lib/utilities/schedules/os/launchd.rb +182 -0
  22. data/lib/utilities/schedules/os/linux.rb +81 -0
  23. data/lib/utilities/schedules/os/systemd.rb +194 -0
  24. data/lib/utilities/schedules/os/task_scheduler.rb +195 -0
  25. data/lib/utilities/schedules/os_enumerator.rb +30 -0
  26. data/lib/utilities/schedules/project.rb +70 -0
  27. data/lib/utilities/schedules/rule.rb +162 -0
  28. data/lib/utilities/schedules/run_lock.rb +160 -0
  29. data/lib/utilities/schedules/run_log.rb +122 -0
  30. data/lib/utilities/schedules/run_report.rb +139 -0
  31. data/lib/utilities/schedules/run_wrapper.rb +216 -0
  32. data/lib/utilities/schedules/schedule.rb +89 -0
  33. data/lib/utilities/schedules/schedule_store.rb +53 -0
  34. data/lib/utilities/schedules/scheduler.rb +178 -0
  35. data/lib/utilities/schedules/scheduler_steps.rb +69 -0
  36. data/lib/utilities/schedules/selection.rb +133 -0
  37. data/lib/utilities/schedules/spawn.rb +68 -0
  38. data/lib/utilities/schedules/store.rb +139 -0
  39. data/lib/version +1 -1
  40. data/ruby_raider.gemspec +1 -0
  41. data/sig/commands/schedule_commands.rbs +12 -0
  42. data/sig/ruby_raider/runtime/retry_reset.rbs +7 -0
  43. data/sig/ruby_raider/runtime/show_browser.rbs +27 -0
  44. data/sig/ruby_raider.rbs +6 -0
  45. data/sig/utilities/schedules/adapter.rbs +5 -0
  46. data/sig/utilities/schedules/base.rbs +15 -0
  47. data/sig/utilities/schedules/kind.rbs +32 -0
  48. data/sig/utilities/schedules/legacy.rbs +45 -0
  49. data/sig/utilities/schedules/legacy_stub.rbs +15 -0
  50. data/sig/utilities/schedules/next_run.rbs +15 -0
  51. data/sig/utilities/schedules/notifier.rbs +29 -0
  52. data/sig/utilities/schedules/os/command_runner.rbs +27 -0
  53. data/sig/utilities/schedules/os/cron.rbs +34 -0
  54. data/sig/utilities/schedules/os/launchd.rbs +46 -0
  55. data/sig/utilities/schedules/os/linux.rbs +33 -0
  56. data/sig/utilities/schedules/os/systemd.rbs +44 -0
  57. data/sig/utilities/schedules/os/task_scheduler.rbs +56 -0
  58. data/sig/utilities/schedules/os_enumerator.rbs +12 -0
  59. data/sig/utilities/schedules/project.rbs +22 -0
  60. data/sig/utilities/schedules/rule.rbs +72 -0
  61. data/sig/utilities/schedules/run_lock.rbs +29 -0
  62. data/sig/utilities/schedules/run_log.rbs +33 -0
  63. data/sig/utilities/schedules/run_report.rbs +34 -0
  64. data/sig/utilities/schedules/run_wrapper.rbs +45 -0
  65. data/sig/utilities/schedules/schedule.rbs +27 -0
  66. data/sig/utilities/schedules/schedule_store.rbs +21 -0
  67. data/sig/utilities/schedules/scheduler.rbs +49 -0
  68. data/sig/utilities/schedules/scheduler_steps.rbs +22 -0
  69. data/sig/utilities/schedules/selection.rbs +36 -0
  70. data/sig/utilities/schedules/spawn.rbs +10 -0
  71. data/sig/utilities/schedules/store.rbs +39 -0
  72. data/spec/commands/schedule_commands_spec.rb +284 -0
  73. data/spec/integration/content/common_content_spec.rb +8 -2
  74. data/spec/integration/content/gemfile_content_spec.rb +2 -2
  75. data/spec/runtime/retry_reset_spec.rb +112 -0
  76. data/spec/runtime/show_browser_project_spec.rb +70 -0
  77. data/spec/runtime/show_browser_spec.rb +101 -0
  78. data/spec/utilities/schedules/kind_spec.rb +81 -0
  79. data/spec/utilities/schedules/legacy_spec.rb +433 -0
  80. data/spec/utilities/schedules/legacy_stub_spec.rb +144 -0
  81. data/spec/utilities/schedules/next_run_spec.rb +119 -0
  82. data/spec/utilities/schedules/notifier_spec.rb +120 -0
  83. data/spec/utilities/schedules/os/command_runner_spec.rb +55 -0
  84. data/spec/utilities/schedules/os/cron_spec.rb +292 -0
  85. data/spec/utilities/schedules/os/launchd_spec.rb +306 -0
  86. data/spec/utilities/schedules/os/linux_spec.rb +163 -0
  87. data/spec/utilities/schedules/os/list_ids_spec.rb +202 -0
  88. data/spec/utilities/schedules/os/systemd_spec.rb +333 -0
  89. data/spec/utilities/schedules/os/task_scheduler_spec.rb +511 -0
  90. data/spec/utilities/schedules/os_entry_spec.rb +54 -0
  91. data/spec/utilities/schedules/os_enumerator_spec.rb +57 -0
  92. data/spec/utilities/schedules/project_spec.rb +125 -0
  93. data/spec/utilities/schedules/run_lock_spec.rb +143 -0
  94. data/spec/utilities/schedules/run_log_spec.rb +83 -0
  95. data/spec/utilities/schedules/run_report_spec.rb +150 -0
  96. data/spec/utilities/schedules/run_wrapper_integration_spec.rb +166 -0
  97. data/spec/utilities/schedules/run_wrapper_spec.rb +430 -0
  98. data/spec/utilities/schedules/schedule_spec.rb +120 -0
  99. data/spec/utilities/schedules/schedule_store_spec.rb +151 -0
  100. data/spec/utilities/schedules/scheduler_launchd_spec.rb +77 -0
  101. data/spec/utilities/schedules/scheduler_spec.rb +445 -0
  102. data/spec/utilities/schedules/selection_spec.rb +176 -0
  103. data/spec/utilities/schedules/spawn_spec.rb +104 -0
  104. metadata +106 -2
@@ -0,0 +1,333 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tmpdir'
4
+ require_relative '../../../../lib/utilities/schedules/os/systemd'
5
+ require_relative '../../../../lib/utilities/schedules/schedule'
6
+
7
+ # The fake runner, temp home and project folders sit next to the adapter under test
8
+ # rubocop:disable RSpec/MultipleMemoizedHelpers
9
+ RSpec.describe RubyRaider::Schedules::Os::Systemd do # rubocop:disable RSpec/FilePath
10
+ # Records every command and answers from a table keyed by the systemctl verb; never runs anything
11
+ let(:fake_runner_class) do
12
+ Class.new do
13
+ attr_reader :calls, :answers
14
+
15
+ def initialize
16
+ @calls = []
17
+ @answers = {}
18
+ end
19
+
20
+ def call(*argv, stdin_data: nil)
21
+ @calls << argv
22
+ @seen&.call(argv, stdin_data)
23
+ stderr, status = answers.fetch(argv[2], ['', 0])
24
+ RubyRaider::Schedules::Os::CommandRunner::Result.new(stdout: '', stderr: stderr, exitstatus: status)
25
+ end
26
+
27
+ def on_call(&block) = @seen = block
28
+ end
29
+ end
30
+
31
+ let(:hostile) { %q('; rm -rf ~; ' </string> %h $(id) " \\ &) }
32
+ let(:tmp) { File.realpath(Dir.mktmpdir('schedules-systemd')) }
33
+ let(:home) { File.join(tmp, 'home') }
34
+ let(:project_dir) { File.join(tmp, 'plain') }
35
+ let(:runner) { fake_runner_class.new }
36
+ let(:systemd) { described_class.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner, home: home, config_home: nil) }
37
+ let(:now) { Time.utc(2026, 11, 9, 10, 0, 0) }
38
+ let(:units) { File.join(home, '.config', 'systemd', 'user') }
39
+
40
+ def schedule(dir: project_dir, gem_env: {}, bundle: '/opt/ruby/bin/bundle', **options)
41
+ FileUtils.mkdir_p(dir)
42
+ # Hermetic: the GEM_HOME/GEM_PATH and bundle this spec runs with never reach the entry; a spec passes its own
43
+ allow(RubyRaider::Schedules::Schedule).to receive_messages(captured_gem_env: gem_env, bundle_path: bundle)
44
+ project = RubyRaider::Schedules::Project.new(File.realpath(dir))
45
+ RubyRaider::Schedules::Schedule.build(project: project, name: 'report', every: 'day', at: '08:00', now: now, **options)
46
+ end
47
+
48
+ # systemd's specifier rule for a raw value: %% is %, any other % would be a specifier
49
+ def unspecify(text)
50
+ text.gsub(/%(.?)/m) do
51
+ raise ArgumentError, "specifier %#{Regexp.last_match(1)} in #{text.inspect}" unless Regexp.last_match(1) == '%'
52
+
53
+ '%'
54
+ end
55
+ end
56
+
57
+ # Splits a value the way systemd reads ExecStart= (dollars: true) or Environment= (dollars: false): words
58
+ # separated by spaces, each in double quotes with \\ and \" as the only C escapes, %% for %, and in ExecStart
59
+ # $$ for $. Strict: anything else raises, so a value that would be expanded or misread fails the spec.
60
+ # :reek:TooManyStatements
61
+ def systemd_words(text, dollars:)
62
+ words = []
63
+ rest = text.dup
64
+ until rest.empty?
65
+ raise ArgumentError, "unquoted word at #{rest.inspect}" unless rest.start_with?('"')
66
+
67
+ word = +''
68
+ index = 1
69
+ loop do
70
+ char = rest[index] or raise ArgumentError, 'unterminated quote'
71
+ index += 1
72
+ break if char == '"'
73
+
74
+ if char == '\\'
75
+ escaped = rest[index]
76
+ raise ArgumentError, "C escape \\#{escaped}" unless ['\\', '"'].include?(escaped)
77
+
78
+ word << escaped
79
+ index += 1
80
+ elsif char == '%' || (dollars && char == '$')
81
+ raise ArgumentError, "lone #{char}" unless rest[index] == char
82
+
83
+ word << char
84
+ index += 1
85
+ else
86
+ word << char
87
+ end
88
+ end
89
+ words << word
90
+ rest = rest[index..].sub(/\A /, '')
91
+ end
92
+ words
93
+ end
94
+
95
+ def value_of(text, key) = text.lines.map(&:chomp).select { |line| line.start_with?("#{key}=") }.map { |line| line.delete_prefix("#{key}=") }
96
+
97
+ def service_path(item) = File.join(units, "#{item.os_id}.service")
98
+
99
+ def timer_path(item) = File.join(units, "#{item.os_id}.timer")
100
+
101
+ after { FileUtils.rm_rf(tmp) }
102
+
103
+ it 'is called systemd in messages and has no missed runs note' do
104
+ expect([systemd.label, systemd.missed_runs_note]).to eq(['systemd', nil])
105
+ end
106
+
107
+ describe '#service' do
108
+ it 'writes the exact unit for a daily schedule' do
109
+ item = schedule
110
+ exec = item.argv.map { |arg| %("#{arg}") }.join(' ')
111
+ env = item.env.map { |key, value| %(Environment="#{key}=#{value}"\n) }.join
112
+
113
+ expect(systemd.service(item)).to eq(<<~UNIT)
114
+ [Unit]
115
+ Description=raider schedule report
116
+
117
+ [Service]
118
+ Type=oneshot
119
+ WorkingDirectory=#{item.working_directory}
120
+ #{env.chomp}
121
+ ExecStart=#{exec}
122
+ StandardOutput=append:#{item.log_path}
123
+ StandardError=append:#{item.log_path}
124
+ UNIT
125
+ end
126
+
127
+ it 'keeps GEM_HOME and GEM_PATH in the environment when they were captured' do
128
+ item = schedule(gem_env: { 'GEM_HOME' => '/g/%h$x', 'GEM_PATH' => '/g/path' })
129
+
130
+ lines = value_of(systemd.service(item), 'Environment').flat_map { |value| systemd_words(value, dollars: false) }
131
+
132
+ expect(lines.last(3)).to eq(['LANG=en_US.UTF-8', 'GEM_HOME=/g/%h$x', 'GEM_PATH=/g/path'])
133
+ end
134
+
135
+ describe 'with hostile values in the bundle path, GEM_HOME and the project path' do
136
+ let(:item) do
137
+ schedule(dir: File.join(tmp, "p#{hostile}<", "string> #{hostile}"), bundle: "/opt/#{hostile}/bundle", gem_env: { 'GEM_HOME' => "/g/#{hostile}" })
138
+ end
139
+ let(:text) { systemd.service(item) }
140
+
141
+ it 'gives back the exact argv from ExecStart' do
142
+ argv = systemd_words(value_of(text, 'ExecStart').first, dollars: true)
143
+
144
+ expect(argv).to eq(item.argv)
145
+ expect(argv[1]).to eq("/opt/#{hostile}/bundle")
146
+ expect(item.working_directory).to include('</string>', "'; rm -rf ~; '", '$(id)', '%h', '"', '\\', '&', ' ')
147
+ end
148
+
149
+ it 'gives back the exact paths and environment' do
150
+ env = value_of(text, 'Environment').flat_map { |value| systemd_words(value, dollars: false) }
151
+
152
+ expect([unspecify(value_of(text, 'WorkingDirectory').first), value_of(text, 'StandardOutput').map { |value| unspecify(value) }])
153
+ .to eq([item.working_directory, ["append:#{item.log_path}"]])
154
+ expect(env).to eq(item.env.map { |key, value| "#{key}=#{value}" })
155
+ end
156
+
157
+ it 'writes them only in escaped form' do
158
+ expect(text).to include('%%h', '$$(id)', '\\" \\\\ &')
159
+ expect(text.scan(/(?<!%)%(?!%)/)).to be_empty
160
+ expect(text.lines.length).to eq(systemd.service(schedule(gem_env: { 'GEM_HOME' => '/g' })).lines.length)
161
+ end
162
+ end
163
+ end
164
+
165
+ describe '#timer' do
166
+ it 'writes the exact timer for a daily schedule' do
167
+ expect(systemd.timer(schedule)).to eq(<<~UNIT)
168
+ [Unit]
169
+ Description=raider schedule report schedule
170
+
171
+ [Timer]
172
+ OnCalendar=*-*-* 08:00:00
173
+ Persistent=true
174
+
175
+ [Install]
176
+ WantedBy=timers.target
177
+ UNIT
178
+ end
179
+
180
+ it 'turns each rule into OnCalendar' do
181
+ rules = [schedule(every: 'hour', at: ':15'), schedule(every: 'weekday', at: '18:05'), schedule(every: 'week', on: 'sun', at: '07:30')]
182
+
183
+ expect(rules.map { |item| value_of(systemd.timer(item), 'OnCalendar').first })
184
+ .to eq(['*-*-* *:15:00', 'Mon..Fri *-*-* 18:05:00', 'Sun *-*-* 07:30:00'])
185
+ end
186
+ end
187
+
188
+ describe '#install' do
189
+ it 'writes both units 0644, reloads, then enables the timer' do
190
+ item = schedule
191
+
192
+ systemd.install(item)
193
+
194
+ expect(runner.calls).to eq([%w[systemctl --user daemon-reload], ['systemctl', '--user', 'enable', '--now', "#{item.os_id}.timer"]])
195
+ expect([File.read(service_path(item)), File.read(timer_path(item))]).to eq([systemd.service(item), systemd.timer(item)])
196
+ expect([service_path(item), timer_path(item)].map { |path| format('%o', File.stat(path).mode & 0o777) }).to eq(%w[644 644])
197
+ expect(Dir.children(units).sort).to eq([File.basename(service_path(item)), File.basename(timer_path(item))])
198
+ end
199
+
200
+ it 'uses an absolute XDG_CONFIG_HOME and ignores a relative one' do
201
+ item = schedule
202
+ config = File.join(tmp, 'xdg')
203
+ described_class.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner, home: home, config_home: config).install(item)
204
+ described_class.new(kind: RubyRaider::Schedules::Kind::TESTS, runner: runner, home: home, config_home: 'relative').install(item)
205
+
206
+ expect([File.exist?(File.join(config, 'systemd', 'user', "#{item.os_id}.timer")), File.exist?(timer_path(item))]).to eq([true, true])
207
+ end
208
+
209
+ it 'replaces existing units' do
210
+ item = schedule
211
+ FileUtils.mkdir_p(units)
212
+ File.write(service_path(item), 'old')
213
+ File.write(timer_path(item), 'old')
214
+
215
+ systemd.install(item)
216
+
217
+ expect([File.read(service_path(item)), File.read(timer_path(item))]).to eq([systemd.service(item), systemd.timer(item)])
218
+ end
219
+
220
+ it 'removes both units, reloads and raises with the scheduler error when enable fails' do
221
+ item = schedule
222
+ runner.answers['enable'] = ["Failed to enable unit\e[2J\n", 1]
223
+
224
+ expect { systemd.install(item) }.to raise_error(RubyRaider::Schedules::Error, /systemd could not enable .*Failed to enable unit\?\[2J/)
225
+ expect(runner.calls.map { |argv| argv[2] }).to eq(%w[daemon-reload enable disable daemon-reload])
226
+ expect(runner.calls[2]).to eq(['systemctl', '--user', 'disable', "#{item.os_id}.timer"])
227
+ expect(Dir.children(units)).to be_empty
228
+ end
229
+
230
+ it 'removes both units when the first reload fails' do
231
+ item = schedule
232
+ runner.answers['daemon-reload'] = ['Failed to connect to bus', 1]
233
+
234
+ expect { systemd.install(item) }.to raise_error(RubyRaider::Schedules::Error, /Failed to connect to bus/)
235
+ expect(Dir.children(units)).to be_empty
236
+ end
237
+
238
+ it 'refuses a project path systemd can not keep, before writing anything' do
239
+ ['trailing ', 'tab\\'].each do |name|
240
+ item = schedule(dir: File.join(tmp, name))
241
+
242
+ expect { systemd.install(item) }.to raise_error(RubyRaider::Schedules::Error, /systemd can not use the path/)
243
+ end
244
+ expect([runner.calls, File.exist?(units)]).to eq([[], false])
245
+ end
246
+
247
+ it 'leaves no temp file behind when writing one fails' do
248
+ allow(File).to receive(:open).and_call_original
249
+ allow(File).to receive(:open).with(/\.timer\..*\.tmp\z/, any_args).and_wrap_original do |original, path, *rest, **options|
250
+ original.call(path, *rest, **options) { raise Errno::ENOSPC }
251
+ end
252
+
253
+ expect { systemd.install(schedule) }.to raise_error(RubyRaider::Schedules::Error, /Could not write .*No space left/)
254
+ expect([runner.calls, Dir.children(units)]).to eq([[], []])
255
+ end
256
+
257
+ it 'raises a schedule error and runs nothing when it can not write the units' do
258
+ FileUtils.mkdir_p(File.dirname(units))
259
+ File.write(units, 'not a folder')
260
+
261
+ expect { systemd.install(schedule) }.to raise_error(RubyRaider::Schedules::Error, /Could not write .*systemd/)
262
+ expect([runner.calls, File.read(units)]).to eq([[], 'not a folder'])
263
+ end
264
+ end
265
+
266
+ describe '#remove' do
267
+ it 'disables the timer, deletes both units and reloads' do
268
+ item = schedule
269
+ FileUtils.mkdir_p(units)
270
+ File.write(service_path(item), 'x')
271
+ File.write(timer_path(item), 'x')
272
+
273
+ expect(systemd.remove(item.os_id)).to be(true)
274
+ expect(runner.calls).to eq([['systemctl', '--user', 'disable', '--now', "#{item.os_id}.timer"], %w[systemctl --user daemon-reload]])
275
+ expect(Dir.children(units)).to be_empty
276
+ end
277
+
278
+ it 'is false when it was already gone, even if disable fails' do
279
+ runner.answers['disable'] = ['Unit file does not exist', 1]
280
+
281
+ expect(systemd.remove(schedule.os_id)).to be(false)
282
+ expect(runner.calls.map { |argv| argv[2] }).to eq(%w[disable daemon-reload])
283
+ end
284
+
285
+ it 'raises when a unit can not be deleted' do
286
+ item = schedule
287
+ allow(File).to receive(:unlink).and_raise(Errno::EACCES)
288
+
289
+ expect { systemd.remove(item.os_id) }.to raise_error(RubyRaider::Schedules::Error, /Could not remove .*Permission denied/)
290
+ end
291
+
292
+ it 'raises when the reload fails' do
293
+ runner.answers['daemon-reload'] = ['Failed to connect to bus', 1]
294
+
295
+ expect { systemd.remove(schedule.os_id) }.to raise_error(RubyRaider::Schedules::Error, /Failed to connect to bus/)
296
+ end
297
+
298
+ it 'refuses an os_id that is not a schedule id' do
299
+ expect { systemd.remove('../../evil') }.to raise_error(RubyRaider::Schedules::Error, /Invalid os_id/)
300
+ expect(runner.calls).to be_empty
301
+ end
302
+ end
303
+
304
+ describe '#usable?' do
305
+ it 'asks the user manager for its environment' do
306
+ expect(systemd.usable?).to be(true)
307
+ runner.answers['show-environment'] = ['Failed to connect to bus', 1]
308
+ expect(systemd.usable?).to be(false)
309
+ expect(runner.calls).to eq([%w[systemctl --user show-environment]] * 2)
310
+ end
311
+ end
312
+
313
+ describe '#present?' do
314
+ it 'asks whether the timer is enabled' do
315
+ item = schedule
316
+
317
+ expect(systemd.present?(item.os_id)).to be(true)
318
+ expect(runner.calls).to eq([['systemctl', '--user', 'is-enabled', "#{item.os_id}.timer"]])
319
+ end
320
+
321
+ it 'is false when the timer is not enabled' do
322
+ runner.answers['is-enabled'] = ['disabled', 1]
323
+
324
+ expect(systemd.present?(schedule.os_id)).to be(false)
325
+ end
326
+
327
+ it 'refuses an os_id that is not a schedule id and runs nothing' do
328
+ expect { systemd.present?('x; rm') }.to raise_error(RubyRaider::Schedules::Error, /Invalid os_id/)
329
+ expect(runner.calls).to be_empty
330
+ end
331
+ end
332
+ end
333
+ # rubocop:enable RSpec/MultipleMemoizedHelpers