hikari-risa 1.0.0__py3-none-any.whl

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.
risa/errors.py ADDED
@@ -0,0 +1,603 @@
1
+ # Copyright (c) 2025 Rayakame
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+ """The exceptions risa raises.
21
+
22
+ Every exception derives from `RisaError`, builds its own message, and keeps the
23
+ details it was raised with as attributes, so callers can branch on fields instead
24
+ of parsing the message.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import typing
30
+
31
+ from risa.internal import constants
32
+
33
+ if typing.TYPE_CHECKING:
34
+ import collections.abc
35
+
36
+ __all__ = (
37
+ "AlreadyRespondedError",
38
+ "ArgBindError",
39
+ "CodecUnavailableError",
40
+ "CustomIdOverflowError",
41
+ "DuplicateHandlerError",
42
+ "DuplicateViewError",
43
+ "EphemeralOriginError",
44
+ "HandlerNotCallableError",
45
+ "HandlerSignatureError",
46
+ "LayoutError",
47
+ "LockTimeoutError",
48
+ "NoViewError",
49
+ "NotAHandlerError",
50
+ "NotAViewError",
51
+ "RisaError",
52
+ "SerializationError",
53
+ "SignatureMismatchError",
54
+ "StateConflictError",
55
+ "StateEncodeError",
56
+ "StateError",
57
+ "StateNotFoundError",
58
+ "StateOverflowError",
59
+ "StateUnreadableError",
60
+ "StoreConformanceError",
61
+ "StoreUnavailableError",
62
+ "ViewDeclarationError",
63
+ )
64
+
65
+
66
+ class RisaError(Exception):
67
+ """Base class of every exception risa raises."""
68
+
69
+
70
+ class HandlerSignatureError(RisaError):
71
+ """Raised at registration when a handler's parameters cannot be routed.
72
+
73
+ Attributes
74
+ ----------
75
+ callback_name
76
+ The qualified name of the handler.
77
+ parameter
78
+ The parameter at fault.
79
+ reason
80
+ What is wrong with it.
81
+ """
82
+
83
+ def __init__(self, callback_name: str, parameter: str, reason: str) -> None:
84
+ self.callback_name: str = callback_name
85
+ self.parameter: str = parameter
86
+ self.reason: str = reason
87
+ super().__init__(f"handler {callback_name!r}: parameter {parameter!r} {reason}")
88
+
89
+
90
+ class ArgBindError(RisaError):
91
+ """Raised when `risa.bind` gets arguments the handler cannot carry on the wire.
92
+
93
+ Attributes
94
+ ----------
95
+ callback_name
96
+ The qualified name of the handler.
97
+ parameter
98
+ The parameter at fault, or `None` when the arguments as a whole do not fit.
99
+ reason
100
+ What is wrong with them.
101
+ """
102
+
103
+ def __init__(self, callback_name: str, parameter: str | None, reason: str) -> None:
104
+ self.callback_name: str = callback_name
105
+ self.parameter: str | None = parameter
106
+ self.reason: str = reason
107
+ if parameter is None:
108
+ super().__init__(f"handler {callback_name!r}: {reason}")
109
+ else:
110
+ super().__init__(f"handler {callback_name!r}: parameter {parameter!r} {reason}")
111
+
112
+
113
+ class SignatureMismatchError(RisaError):
114
+ """Logged, not raised, when a click carries wire arguments for another handler signature.
115
+
116
+ The handler's wire parameters changed without a version bump. risa logs this error
117
+ and routes the click to `View.on_outdated`. Bump the version in
118
+ `@risa.handler(version=...)` so the old components are retired instead.
119
+
120
+ Attributes
121
+ ----------
122
+ view_name
123
+ The view the handler belongs to.
124
+ handler_id
125
+ The handler's id.
126
+ version
127
+ The handler's version.
128
+ found
129
+ The fingerprint the component carries.
130
+ expected
131
+ The fingerprint of the handler's current signature.
132
+ """
133
+
134
+ def __init__(self, view_name: str, handler_id: str, version: int, *, found: str, expected: str) -> None:
135
+ self.view_name: str = view_name
136
+ self.handler_id: str = handler_id
137
+ self.version: int = version
138
+ self.found: str = found
139
+ self.expected: str = expected
140
+ if not expected:
141
+ detail = "a component carries wire arguments, but the handler declares no wire parameters"
142
+ elif not found:
143
+ detail = "a component carries no wire fingerprint, but the handler declares wire parameters"
144
+ else:
145
+ detail = f"a component carries wire fingerprint {found!r}, but the handler's current chain is {expected!r}"
146
+ super().__init__(
147
+ f"handler {handler_id!r} (version {version}) of view {view_name!r}: {detail};"
148
+ " the signature changed in place - bump the handler version to retire the old components",
149
+ )
150
+
151
+
152
+ class HandlerNotCallableError(RisaError):
153
+ """Raised when a handler is called directly instead of being dispatched by risa.
154
+
155
+ Attributes
156
+ ----------
157
+ callback_name
158
+ The qualified name of the handler.
159
+ """
160
+
161
+ def __init__(self, callback_name: str) -> None:
162
+ self.callback_name: str = callback_name
163
+ super().__init__(
164
+ f"handler {callback_name!r} is dispatched by risa, not called directly;"
165
+ " place it on a component with risa.bind(...), or delegate through the view"
166
+ " class's descriptor (Type.handler.func)",
167
+ )
168
+
169
+
170
+ class EphemeralOriginError(RisaError):
171
+ """Raised when an ephemeral origin message can no longer be edited.
172
+
173
+ On an ephemeral view, `rerender()` and `edit()` must be the initial response, or
174
+ follow a silent `defer()`.
175
+
176
+ Attributes
177
+ ----------
178
+ view_name
179
+ The view whose message could not be edited.
180
+ """
181
+
182
+ def __init__(self, view_name: str) -> None:
183
+ self.view_name: str = view_name
184
+ super().__init__(
185
+ f"the origin message of view {view_name!r} is ephemeral and can no longer be edited:"
186
+ " on ephemeral views, rerender() or edit() must be the initial response,"
187
+ " or follow a silent defer",
188
+ )
189
+
190
+
191
+ class StateOverflowError(RisaError):
192
+ """Raised when an `InMessage` view's durable state does not fit its components.
193
+
194
+ Attributes
195
+ ----------
196
+ view_name
197
+ The view whose state overflowed.
198
+ needed
199
+ The bytes of state to write.
200
+ available
201
+ The bytes the rendered components can carry.
202
+ slots
203
+ The number of interactive components.
204
+ codec_name
205
+ The codec the state was written with.
206
+ fields
207
+ The bytes each durable field takes, by name, in declaration order. What they leave
208
+ of `needed` is risa's own framing.
209
+ """
210
+
211
+ def __init__(
212
+ self,
213
+ view_name: str,
214
+ *,
215
+ needed: int,
216
+ available: int,
217
+ slots: int,
218
+ codec_name: str,
219
+ fields: collections.abc.Mapping[str, int] | None = None,
220
+ ) -> None:
221
+ self.view_name: str = view_name
222
+ self.needed: int = needed
223
+ self.available: int = available
224
+ self.slots: int = slots
225
+ self.codec_name: str = codec_name
226
+ self.fields: collections.abc.Mapping[str, int] = dict(fields or {})
227
+ components = "component carries" if slots == 1 else "components carry"
228
+ head = (
229
+ f"view {view_name!r} needs {needed} bytes of durable state, but its {slots} interactive"
230
+ f" {components} only {available} with codec {codec_name!r}"
231
+ )
232
+ remedy = (
233
+ "Make room by marking per-dispatch fields risa.Prop[...], adding components, shortening"
234
+ " fields, using a denser codec (state=risa.InMessage(codec=risa.codecs.BASE32768) with"
235
+ " hikari-risa[radixly]), or moving the view to state=risa.InStore(...)."
236
+ )
237
+ if not self.fields:
238
+ super().__init__(f"{head}.\n{remedy}")
239
+ return
240
+ rows = sorted(self.fields.items(), key=lambda row: -row[1])
241
+ rows.append(("framing", needed - sum(self.fields.values())))
242
+ name_width = max(len(name) for name, _ in rows)
243
+ size_width = max(len(str(size)) for _, size in rows)
244
+ breakdown = "\n".join(
245
+ f" {name:<{name_width}} {size:>{size_width}} {'byte' if size == 1 else 'bytes'}" for name, size in rows
246
+ )
247
+ super().__init__(f"{head}:\n{breakdown}\n{remedy}")
248
+
249
+
250
+ class CodecUnavailableError(RisaError):
251
+ """Raised when a codec needs an optional dependency that is not installed.
252
+
253
+ Attributes
254
+ ----------
255
+ codec_name
256
+ The codec that is unavailable.
257
+ extra
258
+ The `hikari-risa` extra that installs it.
259
+ """
260
+
261
+ def __init__(self, codec_name: str, extra: str) -> None:
262
+ self.codec_name: str = codec_name
263
+ self.extra: str = extra
264
+ super().__init__(
265
+ f"codec {codec_name!r} needs the optional dependency {extra!r}, which is not installed;"
266
+ f" install it with: pip install hikari-risa[{extra}]",
267
+ )
268
+
269
+
270
+ class ViewDeclarationError(RisaError):
271
+ """Raised when a view is declared or added in a way risa cannot serve.
272
+
273
+ Attributes
274
+ ----------
275
+ view_name
276
+ The view at fault.
277
+ reason
278
+ What is wrong with it.
279
+ """
280
+
281
+ def __init__(self, view_name: str, reason: str) -> None:
282
+ self.view_name: str = view_name
283
+ self.reason: str = reason
284
+ super().__init__(f"view {view_name!r}: {reason}")
285
+
286
+
287
+ class DuplicateViewError(RisaError):
288
+ """Raised when two views would route under the same cookie.
289
+
290
+ Attributes
291
+ ----------
292
+ view_name
293
+ The view being registered.
294
+ existing_name
295
+ The view already registered under that cookie.
296
+ cookie
297
+ The cookie both views hash to.
298
+ """
299
+
300
+ def __init__(self, view_name: str, existing_name: str, cookie: str) -> None:
301
+ self.view_name: str = view_name
302
+ self.existing_name: str = existing_name
303
+ self.cookie: str = cookie
304
+ super().__init__(f"view {view_name!r} collides with {existing_name!r}: both are registered under {cookie!r}")
305
+
306
+
307
+ class DuplicateHandlerError(RisaError):
308
+ """Raised when two handlers of one view would route under the same token.
309
+
310
+ Attributes
311
+ ----------
312
+ view_name
313
+ The view both handlers belong to.
314
+ token
315
+ The token both handlers hash to.
316
+ first_id
317
+ The id of the first handler.
318
+ first_version
319
+ The version of the first handler.
320
+ second_id
321
+ The id of the second handler.
322
+ second_version
323
+ The version of the second handler.
324
+ """
325
+
326
+ def __init__(
327
+ self,
328
+ view_name: str,
329
+ token: str,
330
+ *,
331
+ first_id: str,
332
+ first_version: int,
333
+ second_id: str,
334
+ second_version: int,
335
+ ) -> None:
336
+ self.view_name: str = view_name
337
+ self.token: str = token
338
+ self.first_id: str = first_id
339
+ self.first_version: int = first_version
340
+ self.second_id: str = second_id
341
+ self.second_version: int = second_version
342
+ super().__init__(
343
+ f"view {view_name!r}: handlers {first_id!r} (version {first_version}) and "
344
+ f"{second_id!r} (version {second_version}) both route under token {token!r}",
345
+ )
346
+
347
+
348
+ class AlreadyRespondedError(RisaError):
349
+ """Raised when an interaction that already has its initial response is deferred.
350
+
351
+ Attributes
352
+ ----------
353
+ attempted
354
+ What was attempted.
355
+ already_sent
356
+ The initial response the interaction already received.
357
+ """
358
+
359
+ def __init__(self, attempted: str, already_sent: str) -> None:
360
+ self.attempted: str = attempted
361
+ self.already_sent: str = already_sent
362
+ super().__init__(
363
+ f"cannot {attempted}: this interaction already received its initial response ({already_sent})",
364
+ )
365
+
366
+
367
+ class NotAHandlerError(RisaError):
368
+ """Raised when a component is given something that is not a risa handler.
369
+
370
+ Attributes
371
+ ----------
372
+ type_name
373
+ The type of the object that was given.
374
+ """
375
+
376
+ def __init__(self, type_name: str) -> None:
377
+ self.type_name: str = type_name
378
+ super().__init__(
379
+ f"{type_name} has no handler identity to route under; pass a handler method"
380
+ " accessed on the view instance, bare or through risa.bind(...)",
381
+ )
382
+
383
+
384
+ class NotAViewError(RisaError):
385
+ """Raised when a class or instance that was never `@risa.register`-ed is used as a view.
386
+
387
+ Attributes
388
+ ----------
389
+ type_name
390
+ The type that was given.
391
+ """
392
+
393
+ def __init__(self, type_name: str) -> None:
394
+ self.type_name: str = type_name
395
+ super().__init__(f"{type_name} is not a registered view; decorate it with @risa.register")
396
+
397
+
398
+ class NoViewError(RisaError):
399
+ """Raised when an operation needs the view's state, but the context has none.
400
+
401
+ That is the case in `on_outdated` and `on_state_missing`, after `ctx.replace` gave the
402
+ message to another view, and in a context kept past the end of its dispatch.
403
+
404
+ Attributes
405
+ ----------
406
+ view_name
407
+ The view the context belongs to.
408
+ attempted
409
+ The operation that needed the state.
410
+ """
411
+
412
+ def __init__(self, view_name: str, attempted: str) -> None:
413
+ self.view_name: str = view_name
414
+ self.attempted: str = attempted
415
+ super().__init__(
416
+ f"{attempted} on view {view_name!r} needs the view's state, but this context has none - it"
417
+ " belongs to on_outdated or on_state_missing, to a message ctx.replace gave to another"
418
+ " view, or to a dispatch that has already ended;"
419
+ " answer with ctx.edit(layout) using a tree without interactive components, or with"
420
+ " ctx.respond(...)",
421
+ )
422
+
423
+
424
+ class LayoutError(RisaError):
425
+ """Raised when a layout cannot be built.
426
+
427
+ Attributes
428
+ ----------
429
+ path
430
+ Where in the tree the problem is, such as `Container > Row[1] > Button[0]`.
431
+ reason
432
+ What is wrong there.
433
+ """
434
+
435
+ def __init__(self, path: str, reason: str) -> None:
436
+ self.path: str = path
437
+ self.reason: str = reason
438
+ super().__init__(f"{path}: {reason}")
439
+
440
+
441
+ class CustomIdOverflowError(RisaError):
442
+ """Raised when a component's `custom_id` would exceed Discord's limit.
443
+
444
+ Attributes
445
+ ----------
446
+ view_name
447
+ The view the component belongs to.
448
+ length
449
+ The length the `custom_id` would have.
450
+ """
451
+
452
+ def __init__(self, view_name: str, length: int) -> None:
453
+ self.view_name: str = view_name
454
+ self.length: int = length
455
+ super().__init__(
456
+ f"custom_id for view {view_name!r} is {length} characters, "
457
+ f"which exceeds the Discord limit of {constants.MAX_CUSTOM_ID_LENGTH}",
458
+ )
459
+
460
+
461
+ class SerializationError(RisaError):
462
+ """Base class of the errors raised while writing or reading view state."""
463
+
464
+
465
+ class StateEncodeError(SerializationError):
466
+ """Raised when a durable field holds a value that cannot be serialized.
467
+
468
+ Attributes
469
+ ----------
470
+ view_name
471
+ The view the field belongs to.
472
+ field
473
+ The field at fault.
474
+ reason
475
+ Why its value cannot be written.
476
+ """
477
+
478
+ def __init__(self, view_name: str, field: str, reason: str) -> None:
479
+ self.view_name: str = view_name
480
+ self.field: str = field
481
+ self.reason: str = reason
482
+ super().__init__(
483
+ f"view {view_name!r}: durable field {field!r} cannot be written to state: {reason};"
484
+ " store a value msgpack can carry, or mark the field risa.Prop[...] if it should not persist",
485
+ )
486
+
487
+
488
+ class StateError(RisaError):
489
+ """Base class of the errors raised while working with `InStore` state."""
490
+
491
+
492
+ class StateNotFoundError(StateError):
493
+ """Raised when a view's stored state is gone in the middle of a dispatch.
494
+
495
+ Attributes
496
+ ----------
497
+ key
498
+ The store key of the state.
499
+ """
500
+
501
+ def __init__(self, key: str) -> None:
502
+ self.key: str = key
503
+ super().__init__(f"no state found for key {key!r}; it may have expired or been evicted")
504
+
505
+
506
+ class StateConflictError(StateError):
507
+ """Raised when another process wrote a view's state first.
508
+
509
+ By the time it is raised, the view already holds the state that won, so the handler
510
+ can apply its change again on top of it. A record that cannot be read raises
511
+ `StateUnreadableError` instead.
512
+
513
+ Attributes
514
+ ----------
515
+ key
516
+ The store key of the state.
517
+ expected
518
+ The version this dispatch read.
519
+ found
520
+ The version the store holds.
521
+ """
522
+
523
+ def __init__(self, key: str, *, expected: int, found: int) -> None:
524
+ self.key: str = key
525
+ self.expected: int = expected
526
+ self.found: int = found
527
+ super().__init__(
528
+ f"state for key {key!r} was written concurrently: this handler read version {expected},"
529
+ f" the store holds version {found}; the write was rejected",
530
+ )
531
+
532
+
533
+ class StateUnreadableError(StateError):
534
+ """Raised when another process wrote a view's state first, in a form this code cannot read.
535
+
536
+ It can happen during a deploy, when a process with other fields wins the race. The view
537
+ keeps its own state, the change is lost, and another attempt in this click raises again.
538
+
539
+ Attributes
540
+ ----------
541
+ key
542
+ The store key of the state.
543
+ """
544
+
545
+ def __init__(self, key: str) -> None:
546
+ self.key: str = key
547
+ super().__init__(f"state for key {key!r} was written concurrently in a form this code cannot read")
548
+
549
+
550
+ class LockTimeoutError(StateError):
551
+ """Raised when the lock on a view's state is not granted in time.
552
+
553
+ Attributes
554
+ ----------
555
+ key
556
+ The store key of the state.
557
+ timeout
558
+ How long risa waited, in seconds.
559
+ """
560
+
561
+ def __init__(self, key: str, timeout: float) -> None:
562
+ self.key: str = key
563
+ self.timeout: float = timeout
564
+ super().__init__(f"timed out after {timeout}s waiting for the lock on state key {key!r}")
565
+
566
+
567
+ class StoreUnavailableError(StateError):
568
+ """Raised when the store holding a view's state cannot be reached.
569
+
570
+ The state is not lost; it only cannot be read or written right now. A store reports
571
+ missing state by returning nothing, never with this error.
572
+
573
+ Attributes
574
+ ----------
575
+ key
576
+ The store key of the state.
577
+ reason
578
+ What went wrong.
579
+ """
580
+
581
+ def __init__(self, key: str, reason: str) -> None:
582
+ self.key: str = key
583
+ self.reason: str = reason
584
+ super().__init__(
585
+ f"the store backing key {key!r} could not be reached: {reason};"
586
+ " the state is not lost - the interaction cannot be answered from it right now",
587
+ )
588
+
589
+
590
+ class StoreConformanceError(RisaError):
591
+ """Raised by `risa.store.testing.verify_store` when a store fails any check.
592
+
593
+ Attributes
594
+ ----------
595
+ failures
596
+ One line per failed check, naming the check and what went wrong.
597
+ """
598
+
599
+ def __init__(self, failures: collections.abc.Sequence[str]) -> None:
600
+ self.failures: collections.abc.Sequence[str] = failures
601
+ listed = "".join(f"\n- {failure}" for failure in failures)
602
+ checks = "check" if len(failures) == 1 else "checks"
603
+ super().__init__(f"the store failed {len(failures)} conformance {checks}:{listed}")
@@ -0,0 +1,22 @@
1
+ # Copyright (c) 2025 Rayakame
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+ """risa's private machinery. Nothing here is public API, and any of it may change without notice."""
21
+
22
+ from __future__ import annotations