yorha 1.9.4

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.
@@ -0,0 +1,187 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Crash reporting (Systems layer).
4
+ #
5
+ # Design document reference: section 5.8, Yorha::BlackBox and
6
+ # Yorha::CrashHandler.
7
+ #
8
+ # Responsibility:
9
+ # Render uncaught exceptions as a damage report, then get out of
10
+ # the way (principle P4).
11
+ #
12
+ # This file does not:
13
+ # - Swallow, rewrite, or reorder exceptions.
14
+ # - Install anything at require time; CrashHandler.install is
15
+ # explicitly called by the user (principle P2).
16
+ #
17
+ # Invariants:
18
+ # - Yorha.black_box re-raises the original exception object.
19
+ # - Reports go to the err stream, never $stdout.
20
+ # - BlackBox.report is a pure function; it writes nothing.
21
+
22
+ require "stringio"
23
+ require_relative "widgets"
24
+
25
+ module Yorha
26
+ module BlackBox
27
+ # Default backtrace depth for reports.
28
+ DEFAULT_FRAMES = 6
29
+
30
+ class << self
31
+ # Extracts report data as a plain Hash.
32
+ #
33
+ # This is the documented extension point for companion gems:
34
+ # yorha-rails renders the same data as an HTML error page.
35
+ #
36
+ # @param exception [Exception] the exception to describe
37
+ # @param unit [String, nil] unit name; defaults to config
38
+ # @param frames [Integer, nil] backtrace entries to keep;
39
+ # nil keeps every entry
40
+ # @return [Hash{Symbol => Object}] class, message, frames,
41
+ # archived_frames, unit
42
+ # @api public
43
+ def report_data(exception, unit: nil, frames: nil)
44
+ backtrace = Array(exception.backtrace)
45
+ selected, archived = truncate(backtrace, frames)
46
+
47
+ {
48
+ class: exception.class.name,
49
+ message: safe_message(exception),
50
+ frames: selected,
51
+ archived_frames: archived,
52
+ unit: unit || Yorha.config.unit
53
+ }
54
+ end
55
+
56
+ # Renders a damage report without writing it anywhere.
57
+ #
58
+ # Rendering happens through Widgets.system_message with a
59
+ # StringIO sink, so capabilities are probed against the target
60
+ # stream while the text is returned as a String.
61
+ #
62
+ # If rendering itself raises, the method falls back to
63
+ # Exception#full_message so the user still sees the real error.
64
+ #
65
+ # @param exception [Exception] the exception to report
66
+ # @param unit [String, nil] unit name; defaults to config
67
+ # @param io [#write, nil] stream whose capabilities are probed
68
+ # @param frames [Integer, nil] backtrace entries to keep
69
+ # @return [String] the rendered report
70
+ # @api public
71
+ def report(exception, unit: nil, io: nil, frames: DEFAULT_FRAMES)
72
+ stream = io || Yorha.config.err
73
+ data = report_data(exception, unit: unit, frames: frames)
74
+
75
+ Yorha::Widgets.system_message("BLACK BOX - DAMAGE REPORT", report_body(data), io: stream, sink: StringIO.new)
76
+ rescue StandardError
77
+ exception.full_message
78
+ end
79
+
80
+ private
81
+
82
+ # Builds the report body lines.
83
+ #
84
+ # @param data [Hash{Symbol => Object}] from report_data
85
+ # @return [String]
86
+ def report_body(data)
87
+ lines = ["UNIT: #{data[:unit]}", "CLASS: #{data[:class]}", "MESSAGE: #{data[:message]}", "BACKTRACE:"]
88
+
89
+ data[:frames].each { |frame| lines << " #{frame}" }
90
+
91
+ if data[:archived_frames].positive?
92
+ lines << "... +#{data[:archived_frames]} archived entries"
93
+ end
94
+
95
+ lines.join("\n")
96
+ end
97
+
98
+ # Splits a backtrace into kept and archived entries.
99
+ #
100
+ # @param backtrace [Array<String>]
101
+ # @param frames [Integer, nil] entries to keep; nil keeps all
102
+ # @return [Array<Array<String>>, Integer] kept lines, archived
103
+ def truncate(backtrace, frames)
104
+ return [backtrace, 0] if frames.nil? || backtrace.length <= frames
105
+
106
+ [backtrace.first(frames), backtrace.length - frames]
107
+ end
108
+
109
+ # Reads an exception message without letting a broken message
110
+ # method break the report.
111
+ #
112
+ # @param exception [Exception]
113
+ # @return [String]
114
+ def safe_message(exception)
115
+ exception.message
116
+ rescue StandardError
117
+ "(message unavailable)"
118
+ end
119
+ end
120
+ end
121
+
122
+ # Whole-process crash reporting hook.
123
+ #
124
+ # Design document reference: section 5.8, Yorha::CrashHandler.
125
+ #
126
+ # install is idempotent: a second call is a no-op, so Rails
127
+ # reloading cannot double-install the hook. Normal exits, breaks,
128
+ # and signals are never reported.
129
+ module CrashHandler
130
+ @installed = false
131
+
132
+ class << self
133
+ # Reports whether the at_exit hook is installed.
134
+ #
135
+ # @return [Boolean]
136
+ # @api public
137
+ def installed?
138
+ @installed
139
+ end
140
+
141
+ # Installs the whole-process at_exit hook.
142
+ #
143
+ # Call once, from an initializer or entrypoint. The hook writes
144
+ # a Black Box report to the configured err stream for any
145
+ # uncaught StandardError, and ignores SystemExit, Interrupt,
146
+ # and SignalException so exit codes and Ctrl+C pass through
147
+ # untouched.
148
+ #
149
+ # @param unit [String, nil] unit name; defaults to config
150
+ # @param io [#write, nil] report stream; defaults to config err
151
+ # @return [Boolean] true when installed, false when already
152
+ # installed
153
+ # @api public
154
+ def install(unit: nil, io: nil)
155
+ return false if @installed
156
+
157
+ @installed = true
158
+
159
+ chosen_unit = unit
160
+ stream = io
161
+
162
+ at_exit do
163
+ exception = $!
164
+
165
+ next if exception.nil?
166
+ next if exception.is_a?(SystemExit)
167
+ next if exception.is_a?(Interrupt)
168
+ next if exception.is_a?(SignalException)
169
+
170
+ report = begin
171
+ Yorha::BlackBox.report(exception, unit: chosen_unit, io: stream, frames: Yorha::BlackBox::DEFAULT_FRAMES)
172
+ rescue StandardError
173
+ exception.full_message
174
+ end
175
+
176
+ begin
177
+ (stream || Yorha.config.err).write(report)
178
+ rescue StandardError
179
+ nil
180
+ end
181
+ end
182
+
183
+ true
184
+ end
185
+ end
186
+ end
187
+ end
@@ -0,0 +1,317 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Capacity-budgeted feature registry for YoRHa.
4
+ #
5
+ # Responsibilities:
6
+ # - Register named features as chips.
7
+ # - Prevent installations that exceed the available capacity.
8
+ # - Avoid double-counting duplicate installations.
9
+ # - Provide separate Registry instances when scoped state is needed.
10
+ # - Expose a default process-wide registry.
11
+ #
12
+ # The errors this file raises (ChipOverflowError, UnknownChipError) are
13
+ # defined once, in errors.rb. Do not define them again here: reopening
14
+ # those classes replaces their methods and Ruby reports each one as
15
+ # "method redefined" when warnings are switched on.
16
+ #
17
+ # This file does not install anything merely by being required.
18
+
19
+ require_relative "errors"
20
+
21
+ module Yorha
22
+ module Chips
23
+ # Immutable record describing an installed feature.
24
+ #
25
+ # @!attribute [r] name
26
+ # @return [Symbol] normalized feature name
27
+ # @!attribute [r] cost
28
+ # @return [Integer] capacity consumed
29
+ # @!attribute [r] description
30
+ # @return [String, nil] optional human-readable description
31
+ Chip = Data.define(:name, :cost, :description)
32
+
33
+ # Stores an independent collection of installed chips.
34
+ #
35
+ # Registry instances are intentionally not thread-safe. Install and
36
+ # remove features during application startup rather than concurrently.
37
+ #
38
+ # Installation callbacks may perform their own external side effects.
39
+ # If a callback raises, this registry removes its own chip record, but
40
+ # cannot undo arbitrary changes made by the callback.
41
+ class Registry
42
+ # @return [Integer] total available chip capacity
43
+ attr_reader :capacity
44
+
45
+ # Creates an empty registry with a fixed capacity.
46
+ #
47
+ # @param capacity [Integer] nonnegative total capacity
48
+ # @raise [ArgumentError] when capacity is invalid
49
+ def initialize(capacity: Yorha.config.capacity)
50
+ unless capacity.is_a?(Integer) && capacity >= 0
51
+ raise ArgumentError, "capacity must be a nonnegative Integer"
52
+ end
53
+
54
+ @capacity = capacity
55
+ @chips = {}
56
+ @installing = false
57
+ end
58
+
59
+ # Installs a chip unless a chip with that name already exists.
60
+ #
61
+ # Duplicate installation returns the existing chip without changing
62
+ # its cost or description and without running the callback again.
63
+ #
64
+ # The callback receives the new chip. During the callback, the chip
65
+ # is already visible as installed.
66
+ #
67
+ # @param name [String, Symbol] unique chip identifier
68
+ # @param cost [Integer] nonnegative capacity requirement
69
+ # @param description [String, nil] optional display description
70
+ # @yield [chip] optional installation callback
71
+ # @yieldparam chip [Chip] newly registered chip
72
+ # @return [Chip] new or previously installed chip
73
+ # @raise [ChipOverflowError] when capacity is insufficient
74
+ # @raise [ArgumentError] when arguments are invalid
75
+ # @raise [Yorha::Error] when a callback attempts a registry mutation
76
+ def install(name, cost:, description: nil)
77
+ ensure_not_installing!
78
+
79
+ key = normalize_name(name)
80
+ return @chips.fetch(key) if @chips.key?(key)
81
+
82
+ unless cost.is_a?(Integer) && cost >= 0
83
+ raise ArgumentError, "cost must be a nonnegative Integer"
84
+ end
85
+
86
+ unless description.nil? || description.is_a?(String)
87
+ raise ArgumentError, "description must be a String or nil"
88
+ end
89
+
90
+ if cost > free
91
+ raise ChipOverflowError.new(name: key, cost: cost, free: free)
92
+ end
93
+
94
+ chip = Chip.new(
95
+ name: key,
96
+ cost: cost,
97
+ description: description&.dup&.freeze
98
+ )
99
+
100
+ @chips[key] = chip
101
+
102
+ # ensure also handles nonlocal exits from a callback. Publish the
103
+ # record permanently only after normal callback completion.
104
+ completed = false
105
+
106
+ begin
107
+ @installing = true
108
+ yield chip if block_given?
109
+ completed = true
110
+ chip
111
+ ensure
112
+ @installing = false
113
+ @chips.delete(key) unless completed
114
+ end
115
+ end
116
+
117
+ # Checks whether a named chip is installed.
118
+ #
119
+ # @param name [String, Symbol] chip identifier
120
+ # @return [Boolean] whether the registry contains the chip
121
+ def installed?(name)
122
+ @chips.key?(normalize_name(name))
123
+ end
124
+
125
+ # Removes and returns a chip.
126
+ #
127
+ # @param name [String, Symbol] chip identifier
128
+ # @return [Chip] removed chip
129
+ # @raise [UnknownChipError] when the chip does not exist
130
+ def remove(name)
131
+ ensure_not_installing!
132
+ key = normalize_name(name)
133
+
134
+ @chips.fetch(key) do
135
+ raise UnknownChipError, "Chip #{key.inspect} is not installed"
136
+ end
137
+
138
+ @chips.delete(key)
139
+ end
140
+
141
+ # Returns installed chips in installation order.
142
+ #
143
+ # The returned array is frozen so callers cannot edit the collection.
144
+ #
145
+ # @return [Array<Chip>] installed chip records
146
+ def installed
147
+ @chips.values.freeze
148
+ end
149
+
150
+ # Calculates capacity consumed by installed chips.
151
+ #
152
+ # @return [Integer] total installed cost
153
+ def memory_used
154
+ @chips.values.sum(&:cost)
155
+ end
156
+
157
+ # Calculates remaining capacity.
158
+ #
159
+ # @return [Integer] unused capacity
160
+ def free
161
+ capacity - memory_used
162
+ end
163
+
164
+ # Removes all chips without changing this registry's capacity.
165
+ #
166
+ # @return [Registry] this registry
167
+ def reset!
168
+ ensure_not_installing!
169
+ @chips.clear
170
+ self
171
+ end
172
+
173
+ private
174
+
175
+ # Converts supported identifiers into a consistent symbol key.
176
+ #
177
+ # Leading/trailing whitespace is removed. Names are case-sensitive.
178
+ #
179
+ # @param name [String, Symbol] incoming chip name
180
+ # @return [Symbol] normalized identifier
181
+ # @raise [ArgumentError] when the name is unsupported or empty
182
+ def normalize_name(name)
183
+ unless name.is_a?(String) || name.is_a?(Symbol)
184
+ raise ArgumentError, "chip name must be a String or Symbol"
185
+ end
186
+
187
+ text = name.to_s.strip
188
+
189
+ raise ArgumentError, "chip name cannot be empty" if text.empty?
190
+
191
+ text.to_sym
192
+ end
193
+
194
+ # Prevents callback reentrancy from corrupting installation rollback.
195
+ #
196
+ # Callbacks may read registry state, but must not install, remove,
197
+ # or reset chips in the same registry.
198
+ #
199
+ # @return [void]
200
+ # @raise [Yorha::Error] when a callback attempts mutation
201
+ def ensure_not_installing!
202
+ return unless @installing
203
+
204
+ raise Error, "Cannot mutate a registry inside its installation callback"
205
+ end
206
+ end
207
+
208
+ class << self
209
+ # Returns the lazily created default registry.
210
+ #
211
+ # Its capacity is captured from configuration on first access.
212
+ # Later configuration changes do not resize an existing registry.
213
+ #
214
+ # @return [Registry] process-wide default registry
215
+ def registry
216
+ @registry ||= Registry.new(capacity: Yorha.config.capacity)
217
+ end
218
+
219
+ # Installs a chip in the default registry.
220
+ #
221
+ # @param name [String, Symbol] chip identifier
222
+ # @param cost [Integer] capacity requirement
223
+ # @param description [String, nil] optional explanation
224
+ # @return [Chip] installed or existing chip
225
+ def install(name, cost:, description: nil, &block)
226
+ registry.install(
227
+ name,
228
+ cost: cost,
229
+ description: description,
230
+ &block
231
+ )
232
+ end
233
+
234
+ # Checks the default registry.
235
+ #
236
+ # @param name [String, Symbol] chip identifier
237
+ # @return [Boolean] whether installed
238
+ def installed?(name)
239
+ registry.installed?(name)
240
+ end
241
+
242
+ # Removes a chip from the default registry.
243
+ #
244
+ # @param name [String, Symbol] chip identifier
245
+ # @return [Chip] removed record
246
+ def remove(name)
247
+ registry.remove(name)
248
+ end
249
+
250
+ # @return [Array<Chip>] records from the default registry
251
+ def installed
252
+ registry.installed
253
+ end
254
+
255
+ # @return [Integer] default registry capacity
256
+ def capacity
257
+ registry.capacity
258
+ end
259
+
260
+ # @return [Integer] occupied default registry capacity
261
+ def memory_used
262
+ registry.memory_used
263
+ end
264
+
265
+ # @return [Integer] free default registry capacity
266
+ def free
267
+ registry.free
268
+ end
269
+
270
+ # Clears chips and rebuilds the default registry using current config.
271
+ #
272
+ # Do not call from an installation callback.
273
+ #
274
+ # @return [Registry] new empty default registry
275
+ def reset!
276
+ replacement = Registry.new(capacity: Yorha.config.capacity)
277
+
278
+ # Checks for callback mutation before replacing the old registry.
279
+ @registry&.reset!
280
+
281
+ @registry = replacement
282
+ end
283
+
284
+ # Writes a compact inventory and returns exactly the text written.
285
+ #
286
+ # This first inventory uses a simple list rather than requiring the
287
+ # future Widgets.table implementation.
288
+ #
289
+ # @param io [#write] destination stream
290
+ # @return [String] rendered inventory
291
+ def grid(io: Yorha.config.io)
292
+ lines = [
293
+ Yorha::Render.paint("PLUG-IN CHIP INVENTORY", :accent, io: io),
294
+ Yorha::Render.rule(width: 56, io: io),
295
+ "CAPACITY: #{memory_used}/#{capacity} | FREE: #{free}",
296
+ ""
297
+ ]
298
+
299
+ if installed.empty?
300
+ lines << "No chips installed."
301
+ else
302
+ installed.each do |chip|
303
+ lines << "#{chip.name} [#{chip.cost}]"
304
+
305
+ if chip.description && !chip.description.empty?
306
+ lines << " #{chip.description}"
307
+ end
308
+ end
309
+ end
310
+
311
+ text = "#{lines.join("\n")}\n"
312
+ io.write(text)
313
+ text
314
+ end
315
+ end
316
+ end
317
+ end