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.
- hikari_risa-1.0.0.dist-info/METADATA +83 -0
- hikari_risa-1.0.0.dist-info/RECORD +43 -0
- hikari_risa-1.0.0.dist-info/WHEEL +4 -0
- hikari_risa-1.0.0.dist-info/entry_points.txt +2 -0
- hikari_risa-1.0.0.dist-info/licenses/LICENSE +21 -0
- risa/__init__.py +49 -0
- risa/__main__.py +145 -0
- risa/_about.py +31 -0
- risa/binding.py +251 -0
- risa/client.py +657 -0
- risa/codecs.py +204 -0
- risa/context.py +693 -0
- risa/di.py +75 -0
- risa/dispatch.py +828 -0
- risa/errors.py +603 -0
- risa/internal/__init__.py +22 -0
- risa/internal/codec.py +547 -0
- risa/internal/constants.py +36 -0
- risa/internal/leases.py +197 -0
- risa/internal/locks.py +87 -0
- risa/internal/reader.py +88 -0
- risa/internal/registry.py +208 -0
- risa/internal/wire.py +118 -0
- risa/py.typed +0 -0
- risa/state/__init__.py +25 -0
- risa/state/anchor.py +279 -0
- risa/state/backend.py +155 -0
- risa/state/message.py +278 -0
- risa/state/placement.py +104 -0
- risa/state/schema.py +447 -0
- risa/state/serde.py +69 -0
- risa/state/stateless.py +94 -0
- risa/state/stored.py +444 -0
- risa/store/__init__.py +30 -0
- risa/store/memory.py +152 -0
- risa/store/postgres.py +311 -0
- risa/store/protocol.py +172 -0
- risa/store/redis.py +254 -0
- risa/store/testing.py +341 -0
- risa/ui/__init__.py +26 -0
- risa/ui/build.py +353 -0
- risa/ui/nodes.py +918 -0
- risa/view.py +466 -0
risa/internal/codec.py
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
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 `custom_id` layout, and the converters wire arguments travel through.
|
|
21
|
+
|
|
22
|
+
Every interactive component risa renders carries one `custom_id` of at most 100
|
|
23
|
+
characters, laid out as:
|
|
24
|
+
|
|
25
|
+
```text
|
|
26
|
+
ver:1 codec:1 cookie:6 handler:2 idx:1 frag_len:1 fragment [fingerprint:2 frames]
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`ver` is the layout version and `codec` the tag of the codec the byte fields are
|
|
30
|
+
written in. `cookie` and `handler` route the click. `idx` and `frag_len` frame the
|
|
31
|
+
component's slice of the view's anchor (`risa.state.anchor`). What remains is the
|
|
32
|
+
handler's wire arguments: a signature fingerprint, then one length-prefixed frame per
|
|
33
|
+
argument, or nothing for a handler without wire parameters.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import abc
|
|
39
|
+
import enum
|
|
40
|
+
import inspect
|
|
41
|
+
import re
|
|
42
|
+
import typing
|
|
43
|
+
|
|
44
|
+
import hikari
|
|
45
|
+
import linkd
|
|
46
|
+
import msgspec
|
|
47
|
+
|
|
48
|
+
from risa import codecs
|
|
49
|
+
from risa import errors
|
|
50
|
+
from risa.internal import constants
|
|
51
|
+
from risa.internal import wire
|
|
52
|
+
|
|
53
|
+
if typing.TYPE_CHECKING:
|
|
54
|
+
import collections.abc
|
|
55
|
+
|
|
56
|
+
__all__ = (
|
|
57
|
+
"CODEC_LENGTH",
|
|
58
|
+
"COOKIE_LENGTH",
|
|
59
|
+
"FINGERPRINT_LENGTH",
|
|
60
|
+
"FRAGMENT_INDEX_WIDTH",
|
|
61
|
+
"FRAGMENT_LEN_WIDTH",
|
|
62
|
+
"FRAME_LEN_WIDTH",
|
|
63
|
+
"HANDLER_LENGTH",
|
|
64
|
+
"HEADER_LENGTH",
|
|
65
|
+
"MAX_FRAGMENTS",
|
|
66
|
+
"MAX_FRAGMENT_LENGTH",
|
|
67
|
+
"MAX_FRAME_LENGTH",
|
|
68
|
+
"VERSION",
|
|
69
|
+
"ArgConverter",
|
|
70
|
+
"BoolConverter",
|
|
71
|
+
"CustomID",
|
|
72
|
+
"EnumConverter",
|
|
73
|
+
"HandlerSignature",
|
|
74
|
+
"IntConverter",
|
|
75
|
+
"StrConverter",
|
|
76
|
+
"decode_text",
|
|
77
|
+
"make_cookie",
|
|
78
|
+
"make_handler_token",
|
|
79
|
+
"pack_frames",
|
|
80
|
+
"parse_custom_id",
|
|
81
|
+
"resolve_converter",
|
|
82
|
+
"resolve_signature",
|
|
83
|
+
"unpack_frames",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
VERSION: typing.Final[str] = "1"
|
|
87
|
+
|
|
88
|
+
CODEC_LENGTH: typing.Final[int] = 1
|
|
89
|
+
COOKIE_LENGTH: typing.Final[int] = 6
|
|
90
|
+
HANDLER_LENGTH: typing.Final[int] = 2
|
|
91
|
+
FRAGMENT_INDEX_WIDTH: typing.Final[int] = 1
|
|
92
|
+
FRAGMENT_LEN_WIDTH: typing.Final[int] = 1
|
|
93
|
+
HEADER_LENGTH: typing.Final[int] = (
|
|
94
|
+
len(VERSION) + CODEC_LENGTH + COOKIE_LENGTH + HANDLER_LENGTH + FRAGMENT_INDEX_WIDTH + FRAGMENT_LEN_WIDTH
|
|
95
|
+
)
|
|
96
|
+
MAX_FRAGMENTS: typing.Final[int] = wire.largest_value(FRAGMENT_INDEX_WIDTH) + 1
|
|
97
|
+
MAX_FRAGMENT_LENGTH: typing.Final[int] = constants.MAX_CUSTOM_ID_LENGTH - HEADER_LENGTH
|
|
98
|
+
FRAME_LEN_WIDTH: typing.Final[int] = 1
|
|
99
|
+
MAX_FRAME_LENGTH: typing.Final[int] = wire.largest_value(FRAME_LEN_WIDTH)
|
|
100
|
+
FINGERPRINT_LENGTH: typing.Final[int] = 2
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def make_cookie(name: str, version: int) -> str:
|
|
104
|
+
"""Return the cookie a view routes under, a digest of its name and schema version.
|
|
105
|
+
|
|
106
|
+
Hashing the version in makes a schema bump retire every component sent before it:
|
|
107
|
+
their cookie no longer matches any view.
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
-------
|
|
111
|
+
str
|
|
112
|
+
The six-character cookie.
|
|
113
|
+
"""
|
|
114
|
+
return wire.pack_digest(f"{name}:{version}", chars=COOKIE_LENGTH)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def make_handler_token(handler_id: str, version: int) -> str:
|
|
118
|
+
"""Return the token a handler routes under, a digest of its id and version.
|
|
119
|
+
|
|
120
|
+
It depends on nothing about the handler's siblings, so adding, removing or reordering
|
|
121
|
+
other handlers never moves it.
|
|
122
|
+
|
|
123
|
+
Returns
|
|
124
|
+
-------
|
|
125
|
+
str
|
|
126
|
+
The two-character token.
|
|
127
|
+
"""
|
|
128
|
+
return wire.pack_digest(f"{handler_id}:{version}", chars=HANDLER_LENGTH)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class CustomID(msgspec.Struct, frozen=True):
|
|
132
|
+
"""One component's `custom_id`, split into its fields.
|
|
133
|
+
|
|
134
|
+
Attributes
|
|
135
|
+
----------
|
|
136
|
+
cookie
|
|
137
|
+
The view's cookie.
|
|
138
|
+
handler
|
|
139
|
+
The handler's token.
|
|
140
|
+
fragment_index
|
|
141
|
+
Which slice of the anchor `fragment` is.
|
|
142
|
+
fragment
|
|
143
|
+
The component's slice of the anchor, encoded with `codec`.
|
|
144
|
+
tail
|
|
145
|
+
The wire arguments: the signature fingerprint and the frames, or empty.
|
|
146
|
+
codec
|
|
147
|
+
The codec the fragment and the frames are written in.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
cookie: str
|
|
151
|
+
handler: str
|
|
152
|
+
fragment_index: int
|
|
153
|
+
fragment: str
|
|
154
|
+
tail: str
|
|
155
|
+
codec: codecs.Codec = codecs.BASE85
|
|
156
|
+
|
|
157
|
+
def encode(self) -> str:
|
|
158
|
+
"""Write the fields out as one `custom_id`.
|
|
159
|
+
|
|
160
|
+
Returns
|
|
161
|
+
-------
|
|
162
|
+
str
|
|
163
|
+
The `custom_id`.
|
|
164
|
+
|
|
165
|
+
Raises
|
|
166
|
+
------
|
|
167
|
+
ValueError
|
|
168
|
+
If the cookie or the handler token has the wrong length.
|
|
169
|
+
CustomIdOverflowError
|
|
170
|
+
If it would exceed Discord's 100 characters.
|
|
171
|
+
"""
|
|
172
|
+
if len(self.cookie) != COOKIE_LENGTH:
|
|
173
|
+
msg = f"cookie must be exactly {COOKIE_LENGTH} characters, got {len(self.cookie)}"
|
|
174
|
+
raise ValueError(msg)
|
|
175
|
+
if len(self.handler) != HANDLER_LENGTH:
|
|
176
|
+
msg = f"handler token must be exactly {HANDLER_LENGTH} characters, got {len(self.handler)}"
|
|
177
|
+
raise ValueError(msg)
|
|
178
|
+
|
|
179
|
+
encoded = "".join(
|
|
180
|
+
(
|
|
181
|
+
VERSION,
|
|
182
|
+
self.codec.tag,
|
|
183
|
+
self.cookie,
|
|
184
|
+
self.handler,
|
|
185
|
+
wire.pack_uint(self.fragment_index, FRAGMENT_INDEX_WIDTH),
|
|
186
|
+
wire.pack_uint(len(self.fragment), FRAGMENT_LEN_WIDTH),
|
|
187
|
+
self.fragment,
|
|
188
|
+
self.tail,
|
|
189
|
+
),
|
|
190
|
+
)
|
|
191
|
+
if len(encoded) > constants.MAX_CUSTOM_ID_LENGTH:
|
|
192
|
+
raise errors.CustomIdOverflowError(view_name=f"cookie: {self.cookie}", length=len(encoded))
|
|
193
|
+
|
|
194
|
+
return encoded
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def parse_custom_id(raw: str) -> CustomID | None:
|
|
198
|
+
"""Split `raw` into its fields, or return `None` if risa did not write it.
|
|
199
|
+
|
|
200
|
+
`None` covers every `custom_id` of another layout, an unknown codec tag, or a frame
|
|
201
|
+
that does not fit; dispatch ignores those, so risa can share a bot with other
|
|
202
|
+
component handlers.
|
|
203
|
+
|
|
204
|
+
Returns
|
|
205
|
+
-------
|
|
206
|
+
CustomID | None
|
|
207
|
+
The fields, or `None` for a `custom_id` that is not risa's.
|
|
208
|
+
"""
|
|
209
|
+
if not (HEADER_LENGTH <= len(raw) <= constants.MAX_CUSTOM_ID_LENGTH) or raw[0] != VERSION:
|
|
210
|
+
return None
|
|
211
|
+
wire_codec = codecs.by_tag(raw[len(VERSION)])
|
|
212
|
+
if wire_codec is None:
|
|
213
|
+
return None
|
|
214
|
+
|
|
215
|
+
cookie_start = len(VERSION) + CODEC_LENGTH
|
|
216
|
+
cookie_end = cookie_start + COOKIE_LENGTH
|
|
217
|
+
handler_end = cookie_end + HANDLER_LENGTH
|
|
218
|
+
index_end = handler_end + FRAGMENT_INDEX_WIDTH
|
|
219
|
+
if (fragment_index := wire.unpack_uint(raw[handler_end:index_end])) is None:
|
|
220
|
+
return None
|
|
221
|
+
if (fragment_length := wire.unpack_uint(raw[index_end : index_end + FRAGMENT_LEN_WIDTH])) is None:
|
|
222
|
+
return None
|
|
223
|
+
if HEADER_LENGTH + fragment_length > len(raw):
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
return CustomID(
|
|
227
|
+
cookie=raw[cookie_start:cookie_end],
|
|
228
|
+
handler=raw[cookie_end:handler_end],
|
|
229
|
+
fragment_index=fragment_index,
|
|
230
|
+
fragment=raw[HEADER_LENGTH : HEADER_LENGTH + fragment_length],
|
|
231
|
+
tail=raw[HEADER_LENGTH + fragment_length :],
|
|
232
|
+
codec=wire_codec,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def decode_text(text: str, wire_codec: codecs.Codec) -> bytes | errors.CodecUnavailableError | None:
|
|
237
|
+
"""Decode a fragment or frame with `wire_codec`.
|
|
238
|
+
|
|
239
|
+
Returns
|
|
240
|
+
-------
|
|
241
|
+
bytes | CodecUnavailableError | None
|
|
242
|
+
The bytes; the error, unraised, when the codec's extra is missing, so the caller
|
|
243
|
+
can tell an unreadable host from forged text; or `None` for text the codec cannot
|
|
244
|
+
read.
|
|
245
|
+
"""
|
|
246
|
+
try:
|
|
247
|
+
return wire_codec.decode(text)
|
|
248
|
+
except errors.CodecUnavailableError as exc:
|
|
249
|
+
return exc
|
|
250
|
+
except ValueError:
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class ArgConverter(abc.ABC):
|
|
255
|
+
"""How one wire parameter's values are written into a frame and read back.
|
|
256
|
+
|
|
257
|
+
`type_id` names the converter in the signature fingerprint. It names the type's
|
|
258
|
+
shape, never the parameter, so renaming a parameter or switching `int` to
|
|
259
|
+
`hikari.Snowflake` leaves live components routable.
|
|
260
|
+
"""
|
|
261
|
+
|
|
262
|
+
__slots__ = ()
|
|
263
|
+
|
|
264
|
+
@property
|
|
265
|
+
@abc.abstractmethod
|
|
266
|
+
def type_id(self) -> str:
|
|
267
|
+
"""The converter's part of the signature fingerprint."""
|
|
268
|
+
|
|
269
|
+
@abc.abstractmethod
|
|
270
|
+
def encode(self, value: object) -> bytes:
|
|
271
|
+
"""Write `value` as bytes, raising `TypeError` for a value of the wrong type."""
|
|
272
|
+
|
|
273
|
+
@abc.abstractmethod
|
|
274
|
+
def decode(self, data: bytes) -> object | None:
|
|
275
|
+
"""Read `data` back into a value, or return `None` if it is not one of this converter's."""
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class IntConverter(ArgConverter):
|
|
279
|
+
__slots__ = ("_target",)
|
|
280
|
+
|
|
281
|
+
def __init__(self, target: collections.abc.Callable[[int], object]) -> None:
|
|
282
|
+
self._target = target
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
@typing.override
|
|
286
|
+
def type_id(self) -> str:
|
|
287
|
+
return "i"
|
|
288
|
+
|
|
289
|
+
@typing.override
|
|
290
|
+
def encode(self, value: object) -> bytes:
|
|
291
|
+
if type(value) is bool or not isinstance(value, int):
|
|
292
|
+
msg = f"expected an int, got {type(value).__name__}"
|
|
293
|
+
raise TypeError(msg)
|
|
294
|
+
return value.to_bytes((value.bit_length() + 8) // 8, "little", signed=True)
|
|
295
|
+
|
|
296
|
+
@typing.override
|
|
297
|
+
def decode(self, data: bytes) -> object | None:
|
|
298
|
+
if not data:
|
|
299
|
+
return None
|
|
300
|
+
return self._target(int.from_bytes(data, "little", signed=True))
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class StrConverter(ArgConverter):
|
|
304
|
+
__slots__ = ()
|
|
305
|
+
|
|
306
|
+
@property
|
|
307
|
+
@typing.override
|
|
308
|
+
def type_id(self) -> str:
|
|
309
|
+
return "s"
|
|
310
|
+
|
|
311
|
+
@typing.override
|
|
312
|
+
def encode(self, value: object) -> bytes:
|
|
313
|
+
if not isinstance(value, str):
|
|
314
|
+
msg = f"expected a str, got {type(value).__name__}"
|
|
315
|
+
raise TypeError(msg)
|
|
316
|
+
return value.encode()
|
|
317
|
+
|
|
318
|
+
@typing.override
|
|
319
|
+
def decode(self, data: bytes) -> object | None:
|
|
320
|
+
try:
|
|
321
|
+
return data.decode()
|
|
322
|
+
except UnicodeDecodeError:
|
|
323
|
+
return None
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
class BoolConverter(ArgConverter):
|
|
327
|
+
__slots__ = ()
|
|
328
|
+
|
|
329
|
+
@property
|
|
330
|
+
@typing.override
|
|
331
|
+
def type_id(self) -> str:
|
|
332
|
+
return "b"
|
|
333
|
+
|
|
334
|
+
@typing.override
|
|
335
|
+
def encode(self, value: object) -> bytes:
|
|
336
|
+
if type(value) is not bool:
|
|
337
|
+
msg = f"expected a bool, got {type(value).__name__}"
|
|
338
|
+
raise TypeError(msg)
|
|
339
|
+
return b"\x01" if value else b"\x00"
|
|
340
|
+
|
|
341
|
+
@typing.override
|
|
342
|
+
def decode(self, data: bytes) -> object | None:
|
|
343
|
+
if len(data) != 1 or data[0] > 1:
|
|
344
|
+
return None
|
|
345
|
+
return data == b"\x01"
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class EnumConverter(ArgConverter):
|
|
349
|
+
__slots__ = ("_enum", "_inner", "_type_id")
|
|
350
|
+
|
|
351
|
+
def __init__(self, enum_cls: type[enum.Enum], inner: ArgConverter, type_id: str) -> None:
|
|
352
|
+
self._enum = enum_cls
|
|
353
|
+
self._inner = inner
|
|
354
|
+
self._type_id = type_id
|
|
355
|
+
|
|
356
|
+
@property
|
|
357
|
+
@typing.override
|
|
358
|
+
def type_id(self) -> str:
|
|
359
|
+
return self._type_id
|
|
360
|
+
|
|
361
|
+
@typing.override
|
|
362
|
+
def encode(self, value: object) -> bytes:
|
|
363
|
+
if not isinstance(value, self._enum):
|
|
364
|
+
msg = f"expected {self._enum.__name__}, got {type(value).__name__}"
|
|
365
|
+
raise TypeError(msg)
|
|
366
|
+
return self._inner.encode(value.value)
|
|
367
|
+
|
|
368
|
+
@typing.override
|
|
369
|
+
def decode(self, data: bytes) -> object | None:
|
|
370
|
+
inner = self._inner.decode(data)
|
|
371
|
+
if inner is None:
|
|
372
|
+
return None
|
|
373
|
+
try:
|
|
374
|
+
return self._enum(inner)
|
|
375
|
+
except ValueError:
|
|
376
|
+
return None
|
|
377
|
+
|
|
378
|
+
def reads(self, data: bytes) -> bool:
|
|
379
|
+
"""Whether `data` holds a value of the enum's kind, whichever members the enum has now."""
|
|
380
|
+
return self._inner.decode(data) is not None
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _enum_converter(enum_cls: type[enum.Enum]) -> EnumConverter:
|
|
384
|
+
value_types: set[type[object]] = {type(member.value) for member in enum_cls}
|
|
385
|
+
if all(t is str for t in value_types) and value_types:
|
|
386
|
+
return EnumConverter(enum_cls, StrConverter(), "es")
|
|
387
|
+
if all(t is not bool and issubclass(t, int) for t in value_types) and value_types:
|
|
388
|
+
return EnumConverter(enum_cls, IntConverter(int), "ei")
|
|
389
|
+
msg = "enum values must be all int or all str"
|
|
390
|
+
raise ValueError(msg)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def resolve_converter(annotation: object) -> ArgConverter | None:
|
|
394
|
+
"""Return the converter for a wire parameter annotated `annotation`.
|
|
395
|
+
|
|
396
|
+
Returns
|
|
397
|
+
-------
|
|
398
|
+
ArgConverter | None
|
|
399
|
+
The converter, or `None` for a type that is not a wire type and is therefore
|
|
400
|
+
injected.
|
|
401
|
+
|
|
402
|
+
Raises
|
|
403
|
+
------
|
|
404
|
+
ValueError
|
|
405
|
+
If `annotation` is an enum whose values are not all `int` or all `str`.
|
|
406
|
+
"""
|
|
407
|
+
if annotation is bool:
|
|
408
|
+
return BoolConverter()
|
|
409
|
+
if annotation is int:
|
|
410
|
+
return IntConverter(int)
|
|
411
|
+
if annotation is hikari.Snowflake:
|
|
412
|
+
return IntConverter(hikari.Snowflake)
|
|
413
|
+
if annotation is str:
|
|
414
|
+
return StrConverter()
|
|
415
|
+
if isinstance(annotation, type) and issubclass(annotation, enum.Enum):
|
|
416
|
+
return _enum_converter(annotation)
|
|
417
|
+
return None
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def pack_frames(parts: collections.abc.Sequence[str]) -> str:
|
|
421
|
+
"""Join encoded arguments, each led by its length in one base-92 digit."""
|
|
422
|
+
return "".join(wire.pack_uint(len(part), FRAME_LEN_WIDTH) + part for part in parts)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def unpack_frames(raw: str) -> list[str] | None:
|
|
426
|
+
"""Split joined frames back apart, or return `None` if their lengths do not add up."""
|
|
427
|
+
parts: list[str] = []
|
|
428
|
+
position = 0
|
|
429
|
+
while position < len(raw):
|
|
430
|
+
length = wire.unpack_uint(raw[position : position + FRAME_LEN_WIDTH])
|
|
431
|
+
if length is None:
|
|
432
|
+
return None
|
|
433
|
+
start = position + FRAME_LEN_WIDTH
|
|
434
|
+
end = start + length
|
|
435
|
+
if end > len(raw):
|
|
436
|
+
return None
|
|
437
|
+
parts.append(raw[start:end])
|
|
438
|
+
position = end
|
|
439
|
+
return parts
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
class HandlerSignature(msgspec.Struct, frozen=True):
|
|
443
|
+
"""A handler's wire parameters, resolved once at registration.
|
|
444
|
+
|
|
445
|
+
Attributes
|
|
446
|
+
----------
|
|
447
|
+
converters
|
|
448
|
+
One converter per wire parameter, in order.
|
|
449
|
+
required
|
|
450
|
+
How many of them have no default.
|
|
451
|
+
fingerprint
|
|
452
|
+
The digest of the converters' type ids, which every component with wire arguments
|
|
453
|
+
carries.
|
|
454
|
+
"""
|
|
455
|
+
|
|
456
|
+
converters: collections.abc.Mapping[str, ArgConverter]
|
|
457
|
+
required: int
|
|
458
|
+
fingerprint: str
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _find_unresolvable_parameter(func: collections.abc.Callable[..., object], missing: str) -> str:
|
|
462
|
+
try:
|
|
463
|
+
annotations: dict[str, object] = getattr(func, "__annotations__", {})
|
|
464
|
+
except NameError:
|
|
465
|
+
return missing
|
|
466
|
+
pattern = re.compile(rf"\b{re.escape(missing)}\b")
|
|
467
|
+
for name, raw in annotations.items():
|
|
468
|
+
if name != "return" and isinstance(raw, str) and pattern.search(raw):
|
|
469
|
+
return name
|
|
470
|
+
return missing
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _resolve_hints(func: collections.abc.Callable[..., object]) -> dict[str, object]:
|
|
474
|
+
try:
|
|
475
|
+
return typing.get_type_hints(func)
|
|
476
|
+
except NameError as exc:
|
|
477
|
+
missing = exc.name or "?"
|
|
478
|
+
reason = (
|
|
479
|
+
f"has annotation {missing!r}, which is not importable at runtime; annotations on"
|
|
480
|
+
" handler parameters must be imported outside TYPE_CHECKING"
|
|
481
|
+
)
|
|
482
|
+
raise errors.HandlerSignatureError(
|
|
483
|
+
func.__qualname__,
|
|
484
|
+
_find_unresolvable_parameter(func, missing),
|
|
485
|
+
reason,
|
|
486
|
+
) from exc
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def resolve_signature(func: collections.abc.Callable[..., object]) -> HandlerSignature:
|
|
490
|
+
"""Split a handler's parameters after `self` and `ctx` into wire and injected ones.
|
|
491
|
+
|
|
492
|
+
Wire parameters are the leading positional parameters with a wire type. The first
|
|
493
|
+
parameter that is keyword-only, unannotated, defaulted to `linkd.INJECTED` or of
|
|
494
|
+
another type starts the injected section, and nothing after it may be a wire type
|
|
495
|
+
again.
|
|
496
|
+
|
|
497
|
+
Returns
|
|
498
|
+
-------
|
|
499
|
+
HandlerSignature
|
|
500
|
+
The converters, the count of required ones, and their fingerprint.
|
|
501
|
+
|
|
502
|
+
Raises
|
|
503
|
+
------
|
|
504
|
+
HandlerSignatureError
|
|
505
|
+
If a wire-typed parameter follows the injected section, or an enum cannot be a
|
|
506
|
+
wire type.
|
|
507
|
+
"""
|
|
508
|
+
hints = _resolve_hints(func)
|
|
509
|
+
params = list(inspect.signature(func).parameters.values())[2:]
|
|
510
|
+
converters: dict[str, ArgConverter] = {}
|
|
511
|
+
required_count = 0
|
|
512
|
+
|
|
513
|
+
di_flag = False
|
|
514
|
+
for param in params:
|
|
515
|
+
if param.kind in {inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD}:
|
|
516
|
+
di_flag = True
|
|
517
|
+
continue
|
|
518
|
+
if param.kind is inspect.Parameter.KEYWORD_ONLY:
|
|
519
|
+
di_flag = True
|
|
520
|
+
if param.name not in hints:
|
|
521
|
+
di_flag = True
|
|
522
|
+
continue
|
|
523
|
+
if param.default is linkd.INJECTED:
|
|
524
|
+
di_flag = True
|
|
525
|
+
continue
|
|
526
|
+
try:
|
|
527
|
+
converter = resolve_converter(hints[param.name])
|
|
528
|
+
except ValueError as exc:
|
|
529
|
+
raise errors.HandlerSignatureError(func.__qualname__, param.name, str(exc)) from exc
|
|
530
|
+
|
|
531
|
+
if converter is None:
|
|
532
|
+
di_flag = True
|
|
533
|
+
continue
|
|
534
|
+
if di_flag:
|
|
535
|
+
raise errors.HandlerSignatureError(
|
|
536
|
+
func.__qualname__,
|
|
537
|
+
param.name,
|
|
538
|
+
"is converter-typed but sits after the wire-argument section; "
|
|
539
|
+
"move it before the first injected parameter, or wrap it in its own type",
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
if param.default is inspect.Parameter.empty:
|
|
543
|
+
required_count += 1
|
|
544
|
+
|
|
545
|
+
converters[param.name] = converter
|
|
546
|
+
fingerprint = wire.pack_digest("".join(c.type_id for c in converters.values()), chars=FINGERPRINT_LENGTH)
|
|
547
|
+
return HandlerSignature(converters=converters, required=required_count, fingerprint=fingerprint)
|
|
@@ -0,0 +1,36 @@
|
|
|
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
|
+
"""Discord's limits and timings, and the attribute risa stamps on view classes."""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import typing
|
|
25
|
+
|
|
26
|
+
__all__ = (
|
|
27
|
+
"AUTO_DEFER_DELAY",
|
|
28
|
+
"INTERACTION_WINDOW",
|
|
29
|
+
"MAX_CUSTOM_ID_LENGTH",
|
|
30
|
+
"VIEW_META",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
MAX_CUSTOM_ID_LENGTH: typing.Final[int] = 100
|
|
34
|
+
VIEW_META: typing.Final[str] = "__risa_view_meta__"
|
|
35
|
+
AUTO_DEFER_DELAY: typing.Final[float] = 2.0
|
|
36
|
+
INTERACTION_WINDOW: typing.Final[float] = 3.0
|