samagotchi 0.186.0 → 0.187.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +14 -1
- data/bin/chi +2 -0
- data/docs/cli.md +1 -0
- data/docs/internals/inline-widgets.md +18 -0
- data/docs/internals/pages.md +172 -0
- data/docs/internals/web-frontend.md +5 -4
- data/docs/memory.md +7 -0
- data/docs/pages.md +150 -0
- data/lib/samagotchi/bundles/system/manifest.yml +5 -2
- data/lib/samagotchi/bundles/system/self_map.md +5 -1
- data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
- data/lib/samagotchi/inline_widgets.rb +65 -0
- data/lib/samagotchi/page_command.rb +234 -0
- data/lib/samagotchi/pages/builder.rb +187 -0
- data/lib/samagotchi/pages/launch.rb +187 -0
- data/lib/samagotchi/pages/runner.rb +154 -0
- data/lib/samagotchi/pages/store.rb +143 -0
- data/lib/samagotchi/pages.rb +119 -0
- data/lib/samagotchi/run_options.rb +1 -0
- data/lib/samagotchi/session_access/contract.rb +1 -1
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +5 -5
- data/lib/samagotchi/web/page_routes.rb +116 -0
- data/lib/samagotchi/web/public/app.js +24 -84
- data/lib/samagotchi/web/public/index.html +3 -0
- data/lib/samagotchi/web/public/page_blocks.js +58 -0
- data/lib/samagotchi/web/public/page_links.js +33 -0
- data/lib/samagotchi/web/public/page_model.js +68 -0
- data/lib/samagotchi/web/public/page_route.js +24 -0
- data/lib/samagotchi/web/public/page_table.js +74 -0
- data/lib/samagotchi/web/public/page_table_model.js +76 -0
- data/lib/samagotchi/web/public/page_view.js +218 -0
- data/lib/samagotchi/web/public/pages.css +77 -0
- data/lib/samagotchi/web/public/pages_group.js +65 -0
- data/lib/samagotchi/web/public/views.js +161 -0
- data/lib/samagotchi/web/viewer.rb +1 -1
- metadata +21 -1
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "rbconfig"
|
|
5
|
+
require_relative "../pages"
|
|
6
|
+
require_relative "../child_env"
|
|
7
|
+
require_relative "../process_group"
|
|
8
|
+
require_relative "../agent_caller"
|
|
9
|
+
require_relative "../session_access/dispatch"
|
|
10
|
+
|
|
11
|
+
module Samagotchi
|
|
12
|
+
module Pages
|
|
13
|
+
# One run of a page: the one launch path, for `chi page run` and (Build 2)
|
|
14
|
+
# chi web's Refresh alike. It takes the page's lock, starts the runner
|
|
15
|
+
# (pages/runner.rb) in a process group of its own, in the pages folder,
|
|
16
|
+
# with this process's environment as a worker gets it (the Bundler changes
|
|
17
|
+
# undone, the spawner's keys and #cleared_keys unset, the XDG dirs
|
|
18
|
+
# absolute) and the lock on fd 3 (the runner holds it too, and has a
|
|
19
|
+
# deadline of its own for a launcher that dies mid-run), reads its
|
|
20
|
+
# stdout and stderr through bounded readers, and cuts it at +timeout+.
|
|
21
|
+
# The runner writes the output file; a cut, or a runner that ended without
|
|
22
|
+
# writing one, is recorded here (Store.record_failure). Whatever the
|
|
23
|
+
# script left running in its group is killed after any exit.
|
|
24
|
+
# ContextFetch#run_command is the model.
|
|
25
|
+
module Launch
|
|
26
|
+
# This chi's lib: the runner is started from the same code (a checkout
|
|
27
|
+
# or an installed gem alike).
|
|
28
|
+
LIB_DIR = File.expand_path("../..", __dir__)
|
|
29
|
+
BOOT = 'require "samagotchi/pages/runner"; exit Samagotchi::Pages::Runner.run(ARGV)'
|
|
30
|
+
PIPE_CAP = 64 * 1024
|
|
31
|
+
# How long the group gets after TERM before KILL, and the readers
|
|
32
|
+
# after the exit.
|
|
33
|
+
GRACE_SECONDS = 1.0
|
|
34
|
+
POLL_SECONDS = 0.05
|
|
35
|
+
# The runner's own deadline is the timeout + GRACE_SECONDS + this,
|
|
36
|
+
# from its start: later than the launcher's cut, which wins whenever
|
|
37
|
+
# the launcher is alive.
|
|
38
|
+
DEADLINE_MARGIN = 2.0
|
|
39
|
+
# The fd the runner gets the page's lock on.
|
|
40
|
+
LOCK_FD = 3
|
|
41
|
+
|
|
42
|
+
# +page+ the stored page after the run; +stdout+ / +stderr+ the
|
|
43
|
+
# script's own words (their last 64 KB); +seconds+ the run's wall time.
|
|
44
|
+
Result = Data.define(:ok, :page, :stdout, :stderr, :seconds) do
|
|
45
|
+
def ok? = ok
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
module_function
|
|
49
|
+
|
|
50
|
+
# @param cancelled [#call, nil] polled while the run waits: true stops
|
|
51
|
+
# the run as the cut does, recorded as "the run was stopped" (chi web
|
|
52
|
+
# stopping during a Refresh)
|
|
53
|
+
# @raise [BadName] [Missing] [Busy]
|
|
54
|
+
# @return [Result]
|
|
55
|
+
def run(name, timeout: TIMEOUT_SECONDS, cancelled: nil)
|
|
56
|
+
Pages.check_name!(name)
|
|
57
|
+
raise Missing, name unless File.file?(Pages.script_path(name))
|
|
58
|
+
|
|
59
|
+
Store.locked(name) do |lock|
|
|
60
|
+
# Again under the lock: a `chi page rm` between the check above and
|
|
61
|
+
# the lock removed the page, so this run writes nothing (not even
|
|
62
|
+
# the lock file it just made).
|
|
63
|
+
unless File.file?(Pages.script_path(name))
|
|
64
|
+
FileUtils.rm_f(Store.lock_path(name))
|
|
65
|
+
raise Missing, name
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
launch(name, timeout, lock, cancelled)
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# The runner's argv: the name, the timeout (for its cut's words) and
|
|
73
|
+
# its own deadline in seconds.
|
|
74
|
+
def command(name, timeout)
|
|
75
|
+
[RbConfig.ruby, "-I", LIB_DIR, "-e", BOOT, name, seconds(timeout),
|
|
76
|
+
seconds(timeout + GRACE_SECONDS + DEADLINE_MARGIN)]
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# The changes to this process's env a run gets, as a worker's
|
|
80
|
+
# (SessionManager::WorkerCommand#spawn_options): an installed gem's
|
|
81
|
+
# Bundler changes mapped back, the spawner's keys unset, the XDG dirs
|
|
82
|
+
# absolute. PWD is set to the pages folder too: spawn's chdir doesn't
|
|
83
|
+
# change it, and a script reading ENV["PWD"] would otherwise see the
|
|
84
|
+
# caller's folder, so the terminal and chi web would differ.
|
|
85
|
+
# The remote, worker and agent markers (#cleared_keys) are unset too.
|
|
86
|
+
def env
|
|
87
|
+
ChildEnv.unbundled.merge(ChildEnv.unset).merge(cleared_keys.to_h { |key| [key, nil] })
|
|
88
|
+
.merge(Paths.absolute_xdg).merge("PWD" => Pages.scripts_dir)
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# What a run never takes from its launcher, so the terminal and chi web
|
|
92
|
+
# are one path: CHI_REMOTE (a run never goes remote), a worker's
|
|
93
|
+
# markers (it is no worker's child) and the vendor agent markers (a
|
|
94
|
+
# script's `chi send` is the owner's, even from a chi web started in an
|
|
95
|
+
# agent's pane).
|
|
96
|
+
# @return [Array<String>]
|
|
97
|
+
def cleared_keys(env = ENV)
|
|
98
|
+
[SessionAccess::Dispatch::ENV_KEY, *AgentCaller::VENDOR_MARKERS.map(&:first)] +
|
|
99
|
+
env.each_key.select { |key| key.start_with?(ChildEnv::WORKER_PREFIX) }
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def launch(name, timeout, lock, cancelled)
|
|
103
|
+
before = Store.file_id(name)
|
|
104
|
+
started = monotonic
|
|
105
|
+
out_r, out_w = IO.pipe
|
|
106
|
+
err_r, err_w = IO.pipe
|
|
107
|
+
pid = ProcessGroup.spawn(env, *command(name, timeout), chdir: Pages.scripts_dir, in: File::NULL, out: out_w,
|
|
108
|
+
err: err_w, LOCK_FD => lock)
|
|
109
|
+
out_w.close
|
|
110
|
+
err_w.close
|
|
111
|
+
readers = [out_r, err_r].map { |io| ProcessGroup::PipeReader.new(io, cap: PIPE_CAP, keep: :tail) }
|
|
112
|
+
|
|
113
|
+
status, cut = wait(pid, timeout, cancelled)
|
|
114
|
+
reaped = true
|
|
115
|
+
# A script's background child would hold the pipes open.
|
|
116
|
+
ProcessGroup.signal(pid, "KILL")
|
|
117
|
+
readers.each { |reader| reader.wait(GRACE_SECONDS) || reader.kill }
|
|
118
|
+
stdout, stderr = readers.map { |reader| reader.text(Encoding::UTF_8).scrub }
|
|
119
|
+
ok = record(name, status, cut, timeout, before, stderr)
|
|
120
|
+
Result.new(ok: ok, page: Store.read(name), stdout: stdout, stderr: stderr, seconds: monotonic - started)
|
|
121
|
+
ensure
|
|
122
|
+
# Cut short (Ctrl-C, an exception): the group doesn't get the
|
|
123
|
+
# terminal's SIGINT (pgroup), so stop and reap it here.
|
|
124
|
+
abandon(pid, readers) if pid && !reaped
|
|
125
|
+
[out_r, out_w, err_r, err_w].each { |io| io.close if io && !io.closed? }
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# @return [Boolean] whether the run was good. A cut or a runner that
|
|
129
|
+
# ended without its result is recorded here; the runner recorded the rest.
|
|
130
|
+
def record(name, status, cut, timeout, before, stderr)
|
|
131
|
+
sha = Store.script_sha(name)
|
|
132
|
+
if cut
|
|
133
|
+
message = cut == :cancelled ? "the run was stopped" : "the script was stopped after #{seconds(timeout)} s"
|
|
134
|
+
Store.record_failure(name, message: message, line: nil, script_sha: sha)
|
|
135
|
+
return false
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
written = Store.file_id(name)
|
|
139
|
+
if written.nil? || written == before || ![0, 1].include?(status&.exitstatus)
|
|
140
|
+
# Not a backtrace frame: a Ruby crash ends stderr with "from …" lines.
|
|
141
|
+
tail = stderr.lines.map(&:strip).reject { |line| line.empty? || line.start_with?("from ") }.last
|
|
142
|
+
Store.record_failure(name, message: ["the runner ended without a result", tail].compact.join(": "), line: nil,
|
|
143
|
+
script_sha: sha)
|
|
144
|
+
return false
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
status.exitstatus.zero? && Store.read(name).state == :ok
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# @return [Array(Process::Status|nil, Symbol|nil)] the status, and
|
|
151
|
+
# why it was cut: :timeout, :cancelled, or nil when it ended itself
|
|
152
|
+
def wait(pid, timeout, cancelled = nil)
|
|
153
|
+
deadline = monotonic + timeout
|
|
154
|
+
loop do
|
|
155
|
+
_, status = Process.wait2(pid, Process::WNOHANG)
|
|
156
|
+
return [status, nil] if status
|
|
157
|
+
return [stop_group(pid), :timeout] if monotonic > deadline
|
|
158
|
+
return [stop_group(pid), :cancelled] if cancelled&.call
|
|
159
|
+
|
|
160
|
+
sleep(POLL_SECONDS)
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# TERM the group, a grace, then KILL; the reap ends the wait.
|
|
165
|
+
# @return [Process::Status, nil]
|
|
166
|
+
def stop_group(pid)
|
|
167
|
+
status = nil
|
|
168
|
+
reaped = -> { status = Process.wait2(pid, Process::WNOHANG)&.last }
|
|
169
|
+
return status if ProcessGroup.stop(pid, grace: GRACE_SECONDS, poll: POLL_SECONDS, stopped: reaped)
|
|
170
|
+
|
|
171
|
+
status || Process.wait2(pid).last
|
|
172
|
+
rescue Errno::ECHILD
|
|
173
|
+
status
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
def abandon(pid, readers)
|
|
177
|
+
stop_group(pid)
|
|
178
|
+
ProcessGroup.signal(pid, "KILL")
|
|
179
|
+
Array(readers).each(&:kill)
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def seconds(value) = format("%g", value)
|
|
183
|
+
|
|
184
|
+
def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
end
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../pages"
|
|
4
|
+
|
|
5
|
+
module Samagotchi
|
|
6
|
+
module Pages
|
|
7
|
+
# The page runner: the process Launch starts for one run of one page,
|
|
8
|
+
# ruby -I <lib> -e 'require "samagotchi/pages/runner"; exit Samagotchi::Pages::Runner.run(ARGV)' NAME [TIMEOUT DEADLINE]
|
|
9
|
+
# with the page's lock on fd 3. It holds that lock while it lives and,
|
|
10
|
+
# given a DEADLINE (seconds from its start), stops itself and its group
|
|
11
|
+
# there, recording the cut: a launcher killed mid-run (chi web) leaves at
|
|
12
|
+
# most one bounded run, and the page "already running" until it ends.
|
|
13
|
+
# Requiring this file runs nothing. It loads Pages only (no engine, no
|
|
14
|
+
# config, no web, no plugins, no ProcessGroup), so a run is as light as a
|
|
15
|
+
# Ruby script, and a page's surroundings are the same from the terminal
|
|
16
|
+
# and from chi web.
|
|
17
|
+
#
|
|
18
|
+
# The script is loaded with a fresh module as its wrap (Kernel#load), which
|
|
19
|
+
# gives it `page` and keeps its own methods off Object. What the run built,
|
|
20
|
+
# or what it raised, goes to the output file (Store), never to stdout: a
|
|
21
|
+
# `puts` in a script is the script's own. A TERM (Launch's cut) is not
|
|
22
|
+
# rescued: the launcher records the cut itself.
|
|
23
|
+
module Runner
|
|
24
|
+
# The script's `page "Title" do |ui| … end`, once per run.
|
|
25
|
+
class Collector
|
|
26
|
+
attr_reader :builder
|
|
27
|
+
|
|
28
|
+
def dsl
|
|
29
|
+
collector = self
|
|
30
|
+
Module.new do
|
|
31
|
+
define_method(:page) do |title, &block|
|
|
32
|
+
collector.page(title, &block)
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def page(title)
|
|
38
|
+
raise Refused, "a page script calls page once" if @builder
|
|
39
|
+
|
|
40
|
+
@builder = Builder.new(title)
|
|
41
|
+
yield @builder if block_given?
|
|
42
|
+
nil
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# The fd Launch hands the page's lock on (Launch::LOCK_FD).
|
|
47
|
+
LOCK_FD = 3
|
|
48
|
+
|
|
49
|
+
module_function
|
|
50
|
+
|
|
51
|
+
# @param argv [Array<String>] [NAME] or [NAME, TIMEOUT, DEADLINE]
|
|
52
|
+
# @return [Integer] 0 the page ran, 1 the script failed (recorded), 2
|
|
53
|
+
# no such page (nothing recorded: Launch checks this first)
|
|
54
|
+
def run(argv)
|
|
55
|
+
hold_lock
|
|
56
|
+
name, timeout, deadline = argv
|
|
57
|
+
return 2 unless Pages.valid_name?(name) && File.file?(Pages.script_path(name))
|
|
58
|
+
|
|
59
|
+
# The deadline thread and the result's write take this in turn, and
|
|
60
|
+
# the write sets done under it: a run recorded before the deadline
|
|
61
|
+
# fires (an at_exit still going, the exit itself) is never
|
|
62
|
+
# overwritten by the cut.
|
|
63
|
+
recording = Mutex.new
|
|
64
|
+
done = [false]
|
|
65
|
+
arm_deadline(name, timeout, Float(deadline), recording, done) if deadline
|
|
66
|
+
path = Pages.script_path(name)
|
|
67
|
+
sha = Digest::SHA256.file(path).hexdigest
|
|
68
|
+
collector = Collector.new
|
|
69
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
70
|
+
begin
|
|
71
|
+
load(path, collector.dsl)
|
|
72
|
+
raise Refused, "the script never called page" unless collector.builder
|
|
73
|
+
|
|
74
|
+
data = collector.builder.data
|
|
75
|
+
ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
|
|
76
|
+
recording.synchronize do
|
|
77
|
+
Store.record_run(name, title: data["title"], blocks: data["blocks"], duration_ms: ms, script_sha: sha)
|
|
78
|
+
done[0] = true
|
|
79
|
+
end
|
|
80
|
+
0
|
|
81
|
+
# SystemStackError (endless recursion) and NoMemoryError are no
|
|
82
|
+
# StandardError, but a script's own bug all the same.
|
|
83
|
+
rescue StandardError, ScriptError, SystemExit, SystemStackError, NoMemoryError => e
|
|
84
|
+
recording.synchronize do
|
|
85
|
+
Store.record_failure(name, message: message(e, path), line: line(e, path), script_sha: sha)
|
|
86
|
+
done[0] = true
|
|
87
|
+
end
|
|
88
|
+
1
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# The first act: the inherited lock fd is close-on-exec here, so the
|
|
93
|
+
# runner holds the lock alone. A child the script execs, even one that
|
|
94
|
+
# leaves the group (and so outlives the run), never inherits it: it
|
|
95
|
+
# would keep the page "already running" for as long as it lives. A
|
|
96
|
+
# runner started by hand has no lock there: fd 3 is closed (EBADF) or,
|
|
97
|
+
# as Ruby keeps it for itself when nothing is inherited there, refused
|
|
98
|
+
# (ArgumentError, "RubyVM reserves it").
|
|
99
|
+
def hold_lock
|
|
100
|
+
IO.for_fd(LOCK_FD, autoclose: false).close_on_exec = true
|
|
101
|
+
rescue Errno::EBADF, ArgumentError
|
|
102
|
+
nil
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# At +deadline+ seconds from now the cut is recorded (a dead launcher
|
|
106
|
+
# can't), unless the run's own result is already written (+done+), and
|
|
107
|
+
# the runner's whole group is KILLed either way (it leads its group).
|
|
108
|
+
# A Ruby thread: it can't fire while a C extension holds the GVL
|
|
109
|
+
# (docs/internals/pages.md). Plain Process calls, no ProcessGroup, to
|
|
110
|
+
# stay light.
|
|
111
|
+
def arm_deadline(name, timeout, deadline, recording, done)
|
|
112
|
+
Thread.new do
|
|
113
|
+
sleep(deadline)
|
|
114
|
+
recording.lock
|
|
115
|
+
begin
|
|
116
|
+
unless done[0]
|
|
117
|
+
Store.record_failure(name, message: "the script was stopped after #{timeout} s", line: nil,
|
|
118
|
+
script_sha: Store.script_sha(name))
|
|
119
|
+
end
|
|
120
|
+
# Not an ensure: a normal exit kills this thread, and its ensure would KILL the group.
|
|
121
|
+
rescue StandardError # degrade-ok: the KILL matters more than the record (a dead launcher records nothing)
|
|
122
|
+
nil
|
|
123
|
+
end
|
|
124
|
+
Process.kill("KILL", -Process.pid)
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# The error as the page shows it: a syntax error without its leading
|
|
129
|
+
# "path:line:" (its line is #line's), an exit as what it was.
|
|
130
|
+
def message(error, path)
|
|
131
|
+
case error
|
|
132
|
+
when ScriptError then error.message.sub(/\A#{Regexp.escape(path)}:\d+:\s*/, "")
|
|
133
|
+
when SystemExit
|
|
134
|
+
words = error.message == "exit" ? nil : error.message
|
|
135
|
+
words || "the script called exit #{error.status}"
|
|
136
|
+
else error.message
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# The script's line: a syntax error's from its message's first line
|
|
141
|
+
# (the rest differs between Rubies), anything else's from the first
|
|
142
|
+
# backtrace entry inside the script file. nil when neither has one.
|
|
143
|
+
def line(error, path)
|
|
144
|
+
prefix = "#{path}:"
|
|
145
|
+
if error.is_a?(ScriptError)
|
|
146
|
+
found = error.message.lines.first.to_s[/\A#{Regexp.escape(prefix)}(\d+)/, 1]
|
|
147
|
+
return found.to_i if found
|
|
148
|
+
end
|
|
149
|
+
entry = Array(error.backtrace).find { |frame| frame.start_with?(prefix) }
|
|
150
|
+
entry && entry.delete_prefix(prefix)[/\A\d+/]&.to_i
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
end
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require_relative "../pages"
|
|
5
|
+
|
|
6
|
+
module Samagotchi
|
|
7
|
+
module Pages
|
|
8
|
+
# Where pages live: the scripts (<config>/samagotchi/pages/NAME.rb), each
|
|
9
|
+
# one's output (<state>/samagotchi/pages/NAME/output.json) and its lock
|
|
10
|
+
# (<state>/samagotchi/pages/NAME.lock, beside the folder so a remove can
|
|
11
|
+
# delete the folder while holding it). A failed run rewrites only the
|
|
12
|
+
# error: the blocks of the last good run stay. Every path is built after
|
|
13
|
+
# Pages.check_name!.
|
|
14
|
+
module Store
|
|
15
|
+
OUTPUT = "output.json"
|
|
16
|
+
# How much of a failure's message is kept.
|
|
17
|
+
MAX_MESSAGE = 2000
|
|
18
|
+
|
|
19
|
+
module_function
|
|
20
|
+
|
|
21
|
+
def output_dir(name) = File.join(Pages.state_dir, Pages.check_name!(name))
|
|
22
|
+
def output_path(name) = File.join(output_dir(name), OUTPUT)
|
|
23
|
+
def lock_path(name) = File.join(Pages.state_dir, "#{Pages.check_name!(name)}.lock")
|
|
24
|
+
|
|
25
|
+
# @return [String, nil] the sha256 of NAME's script, nil when it has none
|
|
26
|
+
def script_sha(name)
|
|
27
|
+
path = Pages.script_path(name)
|
|
28
|
+
File.file?(path) ? Digest::SHA256.file(path).hexdigest : nil
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# @return [Stored] never ran when the output file is missing or unreadable
|
|
32
|
+
def read(name)
|
|
33
|
+
raw = read_raw(name)
|
|
34
|
+
error = raw["error"]
|
|
35
|
+
error = if error.is_a?(Hash) && error["message"].is_a?(String)
|
|
36
|
+
Failure.new(message: error["message"], line: error["line"].is_a?(Integer) ? error["line"] : nil,
|
|
37
|
+
at: string(error["at"]), script_sha: string(error["script_sha"]))
|
|
38
|
+
end
|
|
39
|
+
ran_at = string(raw["ran_at"])
|
|
40
|
+
Stored.new(name: name, title: string(raw["title"]), blocks: ran_at && raw["blocks"].is_a?(Array) ? raw["blocks"] : [],
|
|
41
|
+
ran_at: ran_at, duration_ms: raw["duration_ms"].is_a?(Numeric) ? raw["duration_ms"] : nil,
|
|
42
|
+
script_sha: string(raw["script_sha"]), error: error, current_sha: script_sha(name))
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Every script with a valid name, by name; a file whose name breaks
|
|
46
|
+
# the rule is skipped.
|
|
47
|
+
# @return [Array<Stored>]
|
|
48
|
+
def list
|
|
49
|
+
return [] unless File.directory?(Pages.scripts_dir)
|
|
50
|
+
|
|
51
|
+
Dir.children(Pages.scripts_dir).filter_map do |file|
|
|
52
|
+
name = file.delete_suffix(".rb")
|
|
53
|
+
name if file.end_with?(".rb") && Pages.valid_name?(name) && File.file?(File.join(Pages.scripts_dir, file))
|
|
54
|
+
end.sort.map { |name| read(name) }
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# A good run: its blocks replace the last ones and the error is cleared.
|
|
58
|
+
# @raise [Refused] the output is over MAX_OUTPUT_BYTES
|
|
59
|
+
# @return [Stored]
|
|
60
|
+
def record_run(name, title:, blocks:, duration_ms:, script_sha:)
|
|
61
|
+
stored = Stored.new(name: name, title: title, blocks: blocks, ran_at: now, duration_ms: duration_ms,
|
|
62
|
+
script_sha: script_sha, error: nil, current_sha: script_sha)
|
|
63
|
+
json = JSON.generate(stored.to_json_hash)
|
|
64
|
+
if json.bytesize > MAX_OUTPUT_BYTES
|
|
65
|
+
raise Refused, format("the output is %<kb>.1f KB (at most %<max>d KB)", kb: json.bytesize / 1024.0,
|
|
66
|
+
max: MAX_OUTPUT_BYTES / 1024)
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
write(name, json)
|
|
70
|
+
stored
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# A failed run: the error is set; the last good run's blocks stay.
|
|
74
|
+
# The one writer of a failure, for the runner (the script's) and the
|
|
75
|
+
# launcher (a cut, a runner with no result) alike.
|
|
76
|
+
# @return [Stored]
|
|
77
|
+
def record_failure(name, message:, line:, script_sha:)
|
|
78
|
+
# Scrubbed: a message with stray bytes (backtick output) would make
|
|
79
|
+
# JSON.generate raise inside the runner's rescue and lose the error.
|
|
80
|
+
message = Builder.text_of(message)
|
|
81
|
+
message = "#{message[0, MAX_MESSAGE - 1]}…" if message.size > MAX_MESSAGE
|
|
82
|
+
stored = read(name).with(error: Failure.new(message: message, line: line, at: now, script_sha: script_sha))
|
|
83
|
+
write(name, JSON.generate(stored.to_json_hash))
|
|
84
|
+
stored
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Runs the block holding NAME's lock (flock, non-blocking), with the
|
|
88
|
+
# lock's io: Launch hands it to the runner, which then holds the lock
|
|
89
|
+
# for as long as it lives (a killed launcher leaves a run that still
|
|
90
|
+
# holds it).
|
|
91
|
+
# @yieldparam lock [File]
|
|
92
|
+
# @raise [Busy] another process holds it
|
|
93
|
+
def locked(name)
|
|
94
|
+
path = lock_path(name)
|
|
95
|
+
FileUtils.mkdir_p(File.dirname(path))
|
|
96
|
+
File.open(path, File::RDWR | File::CREAT, 0o644) do |lock|
|
|
97
|
+
raise Busy, name unless lock.flock(File::LOCK_EX | File::LOCK_NB)
|
|
98
|
+
|
|
99
|
+
yield lock
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# Deletes NAME's script and output folder under its lock, then the lock.
|
|
104
|
+
# @raise [Missing] no script and no output
|
|
105
|
+
# @raise [Busy] it is running
|
|
106
|
+
def remove(name)
|
|
107
|
+
script = Pages.script_path(name)
|
|
108
|
+
raise Missing, name unless File.exist?(script) || File.exist?(output_dir(name))
|
|
109
|
+
|
|
110
|
+
locked(name) do
|
|
111
|
+
FileUtils.rm_f(script)
|
|
112
|
+
FileUtils.rm_rf(output_dir(name))
|
|
113
|
+
FileUtils.rm_f(lock_path(name))
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# The output file's identity (its inode): AtomicFile renames a new file
|
|
118
|
+
# in for every write, so a run that wrote changes it, even within the
|
|
119
|
+
# same second. nil when there is none.
|
|
120
|
+
def file_id(name)
|
|
121
|
+
File.stat(output_path(name)).ino
|
|
122
|
+
rescue SystemCallError
|
|
123
|
+
nil
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def write(name, json)
|
|
127
|
+
FileUtils.mkdir_p(output_dir(name))
|
|
128
|
+
AtomicFile.write(output_path(name), json)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def read_raw(name)
|
|
132
|
+
raw = JSON.parse(File.read(output_path(name), encoding: Encoding::UTF_8))
|
|
133
|
+
raw.is_a?(Hash) ? raw : {}
|
|
134
|
+
rescue JSON::ParserError, SystemCallError, EncodingError
|
|
135
|
+
{}
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def string(value) = value.is_a?(String) ? value : nil
|
|
139
|
+
|
|
140
|
+
def now = Time.now.utc.iso8601
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
end
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "digest"
|
|
5
|
+
require "time"
|
|
6
|
+
require_relative "inline_widgets"
|
|
7
|
+
require_relative "paths"
|
|
8
|
+
require_relative "atomic_file"
|
|
9
|
+
|
|
10
|
+
module Samagotchi
|
|
11
|
+
# Pages: a Ruby script under <config>/samagotchi/pages/NAME.rb says what to
|
|
12
|
+
# show (`page "Title" do |ui| ui.text …; ui.table …; ui.walk … end`); a run
|
|
13
|
+
# stores the blocks it built as JSON under <state>/samagotchi/pages/NAME/,
|
|
14
|
+
# and what shows a page draws from that file (docs/pages.md,
|
|
15
|
+
# docs/internals/pages.md).
|
|
16
|
+
#
|
|
17
|
+
# Light on purpose: the runner (pages/runner.rb) is a process of its own
|
|
18
|
+
# that requires this file only, so nothing here may require the engine, the
|
|
19
|
+
# config, the web, the plugins or the launcher (pages/launch.rb, which
|
|
20
|
+
# spawns the runner and needs ProcessGroup and ChildEnv).
|
|
21
|
+
module Pages
|
|
22
|
+
autoload :Builder, File.expand_path("pages/builder", __dir__)
|
|
23
|
+
autoload :TableBlock, File.expand_path("pages/builder", __dir__)
|
|
24
|
+
autoload :Store, File.expand_path("pages/store", __dir__)
|
|
25
|
+
|
|
26
|
+
# A page's name: lowercase letters, digits and hyphens, a letter or a
|
|
27
|
+
# digit first, at most 40.
|
|
28
|
+
NAME = /\A[a-z0-9][a-z0-9-]{0,39}\z/
|
|
29
|
+
MAX_ROWS = 500
|
|
30
|
+
MAX_COLUMNS = 12
|
|
31
|
+
MAX_CELL = 300
|
|
32
|
+
MAX_BLOCKS = 20
|
|
33
|
+
MAX_TEXT_BYTES = 16 * 1024
|
|
34
|
+
MAX_OUTPUT_BYTES = 256 * 1024
|
|
35
|
+
TIMEOUT_SECONDS = 30
|
|
36
|
+
FORMATS = %i[money count].freeze
|
|
37
|
+
|
|
38
|
+
# Anything that keeps a page from running or from being stored. Each
|
|
39
|
+
# subclass owns its message.
|
|
40
|
+
class Error < StandardError; end
|
|
41
|
+
|
|
42
|
+
# A rule a script broke (a limit, a table's column, page called twice):
|
|
43
|
+
# the run fails with this message.
|
|
44
|
+
class Refused < Error; end
|
|
45
|
+
|
|
46
|
+
# A name that breaks NAME: the command line's fault (exit 2).
|
|
47
|
+
class BadName < Error
|
|
48
|
+
def initialize(name)
|
|
49
|
+
super("#{name.to_s.inspect} isn't a page name (lowercase letters, digits and hyphens, a letter or digit first, at most 40)")
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# No script for the name.
|
|
54
|
+
class Missing < Error
|
|
55
|
+
def initialize(name)
|
|
56
|
+
super("no page #{name}")
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Another run (or a remove) holds the page's lock.
|
|
61
|
+
class Busy < Error
|
|
62
|
+
def initialize(name)
|
|
63
|
+
super("page #{name} is already running")
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# A failed run: what the script raised (or why it was stopped), the
|
|
68
|
+
# script's line when one is known, when, and the sha256 of the script
|
|
69
|
+
# that failed.
|
|
70
|
+
Failure = Data.define(:message, :line, :at, :script_sha) do
|
|
71
|
+
def to_json_hash = { "message" => message, "line" => line, "at" => at, "script_sha" => script_sha }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# A page as stored (Store.read): the blocks of its last good run (none
|
|
75
|
+
# before one, ran_at nil) and the last failure since, if any.
|
|
76
|
+
# +current_sha+ is the script's sha256 now (nil when the script is gone).
|
|
77
|
+
Stored = Data.define(:name, :title, :blocks, :ran_at, :duration_ms, :script_sha, :error, :current_sha) do
|
|
78
|
+
# :never_ran, :ok or :failed (the last run failed; the good blocks, if
|
|
79
|
+
# any, are still there).
|
|
80
|
+
def state
|
|
81
|
+
return :failed if error
|
|
82
|
+
return :ok if ran_at
|
|
83
|
+
|
|
84
|
+
:never_ran
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Whether the script differs from the one that made the blocks.
|
|
88
|
+
def changed? = !script_sha.nil? && !current_sha.nil? && current_sha != script_sha
|
|
89
|
+
|
|
90
|
+
# The output file's JSON.
|
|
91
|
+
def to_json_hash
|
|
92
|
+
{ "name" => name, "title" => title, "blocks" => blocks, "ran_at" => ran_at, "duration_ms" => duration_ms,
|
|
93
|
+
"script_sha" => script_sha, "error" => error&.to_json_hash }
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
module_function
|
|
98
|
+
|
|
99
|
+
def valid_name?(name) = name.is_a?(String) && NAME.match?(name)
|
|
100
|
+
|
|
101
|
+
# The one check every path goes through before it builds a path.
|
|
102
|
+
# @return [String] +name+
|
|
103
|
+
# @raise [BadName]
|
|
104
|
+
def check_name!(name)
|
|
105
|
+
raise BadName, name unless valid_name?(name)
|
|
106
|
+
|
|
107
|
+
name
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# @return [String] <config home>/samagotchi/pages (ConfigFile.config_dir
|
|
111
|
+
# lives in config.rb, which loads far more than a runner may)
|
|
112
|
+
def scripts_dir = File.join(Paths.config_home, Paths::APP_DIR, "pages")
|
|
113
|
+
|
|
114
|
+
# @return [String] <state dir>/pages
|
|
115
|
+
def state_dir = File.join(Paths.state_dir, "pages")
|
|
116
|
+
|
|
117
|
+
def script_path(name) = File.join(scripts_dir, "#{check_name!(name)}.rb")
|
|
118
|
+
end
|
|
119
|
+
end
|
|
@@ -204,6 +204,7 @@ module Samagotchi
|
|
|
204
204
|
chi answer ID --question QID --option N answer a question a session waits on
|
|
205
205
|
chi share ID --name NAME | ls [ID] | cap ID P D | revoke ID [P]|--all invite people into a session
|
|
206
206
|
chi memory <ls|rm> [--scope project|system] the memories; rm moves one to the bundle trash
|
|
207
|
+
chi page <run|list|rm> [NAME] pages: scripts under ~/.config/samagotchi/pages that say what to show
|
|
207
208
|
chi bundle <install|upgrade|uninstall|status|diff|list|build|trash|new|test|check|try>
|
|
208
209
|
chi guardrails replay [--dry-run] [--threshold T] [--model M] seed System 1's record from answered approvals
|
|
209
210
|
chi guardrails rule <id> print "asks" if that rule votes ask on this machine now
|
|
@@ -26,7 +26,7 @@ module Samagotchi
|
|
|
26
26
|
# bin/chi subcommands that act on this machine: never sessions. chi
|
|
27
27
|
# remote (this machine's list of remotes) runs here under a remote too
|
|
28
28
|
# (Dispatch); the others are refused there.
|
|
29
|
-
MACHINE = %w[bootstrap update models desktop memory bundle guardrails toolkit judgments remote home project schedule].freeze
|
|
29
|
+
MACHINE = %w[bootstrap update models desktop memory page bundle guardrails toolkit judgments remote home project schedule].freeze
|
|
30
30
|
|
|
31
31
|
# "command", "command sub" or either with a flag (its long name) →
|
|
32
32
|
# SUPPORTED or LOCAL_ONLY. A LOCAL_ONLY command or subcommand lists
|
data/lib/samagotchi/version.rb
CHANGED
data/lib/samagotchi/web/app.rb
CHANGED
|
@@ -84,6 +84,7 @@ require_relative "verify_fresh_routes"
|
|
|
84
84
|
require_relative "block_fix_routes"
|
|
85
85
|
require_relative "reload_check_route"
|
|
86
86
|
require_relative "working_set_routes"
|
|
87
|
+
require_relative "page_routes"
|
|
87
88
|
require_relative "push_routes"
|
|
88
89
|
require_relative "block_renderer_routes"
|
|
89
90
|
require_relative "update_check"
|
|
@@ -125,6 +126,7 @@ module Samagotchi
|
|
|
125
126
|
include BlockFixRoutes
|
|
126
127
|
include ReloadCheckRoute
|
|
127
128
|
include WorkingSetRoutes
|
|
129
|
+
include PageRoutes
|
|
128
130
|
include PushRoutes
|
|
129
131
|
include BlockRendererRoutes
|
|
130
132
|
include ProxyGate
|
|
@@ -297,7 +299,7 @@ module Samagotchi
|
|
|
297
299
|
["GET", %r{\A/api/sessions/summaries\z}, :handle_summaries, :owner],
|
|
298
300
|
["GET", %r{\A/api/info\z}, :handle_info, :participant],
|
|
299
301
|
["POST", %r{\A/api/token\z}, :handle_token, :participant],
|
|
300
|
-
["GET", %r{\A/api/models\z}, :handle_models, :owner],
|
|
302
|
+
["GET", %r{\A/api/models\z}, :handle_models, :owner], *PageRoutes::ROUTES,
|
|
301
303
|
["GET", %r{\A/api/history\z}, :handle_history, :owner],
|
|
302
304
|
["GET", %r{\A/api/events\z}, :handle_events, :owner],
|
|
303
305
|
["POST", %r{\A/api/update\z}, :handle_update, :owner],
|
|
@@ -905,8 +907,7 @@ module Samagotchi
|
|
|
905
907
|
end
|
|
906
908
|
|
|
907
909
|
# At most once a minute per peer: a phone with an old link retries.
|
|
908
|
-
# At most REFUSED_LOG_KEYS peers a minute (rotating headers can't
|
|
909
|
-
# fill the log).
|
|
910
|
+
# At most REFUSED_LOG_KEYS peers a minute (rotating headers can't fill the log).
|
|
910
911
|
def log_refused(peer, path, reason = nil)
|
|
911
912
|
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
912
913
|
due = @refused_mutex.synchronize do
|
|
@@ -1099,8 +1100,7 @@ module Samagotchi
|
|
|
1099
1100
|
# on loopback only; proxy: {identity_header} behind an auth proxy
|
|
1100
1101
|
# (web.public_url or a tunnel; the header nil when none is trusted),
|
|
1101
1102
|
# nil without one: the Invite dialog's email field and chi share's
|
|
1102
|
-
# warning. A participant gets app, version and features only
|
|
1103
|
-
# (#participant_info).
|
|
1103
|
+
# warning. A participant gets app, version and features only (#participant_info).
|
|
1104
1104
|
def handle_info(req)
|
|
1105
1105
|
return participant_info unless principal(req).owner?
|
|
1106
1106
|
|