samagotchi 0.188.0 → 0.189.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 +42 -1
- data/docs/architecture.md +5 -3
- data/docs/bundle-authoring.md +1 -1
- data/docs/bundles.md +15 -0
- data/docs/cli.md +23 -5
- data/docs/guardrails.md +3 -2
- data/docs/internals/bundles.md +3 -3
- data/docs/internals/pages.md +65 -18
- data/docs/internals/session-lifecycle.md +19 -6
- data/docs/internals/web-frontend.md +3 -3
- data/docs/internals/web-push.md +11 -5
- data/docs/pages.md +68 -15
- data/docs/peers.md +3 -0
- data/docs/plugins.md +25 -1
- data/docs/releasing.md +1 -1
- data/docs/scheduling.md +71 -8
- data/docs/sessions.md +4 -4
- data/docs/testing.md +1 -1
- data/lib/samagotchi/bundle_manifest.rb +34 -5
- data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
- data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +159 -0
- data/lib/samagotchi/bundles/system/manifest.yml +3 -3
- data/lib/samagotchi/bundles/system/self_map.md +2 -2
- data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
- data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
- data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
- data/lib/samagotchi/memory_bundle/builder.rb +1 -0
- data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
- data/lib/samagotchi/page_command.rb +9 -6
- data/lib/samagotchi/pages/bundled.rb +83 -0
- data/lib/samagotchi/pages/launch.rb +14 -2
- data/lib/samagotchi/pages/runner.rb +7 -2
- data/lib/samagotchi/pages/runtime.rb +83 -0
- data/lib/samagotchi/pages/store.rb +18 -5
- data/lib/samagotchi/pages.rb +47 -3
- data/lib/samagotchi/peer_continue.rb +14 -8
- data/lib/samagotchi/run_options.rb +1 -1
- data/lib/samagotchi/schedule_command.rb +79 -37
- data/lib/samagotchi/schedule_display.rb +69 -0
- data/lib/samagotchi/schedules/busy_part.rb +146 -0
- data/lib/samagotchi/schedules/edit_part.rb +120 -0
- data/lib/samagotchi/schedules/history_part.rb +51 -0
- data/lib/samagotchi/schedules/listing_part.rb +52 -0
- data/lib/samagotchi/schedules/notices_part.rb +116 -0
- data/lib/samagotchi/schedules/protection_part.rb +103 -0
- data/lib/samagotchi/schedules/recurrence.rb +103 -0
- data/lib/samagotchi/schedules.rb +134 -330
- data/lib/samagotchi/session_access/local.rb +9 -1
- data/lib/samagotchi/session_access/remote.rb +2 -1
- data/lib/samagotchi/session_chain/delete.rb +7 -5
- data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
- data/lib/samagotchi/session_lifecycle.rb +3 -2
- data/lib/samagotchi/session_manager/removal.rb +16 -9
- data/lib/samagotchi/session_protection.rb +99 -0
- data/lib/samagotchi/session_retention.rb +21 -6
- data/lib/samagotchi/sessions_command.rb +4 -0
- data/lib/samagotchi/testing/boundary.rb +13 -0
- data/lib/samagotchi/tools/cancel_schedule.rb +5 -2
- data/lib/samagotchi/turn_outcome.rb +41 -0
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/page_routes.rb +13 -8
- data/lib/samagotchi/web/public/app.js +12 -18
- data/lib/samagotchi/web/public/index.html +11 -2
- data/lib/samagotchi/web/public/owner_claim.js +7 -5
- data/lib/samagotchi/web/public/page_links.js +1 -1
- data/lib/samagotchi/web/public/page_view.js +8 -5
- data/lib/samagotchi/web/public/pages.css +9 -2
- data/lib/samagotchi/web/public/pages_group.js +21 -19
- data/lib/samagotchi/web/public/pages_list.js +73 -0
- data/lib/samagotchi/web/public/pages_model.js +54 -0
- data/lib/samagotchi/web/public/pages_wiring.js +66 -0
- data/lib/samagotchi/web/public/views.js +77 -23
- data/lib/samagotchi/web/push/notifier.rb +4 -3
- data/lib/samagotchi/web/server.rb +3 -1
- data/lib/samagotchi/web/session_hub.rb +64 -19
- metadata +17 -1
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../continue_offer"
|
|
4
|
+
require_relative "../log"
|
|
5
|
+
require_relative "../session"
|
|
6
|
+
require_relative "../session_inbox"
|
|
7
|
+
require_relative "../session_lifecycle"
|
|
8
|
+
require_relative "../session_manager"
|
|
9
|
+
require_relative "../session_row"
|
|
10
|
+
require_relative "../worker_link"
|
|
11
|
+
require_relative "../worker_presence"
|
|
12
|
+
|
|
13
|
+
module Samagotchi
|
|
14
|
+
class Schedules
|
|
15
|
+
# The busy check (docs/scheduling.md, "The busy check"): whether a
|
|
16
|
+
# schedule may act on its target now, or the skip and its words.
|
|
17
|
+
module BusyPart
|
|
18
|
+
# Seconds a tick waits for a live worker's GET /activity.
|
|
19
|
+
ACTIVITY_TIMEOUT = 2.0
|
|
20
|
+
# The skip words of each busy cell (SessionLifecycle::ALLOWED's
|
|
21
|
+
# sched_chain / sched_same) but :go and :worker_newer (WorkerLink::Skew's
|
|
22
|
+
# own words, #busy_words). spec/schedules_spec.rb checks every cell the
|
|
23
|
+
# table holds has words; one it misses still skips (#busy_words), so a
|
|
24
|
+
# table edit never aborts a tick.
|
|
25
|
+
BUSY_WORDS = {
|
|
26
|
+
deleting: SessionManager::DeliverResult::DELETING["detail"],
|
|
27
|
+
stopped: SessionManager::DeliverResult::STOPPED["detail"],
|
|
28
|
+
worker_busy: "its worker is starting or leaving"
|
|
29
|
+
}.freeze
|
|
30
|
+
|
|
31
|
+
private
|
|
32
|
+
|
|
33
|
+
# Two paths (FR7). The state's answer comes from the lifecycle table
|
|
34
|
+
# (#busy_cell: SessionLifecycle::ALLOWED, plus two op-local overrides);
|
|
35
|
+
# then a live worker is asked through its Bridge (#live_busy_reason)
|
|
36
|
+
# and with no worker the files say what the tick can know
|
|
37
|
+
# (#file_busy_reason). A session being deleted is a skip first, then
|
|
38
|
+
# one its owner stopped, in both modes: a schedule restarts nothing the
|
|
39
|
+
# owner stopped (deliver_turn would refuse a same-mode firing too,
|
|
40
|
+
# SessionManager::DeliverResult::STOPPED, in the same words).
|
|
41
|
+
def busy_reason(entry, links, target)
|
|
42
|
+
dir = Session.session_dir(target, state_dir: @state_dir)
|
|
43
|
+
owner = SessionManager.session_owner(target, state_dir: @state_dir)
|
|
44
|
+
presence = WorkerPresence.read(target, state_dir: @state_dir, owner: owner, link: :look)
|
|
45
|
+
# exists: true: #target_of resolved the target already, and a delete
|
|
46
|
+
# mid-way (its JSON gone, the deleting lock held) must read deleting,
|
|
47
|
+
# not absent. No extra read: SessionLifecycle.read would add a
|
|
48
|
+
# ContinueIntent read this check doesn't use.
|
|
49
|
+
state = SessionLifecycle::Reading.derive(presence.with(exists: true)).state
|
|
50
|
+
cell = busy_cell(entry, presence, state)
|
|
51
|
+
return [:skip, busy_words(cell, presence.link)] unless cell == :go
|
|
52
|
+
return live_busy_reason(entry, links, target, presence.link) if state == :live
|
|
53
|
+
|
|
54
|
+
file_busy_reason(links.session(target), dir)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# The table's cell for this mode in +state+, then the two facts the
|
|
58
|
+
# state doesn't hold, read in today's order (spec/session_lifecycle/
|
|
59
|
+
# matrix_spec.rb's KNOWN_DIFFERENCES name both):
|
|
60
|
+
# - the stop marker before the owner (F1, chain and same; an unknown
|
|
61
|
+
# owner's stop too): stopped under any lock but a deleter's;
|
|
62
|
+
# - F1b: chain mode's starting check with no one-turn-run check: a
|
|
63
|
+
# fresh starting marker without a worker's lock is worker_busy (a
|
|
64
|
+
# worker being started for it holds no lock yet: a chain firing would
|
|
65
|
+
# archive it from under that worker; a queued turn is fine).
|
|
66
|
+
def busy_cell(entry, presence, state)
|
|
67
|
+
chain = entry.mode == CHAIN
|
|
68
|
+
cell = SessionLifecycle.allowed(chain ? :sched_chain : :sched_same, state)
|
|
69
|
+
return :stopped if presence.stop_marked? && cell != :deleting
|
|
70
|
+
return :worker_busy if chain && cell == :go && presence.starting? && !presence.worker_owned?
|
|
71
|
+
|
|
72
|
+
cell
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# A newer worker's Bridge cannot be asked (:worker_newer); updating chi
|
|
76
|
+
# or restarting chi web fixes it, and max_skips still bounds a stuck
|
|
77
|
+
# schedule. A worker that has not published its Bridge yet, or is
|
|
78
|
+
# closing it (:worker_busy): nothing can be read from it, and firing
|
|
79
|
+
# now would race with it.
|
|
80
|
+
def busy_words(cell, link)
|
|
81
|
+
return link.short_message if cell == :worker_newer
|
|
82
|
+
|
|
83
|
+
BUSY_WORDS.fetch(cell) { "it is not free now (#{cell})" }
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# A live worker, asked through its Bridge.
|
|
87
|
+
def live_busy_reason(entry, links, target, link)
|
|
88
|
+
activity = ask_activity(link, target)
|
|
89
|
+
if activity == :old
|
|
90
|
+
# Its chi predates GET /activity. The file checks cannot see an open
|
|
91
|
+
# tab, so a chain firing would archive under someone's terminal:
|
|
92
|
+
# refuse with a restart, never silently degrade. Same mode only
|
|
93
|
+
# queues a turn, so for it the files are enough.
|
|
94
|
+
return [:skip, "its worker is too old to ask: chi sessions restart #{target[0, 8]}"] if entry.mode == CHAIN
|
|
95
|
+
|
|
96
|
+
return file_busy_reason(links.session(target), Session.session_dir(target, state_dir: @state_dir))
|
|
97
|
+
end
|
|
98
|
+
return [:skip, "its worker is not answering"] if activity.nil?
|
|
99
|
+
|
|
100
|
+
return [:skip, "a turn is running in it"] if activity[:turn_running]
|
|
101
|
+
return [:skip, "a prompt is queued for it"] if activity[:input_pending]
|
|
102
|
+
return [:skip, "its step-limit question waits for an answer"] if activity[:awaiting_continue]
|
|
103
|
+
|
|
104
|
+
# A chain firing archives the session and stops its worker: a
|
|
105
|
+
# terminal or a web tab on it would be cut off. A queued turn into
|
|
106
|
+
# an open session is fine, so same mode does not count streams.
|
|
107
|
+
return [:skip, "a terminal or a web tab is open on it"] if entry.mode == CHAIN && activity[:open_streams].to_i.positive?
|
|
108
|
+
|
|
109
|
+
# An idle live worker: free, whatever a starting marker its own
|
|
110
|
+
# start left (Worker#start clears it just after the lock).
|
|
111
|
+
nil
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# The worker's activity snapshot, :old when it has no /activity route, or
|
|
115
|
+
# nil when it did not answer at all. A worker published its features when
|
|
116
|
+
# it started, so a sidecar without "activity" is an older chi's: asking it
|
|
117
|
+
# would only cost a round trip to a 404.
|
|
118
|
+
def ask_activity(link, session_id)
|
|
119
|
+
return :old unless Array(link.features).include?(WorkerLink::ACTIVITY_FEATURE)
|
|
120
|
+
|
|
121
|
+
status, body = link.client(session_id, read_timeout: ACTIVITY_TIMEOUT).get("activity")
|
|
122
|
+
return nil if status.nil?
|
|
123
|
+
return body.transform_keys(&:to_sym) if status == 200 && body.is_a?(Hash)
|
|
124
|
+
|
|
125
|
+
:old
|
|
126
|
+
rescue StandardError => e
|
|
127
|
+
Log.warn(:worker, "activity_failed", sid: session_id, error: e.class.name, msg: e.message)
|
|
128
|
+
nil
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# The signals RemovalPart#archive_refusal reads, from the files alone.
|
|
132
|
+
def file_busy_reason(session, dir)
|
|
133
|
+
return nil if session.nil?
|
|
134
|
+
|
|
135
|
+
if SessionRow.running_or_starting?(saved_status: session.status, live: false, busy: false, updated_at: session.updated_at)
|
|
136
|
+
return [:skip, "a turn is running in it"]
|
|
137
|
+
end
|
|
138
|
+
return [:skip, "a prompt is queued for it"] unless SessionInbox.find_new_input_files(dir).empty?
|
|
139
|
+
|
|
140
|
+
return [:skip, "its step-limit question waits for an answer"] if session.waiting_question(live: false)&.dig(:kind) == ContinueOffer::KIND
|
|
141
|
+
|
|
142
|
+
nil
|
|
143
|
+
end
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
end
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Samagotchi
|
|
4
|
+
class Schedules
|
|
5
|
+
# `chi schedule edit` (docs/scheduling.md): change a schedule's title,
|
|
6
|
+
# prompt, recurrence, catch-up or budgets in place, keeping its id, its
|
|
7
|
+
# session and mode (cancel and add for those), its counters, `enabled`
|
|
8
|
+
# (a spent `date` one-off stays disabled) and the firing fields.
|
|
9
|
+
module EditPart
|
|
10
|
+
# A recurrence edit while a firing is in flight: a state, not a usage
|
|
11
|
+
# error (`chi schedule edit` exits 1).
|
|
12
|
+
class InFlight < StandardError
|
|
13
|
+
def initialize(msg = "a run is in progress; edit the time after it settles") = super
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Each argument nil keeps the field; only the fields given change.
|
|
17
|
+
# @param recurrence [Hash, nil] a whole one, from Schedules.recurrence
|
|
18
|
+
# @return [Entry, nil] the entry as edited; nil when no schedule matches
|
|
19
|
+
# (or it is gone by the time the lock is held)
|
|
20
|
+
# @raise [Usage] nothing to change, a field that is wrong, a duplicate
|
|
21
|
+
# in the chain
|
|
22
|
+
# @raise [InFlight] a recurrence edit while a firing is in flight
|
|
23
|
+
def edit(id_or_name, title: nil, prompt: nil, recurrence: nil, catch_up: nil, keep_links: nil, max_failures: nil,
|
|
24
|
+
max_skips: nil)
|
|
25
|
+
entry = lookup(id_or_name)
|
|
26
|
+
return nil if entry.nil?
|
|
27
|
+
|
|
28
|
+
changes = differing(entry, edit_changes(title: title, prompt: prompt, recurrence: recurrence, catch_up: catch_up,
|
|
29
|
+
keep_links: keep_links, max_failures: max_failures, max_skips: max_skips))
|
|
30
|
+
raise Usage, "nothing to change" if changes.empty?
|
|
31
|
+
|
|
32
|
+
# Each duplicate test only on what the edit changes: a clash in a field
|
|
33
|
+
# it leaves alone (a twin `enable` let in) is not of its making.
|
|
34
|
+
by_title = changes.key?(:title)
|
|
35
|
+
by_content = changes.key?(:prompt) || changes.key?(:recurrence)
|
|
36
|
+
if by_title || by_content
|
|
37
|
+
same = duplicate_in_chain(entry.anchor, prompt: changes.fetch(:prompt, entry.prompt),
|
|
38
|
+
title: changes.fetch(:title, entry.title),
|
|
39
|
+
recurrence: changes.fetch(:recurrence, entry.recurrence), except: entry.id,
|
|
40
|
+
by_title: by_title, by_content: by_content)
|
|
41
|
+
refuse_duplicate!(same, entry.mode) if same
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
result = nil
|
|
45
|
+
write_under_lock do |file|
|
|
46
|
+
position = file.entries.index { |candidate| candidate.is_a?(Entry) && candidate.id == entry.id }
|
|
47
|
+
next if position.nil?
|
|
48
|
+
|
|
49
|
+
result = file.entries[position] = edited(file.entries[position], changes)
|
|
50
|
+
end
|
|
51
|
+
result
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# The duplicate rule #add and #edit share: an enabled schedule of the
|
|
55
|
+
# same chain that says the same thing, the same prompt and recurrence
|
|
56
|
+
# or the same title. An edit passes +except+ (its own entry is no
|
|
57
|
+
# duplicate of itself) and turns off the test whose fields it leaves
|
|
58
|
+
# alone (+by_content+: the prompt and recurrence; +by_title+).
|
|
59
|
+
# @return [Entry, nil]
|
|
60
|
+
def duplicate_in_chain(session_id, prompt:, title:, recurrence:, except: nil, by_content: true, by_title: true)
|
|
61
|
+
given_title = title.to_s.strip
|
|
62
|
+
ids = chain_of(session_id)
|
|
63
|
+
entries.find do |entry|
|
|
64
|
+
next if entry.id == except
|
|
65
|
+
next unless ids.include?(entry.anchor) || ids.include?(entry.head)
|
|
66
|
+
|
|
67
|
+
(by_content && entry.prompt == prompt && entry.recurrence == recurrence) ||
|
|
68
|
+
(by_title && !given_title.empty? && entry.title.to_s.strip.casecmp?(given_title))
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# @raise [Usage] naming the schedule that already says the same thing
|
|
73
|
+
def refuse_duplicate!(same, mode)
|
|
74
|
+
raise Usage, "#{same.id} already schedules this (#{same.recurrence_words}, #{mode}: #{same.prompt}); " \
|
|
75
|
+
"cancel it with chi schedule cancel #{same.id} to change it"
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
private
|
|
79
|
+
|
|
80
|
+
# The +changes+ whose value is not +entry+'s already (`--title ""` on
|
|
81
|
+
# an untitled entry changes nothing).
|
|
82
|
+
def differing(entry, changes) = changes.reject { |field, value| entry.public_send(field) == value }
|
|
83
|
+
|
|
84
|
+
# The fields given, checked as #add checks them.
|
|
85
|
+
def edit_changes(title:, prompt:, recurrence:, catch_up:, **budgets)
|
|
86
|
+
changes = {}
|
|
87
|
+
changes[:title] = title.to_s.strip.empty? ? nil : title.to_s.strip unless title.nil?
|
|
88
|
+
changes[:prompt] = validate_prompt!(prompt) unless prompt.nil?
|
|
89
|
+
changes[:recurrence] = recurrence unless recurrence.nil?
|
|
90
|
+
unless catch_up.nil?
|
|
91
|
+
changes[:catch_up] = catch_up.to_s.strip
|
|
92
|
+
validate_catch_up!(changes[:catch_up])
|
|
93
|
+
end
|
|
94
|
+
{ keep_links: 0, max_failures: 1, max_skips: 1 }.each do |field, min|
|
|
95
|
+
value = int_value(budgets[field], min: min, name: field.to_s)
|
|
96
|
+
changes[field] = value unless value.nil?
|
|
97
|
+
end
|
|
98
|
+
changes
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# +stored+ with +changes+, under the lock. A new recurrence's clock
|
|
102
|
+
# starts now, as #add's does; while a firing is in flight it is refused:
|
|
103
|
+
# #record would put that firing's due_was back over the new clock.
|
|
104
|
+
def edited(stored, changes)
|
|
105
|
+
# Against the entry as stored now: what another writer already set is no change.
|
|
106
|
+
changes = differing(stored, changes)
|
|
107
|
+
return stored if changes.empty?
|
|
108
|
+
|
|
109
|
+
now = @clock.call
|
|
110
|
+
updated = stored.with(**changes)
|
|
111
|
+
if changes.key?(:recurrence)
|
|
112
|
+
raise InFlight if stored.firing_since || stored.pending_turn_id
|
|
113
|
+
|
|
114
|
+
updated = updated.with(next_due: next_due_for(changes[:recurrence], from: now).utc.iso8601, due_was: nil)
|
|
115
|
+
end
|
|
116
|
+
with_history(updated, "edited", changes.keys.join(", "), at: now)
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
end
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Samagotchi
|
|
4
|
+
class Schedules
|
|
5
|
+
# The run history (docs/scheduling.md, `chi schedule show`): each entry
|
|
6
|
+
# keeps its last HISTORY_MAX outcomes in `history`, newest last, rows
|
|
7
|
+
# {at:, status:, detail:, session_id:}. One writer per status, each
|
|
8
|
+
# appending once per event:
|
|
9
|
+
# skipped, failed — #skipped / #failed (the helpers, never their
|
|
10
|
+
# callers), and #run_now's refusal of a disabled entry (no counters);
|
|
11
|
+
# a budget turn-off is that row, its detail "disabled: <reason>"
|
|
12
|
+
# fired — #finish_pending (a firing that settles) and #record's "fired"
|
|
13
|
+
# missed — #reschedule
|
|
14
|
+
# enabled, disabled — #change (the owner's; never a budget turn-off)
|
|
15
|
+
# edited — #edit, its detail the changed fields
|
|
16
|
+
# A pending firing writes no row: it is not an outcome yet.
|
|
17
|
+
module HistoryPart
|
|
18
|
+
HISTORY_MAX = 20
|
|
19
|
+
# A detail is clipped to this many characters (an exception's message
|
|
20
|
+
# or a turn's reason can be long): with the row's other fields (~120
|
|
21
|
+
# bytes) an entry's history stays under about 20 × 320 bytes, 6.4 KB.
|
|
22
|
+
DETAIL_MAX = 200
|
|
23
|
+
|
|
24
|
+
# The rows as JSON hands them back (string keys) or as written (symbol
|
|
25
|
+
# keys): symbol keys, non-rows dropped.
|
|
26
|
+
# @return [Array<Hash>]
|
|
27
|
+
def self.rows(value)
|
|
28
|
+
Array(value).filter_map { |row| row.transform_keys(&:to_sym) if row.is_a?(Hash) }
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
private
|
|
32
|
+
|
|
33
|
+
# A skip's or a failure's row (+before+ the call, +after+ it), and the
|
|
34
|
+
# disabled notice when this call turned the entry off by its budget.
|
|
35
|
+
# Its session: the pending firing's, else the head.
|
|
36
|
+
def recorded(before, after, status, reason, now)
|
|
37
|
+
off = budget_turned_off?(before, after, status)
|
|
38
|
+
noticed = with_disabled_notice(before, after, status, reason, now)
|
|
39
|
+
with_history(noticed, status, off ? "disabled: #{reason}" : reason, at: now,
|
|
40
|
+
session_id: before.pending_session_id || before.head)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# +entry+ with one row more, the oldest dropped past HISTORY_MAX.
|
|
44
|
+
def with_history(entry, status, detail, at:, session_id: nil)
|
|
45
|
+
clipped = detail.nil? ? nil : detail.to_s[0, DETAIL_MAX]
|
|
46
|
+
row = { at: at.utc.iso8601, status: status, detail: clipped, session_id: session_id }
|
|
47
|
+
entry.with(history: (HistoryPart.rows(entry.history) + [row]).last(HISTORY_MAX))
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "time"
|
|
4
|
+
require_relative "../config"
|
|
5
|
+
|
|
6
|
+
module Samagotchi
|
|
7
|
+
class Schedules
|
|
8
|
+
# What a reader is told of the store without changing it: the tick
|
|
9
|
+
# warning (`chi schedule list`, `add`) and #listing (Pages::Runtime's
|
|
10
|
+
# one read).
|
|
11
|
+
module ListingPart
|
|
12
|
+
# The warning `chi schedule` prints when nothing ticks (auto_tick off and
|
|
13
|
+
# no tick in two intervals), nil when something does.
|
|
14
|
+
def tick_warning(now: @clock.call) = tick_warning_for(read.attributes[:last_tick_at], now)
|
|
15
|
+
|
|
16
|
+
# Every schedule as the file holds it now, for a reader that shows them
|
|
17
|
+
# (Pages::Runtime#schedules): one strict read, no lock, no write, and no
|
|
18
|
+
# notice claimed (#claim_disabled_notices is chi web's). +entries+ the
|
|
19
|
+
# readable ones, the earliest due first (as #entries with
|
|
20
|
+
# include_disabled); +unreadable_ids+ the id of each entry that doesn't
|
|
21
|
+
# read (nil for one with none); +warning+ #tick_warning's text, from the
|
|
22
|
+
# same read.
|
|
23
|
+
Listing = Data.define(:entries, :unreadable_ids, :warning)
|
|
24
|
+
|
|
25
|
+
# @return [Listing]
|
|
26
|
+
# @raise [Corrupt] schedules.json isn't readable JSON (#entries reads it
|
|
27
|
+
# as no schedules)
|
|
28
|
+
def listing(now: @clock.call)
|
|
29
|
+
file = read(strict: true)
|
|
30
|
+
entries = file.entries.grep(Entry).sort_by { |entry| [entry.next_due.to_s, entry.id] }
|
|
31
|
+
unreadable = file.entries.grep_v(Entry).map { |record| record.raw.is_a?(Hash) ? record.raw["id"]&.to_s : nil }
|
|
32
|
+
Listing.new(entries: entries, unreadable_ids: unreadable, warning: tick_warning_for(file.attributes[:last_tick_at], now))
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
private
|
|
36
|
+
|
|
37
|
+
# #tick_warning's rule, given the file's last_tick_at.
|
|
38
|
+
def tick_warning_for(last_tick_at, now)
|
|
39
|
+
return if Config.get("schedule.auto_tick")
|
|
40
|
+
|
|
41
|
+
stale_after = self.class.tick_interval_minutes * 120
|
|
42
|
+
return if last_tick_at && now - Time.iso8601(last_tick_at.to_s) <= stale_after
|
|
43
|
+
|
|
44
|
+
"Warning: no schedule tick in the last #{stale_after / 60} minutes; set schedule.auto_tick: true or " \
|
|
45
|
+
"run `chi schedule tick` from cron."
|
|
46
|
+
rescue ArgumentError
|
|
47
|
+
"Warning: no schedule tick in the last #{self.class.tick_interval_minutes * 2} minutes; " \
|
|
48
|
+
"set schedule.auto_tick: true or run `chi schedule tick` from cron."
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "time"
|
|
5
|
+
|
|
6
|
+
module Samagotchi
|
|
7
|
+
class Schedules
|
|
8
|
+
# The disabled notice (docs/scheduling.md): a recurring schedule a ticker
|
|
9
|
+
# turned off by its budget carries {kind:, count:, reason:, at:} in
|
|
10
|
+
# `disabled_notice` until a chi web claims it and pushes it. Set by
|
|
11
|
+
# #skipped / #failed, whatever ran them (a cron tick, a run-now, chi
|
|
12
|
+
# web's own tick); claimed by SessionHub#publish_disabled.
|
|
13
|
+
module NoticesPart
|
|
14
|
+
# The disabled notices whatever ticker set them (#skipped / #failed: a
|
|
15
|
+
# cron `chi schedule tick`, a `run-now`, chi web's own tick), each cleared
|
|
16
|
+
# here and returned once, for chi web's hub to push (SessionHub
|
|
17
|
+
# #publish_disabled). A lock-free read first: with no notice (the usual
|
|
18
|
+
# case) nothing is locked or written. Then the lock, non-blocking: a tick
|
|
19
|
+
# can hold it for seconds through its busy checks, and the hub's scan must
|
|
20
|
+
# not wait; [] then, and the next pass retries. The notices are cleared
|
|
21
|
+
# before the hub emits them (at most once): the Notifier dedupes only
|
|
22
|
+
# within its own process, so two chi webs on one state dir must not both
|
|
23
|
+
# get the same notice; a crash between the clear and the push loses one
|
|
24
|
+
# push, never sends two. An entry enabled again since (an older chi's
|
|
25
|
+
# `enable` keeps the notice) and a notice older than NOTICE_MAX_AGE are
|
|
26
|
+
# cleared without being returned.
|
|
27
|
+
# @param now [Time]
|
|
28
|
+
# @return [Array<Hash>] {id:, title:, kind:, count:, reason:, session_id:, at:}
|
|
29
|
+
# @raise [Corrupt] the file stopped being readable JSON
|
|
30
|
+
def claim_disabled_notices(now: @clock.call)
|
|
31
|
+
return [] unless read.entries.any? { |entry| entry.is_a?(Entry) && entry.disabled_notice }
|
|
32
|
+
|
|
33
|
+
claimed = []
|
|
34
|
+
FileUtils.mkdir_p(@store_dir)
|
|
35
|
+
File.open(lock_path, File::RDWR | File::CREAT, 0o600) do |lock|
|
|
36
|
+
return [] unless lock.flock(File::LOCK_EX | File::LOCK_NB)
|
|
37
|
+
|
|
38
|
+
file = read(strict: true)
|
|
39
|
+
links = nil
|
|
40
|
+
cleared = false
|
|
41
|
+
file.entries.each_with_index do |entry, position|
|
|
42
|
+
next unless entry.is_a?(Entry) && entry.disabled_notice
|
|
43
|
+
|
|
44
|
+
notice = entry.disabled_notice
|
|
45
|
+
file.entries[position] = entry.with(disabled_notice: nil)
|
|
46
|
+
cleared = true
|
|
47
|
+
next if entry.enabled || notice_stale?(notice, now)
|
|
48
|
+
|
|
49
|
+
links ||= links_now
|
|
50
|
+
claimed << { id: entry.id, title: entry.title, kind: notice[:kind], count: notice[:count],
|
|
51
|
+
reason: notice[:reason], session_id: target_of(entry, links).first || entry.head,
|
|
52
|
+
at: notice[:at] }
|
|
53
|
+
end
|
|
54
|
+
write(file: file) if cleared
|
|
55
|
+
end
|
|
56
|
+
claimed
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
private
|
|
60
|
+
|
|
61
|
+
# The skips and failures that turned off a recurring entry that was on when
|
|
62
|
+
# the pass began (+before+), as the file has it now: one diff covers every
|
|
63
|
+
# path that records one. A `date` one-off is spent, not disabled; an entry
|
|
64
|
+
# off within budget is an owner's `chi schedule disable`. The same rule
|
|
65
|
+
# (#budget_turned_off?) sets the entry's disabled notice; this cannot read
|
|
66
|
+
# that notice back, since a chi web may have claimed it by now.
|
|
67
|
+
def mark_disabled(outcomes, before, links: nil)
|
|
68
|
+
status_by_id = outcomes.select { |outcome| %w[skipped failed].include?(outcome.status) }
|
|
69
|
+
.to_h { |outcome| [outcome.id, outcome.status] }
|
|
70
|
+
on = before.select { |entry| status_by_id.key?(entry.id) }.to_h { |entry| [entry.id, entry] }
|
|
71
|
+
return outcomes if on.empty?
|
|
72
|
+
|
|
73
|
+
off = read.entries.grep(Entry).select do |entry|
|
|
74
|
+
on.key?(entry.id) && budget_turned_off?(on[entry.id], entry, status_by_id[entry.id])
|
|
75
|
+
end
|
|
76
|
+
links ||= links_now unless off.empty?
|
|
77
|
+
off.each do |entry|
|
|
78
|
+
index = outcomes.rindex { |outcome| outcome.id == entry.id && %w[skipped failed].include?(outcome.status) }
|
|
79
|
+
session_id = target_of(entry, links).first || entry.head
|
|
80
|
+
outcomes[index] = outcomes[index].with(disabled: true, entry: entry, session_id: session_id)
|
|
81
|
+
end
|
|
82
|
+
outcomes
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# "This skip or failure turned the entry off by its budget": +before+ was a
|
|
86
|
+
# recurring entry that was on, +after+ is off with the +status+'s counter
|
|
87
|
+
# at its budget. A `date` one-off is spent, not disabled; an entry off
|
|
88
|
+
# within budget is an owner's disable. #skipped / #failed set the
|
|
89
|
+
# disabled notice on it, #mark_disabled the CLI's `(disabled)`.
|
|
90
|
+
def budget_turned_off?(before, after, status)
|
|
91
|
+
return false unless before.enabled && before.recurrence[:kind] != "date" && !after.enabled
|
|
92
|
+
|
|
93
|
+
case status
|
|
94
|
+
when "skipped" then after.skips >= after.max_skips
|
|
95
|
+
when "failed" then after.failures >= after.max_failures
|
|
96
|
+
else false
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# The notice a chi web pushes for a budget turn-off (#claim_disabled_notices),
|
|
101
|
+
# when this +status+ call turned +before+ off; +after+ unchanged otherwise.
|
|
102
|
+
def with_disabled_notice(before, after, status, reason, now)
|
|
103
|
+
return after unless budget_turned_off?(before, after, status)
|
|
104
|
+
|
|
105
|
+
count = status == "skipped" ? after.skips : after.failures
|
|
106
|
+
after.with(disabled_notice: { kind: status, count: count, reason: reason, at: now.utc.iso8601 })
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def notice_stale?(notice, now)
|
|
110
|
+
Time.iso8601(notice[:at].to_s) + NOTICE_MAX_AGE < now
|
|
111
|
+
rescue ArgumentError
|
|
112
|
+
true
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require_relative "../session_protection"
|
|
5
|
+
require_relative "../state_format"
|
|
6
|
+
|
|
7
|
+
module Samagotchi
|
|
8
|
+
class Schedules
|
|
9
|
+
# Schedules as a SessionProtection protector: an enabled schedule holds
|
|
10
|
+
# its anchor, its head and its resolved target (#target_of). A disabled
|
|
11
|
+
# one holds nothing. The file is read strict (#protection_entries): one
|
|
12
|
+
# that is there but doesn't read, or holds an entry that doesn't, raises
|
|
13
|
+
# SessionProtection::Unreadable (the tick and the other readers keep
|
|
14
|
+
# their own rules; chi schedule cancel ID drops such an entry,
|
|
15
|
+
# #cancel_unreadable). A missing file holds nothing.
|
|
16
|
+
module ProtectionPart
|
|
17
|
+
# @return [Array<String>] the ids retention keeps
|
|
18
|
+
def protected_ids
|
|
19
|
+
links = links_now
|
|
20
|
+
protection_entries.flat_map { |entry| [entry.anchor, entry.head, target_of(entry, links).first] }.compact.uniq
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# The enabled schedule a delete of +session_id+ would break: one whose
|
|
24
|
+
# anchor or head it is, else one whose target (#protecting) it is. A
|
|
25
|
+
# head deleted would make the schedule fall back to its anchor (an
|
|
26
|
+
# archived link) and fail.
|
|
27
|
+
# @return [SessionProtection::Hold, nil] reason :scheduled
|
|
28
|
+
def hold(session_id)
|
|
29
|
+
list = protection_entries
|
|
30
|
+
entry = list.find { |candidate| candidate.anchor == session_id || candidate.head == session_id } ||
|
|
31
|
+
protecting(session_id, list)
|
|
32
|
+
entry && SessionProtection::Hold.new(session_id: session_id, reason: :scheduled, ref: entry.id)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# The first enabled schedule on the chain +session_id+ belongs to (as
|
|
36
|
+
# #for_chain: its anchor or head a link of it), which a chain's delete
|
|
37
|
+
# would take.
|
|
38
|
+
# @return [SessionProtection::Hold, nil] reason :chain_scheduled
|
|
39
|
+
def chain_hold(session_id)
|
|
40
|
+
ids = chain_of(session_id)
|
|
41
|
+
entry = protection_entries.find { |candidate| ids.include?(candidate.anchor) || ids.include?(candidate.head) }
|
|
42
|
+
entry && SessionProtection::Hold.new(session_id: session_id, reason: :chain_scheduled, ref: entry.id)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
private
|
|
46
|
+
|
|
47
|
+
def protecting(session_id, list)
|
|
48
|
+
links = links_now
|
|
49
|
+
list.find { |entry| target_of(entry, links).first == session_id }
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# The enabled entries, the earliest due first (as #entries), from a
|
|
53
|
+
# strict read of its own: no log line (the caller logs the refusal
|
|
54
|
+
# once), a `schedules` member that isn't a list, a file chi can't open
|
|
55
|
+
# (permissions, a directory) and one entry that doesn't read are all
|
|
56
|
+
# Unreadable. A missing file holds nothing.
|
|
57
|
+
# @raise [SessionProtection::Unreadable]
|
|
58
|
+
def protection_entries
|
|
59
|
+
return [] unless File.exist?(path)
|
|
60
|
+
|
|
61
|
+
raw = JSON.parse(File.read(path))
|
|
62
|
+
if raw.is_a?(Hash) && raw.key?("schedules") && !raw["schedules"].is_a?(Array)
|
|
63
|
+
raise StateFormat::InvalidDocument, "schedules must be a list"
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
records = FORMAT.read(raw, collection: "schedules").entries
|
|
67
|
+
bad = records.find { |record| !record.readable? }
|
|
68
|
+
raise unreadable_entry(bad) if bad
|
|
69
|
+
|
|
70
|
+
records.map { |record| Entry.from_record(record) }.select(&:enabled).sort_by { |entry| [entry.next_due.to_s, entry.id] }
|
|
71
|
+
rescue JSON::ParserError, StateFormat::InvalidDocument, SystemCallError => e
|
|
72
|
+
raise SessionProtection::Unreadable.new(FILE, e.message)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# One entry that doesn't read: named by its id when it has one, so
|
|
76
|
+
# chi schedule cancel can drop it (#cancel_unreadable).
|
|
77
|
+
def unreadable_entry(record)
|
|
78
|
+
id = record.raw.is_a?(Hash) ? record.raw["id"] : nil
|
|
79
|
+
lacks = "lacks #{record.missing.join(", ")}"
|
|
80
|
+
return SessionProtection::Unreadable.new(FILE, lacks, entry: id) if id.is_a?(String) && !id.empty?
|
|
81
|
+
|
|
82
|
+
SessionProtection::Unreadable.new(FILE, "a schedule without an id #{lacks}")
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# chi schedule cancel ID of a record #read keeps but can't read (#entries
|
|
86
|
+
# and #lookup never see it): removed by its exact id, under the lock,
|
|
87
|
+
# the way out of an Unreadable hold. nil when there is none.
|
|
88
|
+
def cancel_unreadable(id)
|
|
89
|
+
unreadable = ->(record) { !record.is_a?(Entry) && record.raw.is_a?(Hash) && record.raw["id"] == id }
|
|
90
|
+
# The lenient read first: a store that isn't JSON has no such record
|
|
91
|
+
# and stays as it is (no strict read, no rewrite).
|
|
92
|
+
return nil unless read.entries.any?(&unreadable)
|
|
93
|
+
|
|
94
|
+
removed = nil
|
|
95
|
+
write_under_lock do |file|
|
|
96
|
+
removed = file.entries.find(&unreadable)
|
|
97
|
+
file.entries.delete(removed) if removed
|
|
98
|
+
end
|
|
99
|
+
removed
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|