ruby-on-dspy 0.1.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 +7 -0
- data/CHANGELOG.md +112 -0
- data/LICENSE +21 -0
- data/README.md +442 -0
- data/exe/ruby-on-dspy +7 -0
- data/lib/dspy_rb/cli.rb +83 -0
- data/lib/dspy_rb/clients/dummy_lm.rb +81 -0
- data/lib/dspy_rb/clients/lm.rb +44 -0
- data/lib/dspy_rb/datasets/data_loader.rb +74 -0
- data/lib/dspy_rb/datasets/dataset.rb +37 -0
- data/lib/dspy_rb/datasets/python_random.rb +38 -0
- data/lib/dspy_rb/errors.rb +135 -0
- data/lib/dspy_rb/evaluate/evaluate.rb +53 -0
- data/lib/dspy_rb/evaluate/metric.rb +61 -0
- data/lib/dspy_rb/execution/around.rb +63 -0
- data/lib/dspy_rb/execution/collector.rb +61 -0
- data/lib/dspy_rb/execution/context.rb +160 -0
- data/lib/dspy_rb/execution/evaluation.rb +90 -0
- data/lib/dspy_rb/execution/optimization.rb +71 -0
- data/lib/dspy_rb/execution/program.rb +126 -0
- data/lib/dspy_rb/execution/rows.rb +41 -0
- data/lib/dspy_rb/execution/scorer.rb +68 -0
- data/lib/dspy_rb/execution/step.rb +116 -0
- data/lib/dspy_rb/execution/toolbox.rb +28 -0
- data/lib/dspy_rb/predict/chain_of_thought.rb +22 -0
- data/lib/dspy_rb/predict/predict.rb +101 -0
- data/lib/dspy_rb/predict/react.rb +80 -0
- data/lib/dspy_rb/primitives/module.rb +105 -0
- data/lib/dspy_rb/primitives/parts.rb +121 -0
- data/lib/dspy_rb/runtime/channel/callback.rb +105 -0
- data/lib/dspy_rb/runtime/channel/ending.rb +35 -0
- data/lib/dspy_rb/runtime/channel/exchange.rb +176 -0
- data/lib/dspy_rb/runtime/channel/gate.rb +74 -0
- data/lib/dspy_rb/runtime/channel/listener.rb +125 -0
- data/lib/dspy_rb/runtime/channel/meter.rb +46 -0
- data/lib/dspy_rb/runtime/channel/reporter.rb +68 -0
- data/lib/dspy_rb/runtime/channel/settler.rb +69 -0
- data/lib/dspy_rb/runtime/channel/traffic.rb +121 -0
- data/lib/dspy_rb/runtime/channel/watchdog.rb +36 -0
- data/lib/dspy_rb/runtime/channel/writer.rb +77 -0
- data/lib/dspy_rb/runtime/channel.rb +145 -0
- data/lib/dspy_rb/runtime/child.rb +48 -0
- data/lib/dspy_rb/runtime/python.rb +43 -0
- data/lib/dspy_rb/runtime/registry.rb +48 -0
- data/lib/dspy_rb/runtime/startup.rb +53 -0
- data/lib/dspy_rb/secrets.rb +25 -0
- data/lib/dspy_rb/setup/environment.rb +120 -0
- data/lib/dspy_rb/setup/stale.rb +102 -0
- data/lib/dspy_rb/setup/uv.rb +122 -0
- data/lib/dspy_rb/signatures/signature.rb +100 -0
- data/lib/dspy_rb/signatures/types.rb +44 -0
- data/lib/dspy_rb/source.rb +64 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot.rb +9 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_optuna.rb +9 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_random_search.rb +9 -0
- data/lib/dspy_rb/teleprompt/gepa.rb +9 -0
- data/lib/dspy_rb/teleprompt/labeled_few_shot.rb +14 -0
- data/lib/dspy_rb/teleprompt/mipro_v2.rb +16 -0
- data/lib/dspy_rb/teleprompt/optimizer.rb +127 -0
- data/lib/dspy_rb/teleprompt/simba.rb +16 -0
- data/lib/dspy_rb/tool.rb +108 -0
- data/lib/dspy_rb/values/check.rb +14 -0
- data/lib/dspy_rb/values/context.rb +46 -0
- data/lib/dspy_rb/values/dataset.rb +55 -0
- data/lib/dspy_rb/values/dict.rb +17 -0
- data/lib/dspy_rb/values/env.rb +23 -0
- data/lib/dspy_rb/values/evaluation_result.rb +31 -0
- data/lib/dspy_rb/values/example.rb +134 -0
- data/lib/dspy_rb/values/fault.rb +15 -0
- data/lib/dspy_rb/values/history.rb +13 -0
- data/lib/dspy_rb/values/list.rb +16 -0
- data/lib/dspy_rb/values/literal.rb +27 -0
- data/lib/dspy_rb/values/loss.rb +12 -0
- data/lib/dspy_rb/values/optional.rb +16 -0
- data/lib/dspy_rb/values/prediction.rb +58 -0
- data/lib/dspy_rb/values/reasoning.rb +13 -0
- data/lib/dspy_rb/values/spend.rb +27 -0
- data/lib/dspy_rb/values/types.rb +164 -0
- data/lib/dspy_rb/version.rb +11 -0
- data/lib/dspy_rb/wire/departure.rb +100 -0
- data/lib/dspy_rb/wire/descriptions.rb +220 -0
- data/lib/dspy_rb/wire/facts.rb +79 -0
- data/lib/dspy_rb/wire/in_flight.rb +128 -0
- data/lib/dspy_rb/wire/json.rb +76 -0
- data/lib/dspy_rb/wire/optimizers.rb +240 -0
- data/lib/dspy_rb/wire/records.rb +44 -0
- data/lib/dspy_rb/wire/replies.rb +188 -0
- data/lib/dspy_rb/wire/requests.rb +214 -0
- data/lib/dspy_rb/wire/shape.rb +25 -0
- data/lib/dspy_rb/wire/types.rb +23 -0
- data/lib/dspy_rb/wire.rb +34 -0
- data/lib/dspy_rb.rb +191 -0
- data/lib/ruby-on-dspy.rb +4 -0
- data/python/dspy_rb/__init__.py +1 -0
- data/python/dspy_rb/__main__.py +76 -0
- data/python/dspy_rb/server/__init__.py +1 -0
- data/python/dspy_rb/server/build.py +281 -0
- data/python/dspy_rb/server/calls.py +215 -0
- data/python/dspy_rb/server/conversion.py +180 -0
- data/python/dspy_rb/server/data.py +169 -0
- data/python/dspy_rb/server/evaluation.py +107 -0
- data/python/dspy_rb/server/facts.py +357 -0
- data/python/dspy_rb/server/optimization.py +98 -0
- data/python/dspy_rb/server/pulse.py +68 -0
- data/python/dspy_rb/server/ruby.py +206 -0
- data/python/dspy_rb/server/serve.py +369 -0
- data/python/dspy_rb/server/standins.py +364 -0
- data/python/dspy_rb/server/state.py +104 -0
- data/python/dspy_rb/server/traffic.py +93 -0
- data/python/dspy_rb/values.py +51 -0
- data/python/dspy_rb/wire/__init__.py +1 -0
- data/python/dspy_rb/wire/channel.py +107 -0
- data/python/dspy_rb/wire/lines.py +269 -0
- data/python/dspy_rb/wire/shapes.py +1220 -0
- data/python/dspy_rb/wire/wire.json +4592 -0
- data/python/pyproject.toml +86 -0
- data/python/uv.lock +1576 -0
- metadata +230 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""The two pipes between this server and one Ruby process: request lines in on one, reply lines out on the other."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import os
|
|
5
|
+
import selectors
|
|
6
|
+
import threading
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from io import FileIO
|
|
10
|
+
from typing import Final, Self, TextIO
|
|
11
|
+
|
|
12
|
+
from dspy_rb.wire.shapes import REPLIES_FD, REQUESTS_FD
|
|
13
|
+
|
|
14
|
+
READ_SIZE: Final = 65_536
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Channel:
|
|
19
|
+
"""One Ruby process's two pipes, and a way to stop reading them from any thread."""
|
|
20
|
+
|
|
21
|
+
requests: FileIO
|
|
22
|
+
replies: TextIO
|
|
23
|
+
_lock: threading.Lock = field(init=False, default_factory=threading.Lock)
|
|
24
|
+
_wake_pipe: tuple[int, int] = field(init=False, default_factory=os.pipe)
|
|
25
|
+
|
|
26
|
+
# Once closed, its numbers may belong to files opened since, so nothing writes to them.
|
|
27
|
+
_closed: bool = field(init=False, default=False)
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def opened(cls, requests: int, replies: int) -> Self:
|
|
31
|
+
"""Open a channel reading requests from the `requests` end and writing replies to the `replies` end."""
|
|
32
|
+
return cls(os.fdopen(requests, "rb", buffering=0), os.fdopen(replies, "w", encoding="utf-8"))
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def spawned(cls) -> Self:
|
|
36
|
+
"""Open the two ends a spawning Ruby passed, made blocking."""
|
|
37
|
+
os.set_blocking(REQUESTS_FD, True)
|
|
38
|
+
os.set_blocking(REPLIES_FD, True)
|
|
39
|
+
|
|
40
|
+
return cls.opened(REQUESTS_FD, REPLIES_FD)
|
|
41
|
+
|
|
42
|
+
def lines(self) -> Iterator[bytes]:
|
|
43
|
+
"""Each request line, until the end of input or until stop() is called."""
|
|
44
|
+
pending = bytearray()
|
|
45
|
+
wake, _ = self._wake_pipe
|
|
46
|
+
|
|
47
|
+
# A selector, since select() takes no end numbered past 1,023.
|
|
48
|
+
with selectors.DefaultSelector() as selector:
|
|
49
|
+
selector.register(self.requests.fileno(), selectors.EVENT_READ)
|
|
50
|
+
selector.register(wake, selectors.EVENT_READ)
|
|
51
|
+
|
|
52
|
+
while all(key.fd != wake for key, _ in selector.select()):
|
|
53
|
+
chunk = self.requests.read(READ_SIZE)
|
|
54
|
+
|
|
55
|
+
if not chunk:
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
read = len(pending)
|
|
59
|
+
pending += chunk
|
|
60
|
+
|
|
61
|
+
# Only the new piece can end a line, so each byte is searched and copied once.
|
|
62
|
+
end = pending.find(b"\n", read)
|
|
63
|
+
|
|
64
|
+
if end >= 0:
|
|
65
|
+
last = pending.rfind(b"\n")
|
|
66
|
+
|
|
67
|
+
yield from bytes(pending[:last]).split(b"\n")
|
|
68
|
+
|
|
69
|
+
del pending[: last + 1]
|
|
70
|
+
|
|
71
|
+
def stop(self) -> None:
|
|
72
|
+
"""End lines() at once, whichever thread it is reading on; a closed channel has nothing to end."""
|
|
73
|
+
_, waker = self._wake_pipe
|
|
74
|
+
|
|
75
|
+
with self._lock:
|
|
76
|
+
if not self._closed:
|
|
77
|
+
os.write(waker, b"\n")
|
|
78
|
+
|
|
79
|
+
def write(self, line: str) -> None:
|
|
80
|
+
"""Write one reply line, whole, whichever thread it comes from."""
|
|
81
|
+
with self._lock:
|
|
82
|
+
if self._closed:
|
|
83
|
+
return
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
self.replies.write(line + "\n")
|
|
87
|
+
self.replies.flush()
|
|
88
|
+
except BrokenPipeError:
|
|
89
|
+
# Ruby has gone, so the reply has no reader.
|
|
90
|
+
return
|
|
91
|
+
|
|
92
|
+
def close(self) -> None:
|
|
93
|
+
"""Close both pipes and the wake pipe, once."""
|
|
94
|
+
with self._lock:
|
|
95
|
+
if self._closed:
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
self._closed = True
|
|
99
|
+
|
|
100
|
+
# A reply left unsent because Ruby has gone has no reader either.
|
|
101
|
+
with contextlib.suppress(BrokenPipeError):
|
|
102
|
+
self.replies.close()
|
|
103
|
+
|
|
104
|
+
self.requests.close()
|
|
105
|
+
|
|
106
|
+
for end in self._wake_pipe:
|
|
107
|
+
os.close(end)
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""The wire's one reader and writer of lines, checked against wire.json."""
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Final, Literal, NoReturn, cast, overload
|
|
8
|
+
|
|
9
|
+
from dspy_rb.values import Malformed, Mismatch
|
|
10
|
+
from dspy_rb.wire.shapes import VIEWS, FromPython, FromRuby, JsonValue, Refused
|
|
11
|
+
|
|
12
|
+
DEFINITION: Final[dict[str, Any]] = json.loads(Path(__file__).with_name("wire.json").read_text(encoding="utf-8"))
|
|
13
|
+
PRIMITIVES: Final[dict[str, Callable[[object], bool]]] = {
|
|
14
|
+
"string": lambda value: isinstance(value, str),
|
|
15
|
+
"integer": lambda value: isinstance(value, int) and not isinstance(value, bool),
|
|
16
|
+
"number": lambda value: isinstance(value, int | float) and not isinstance(value, bool),
|
|
17
|
+
"boolean": lambda value: isinstance(value, bool),
|
|
18
|
+
"values": lambda value: isinstance(value, dict),
|
|
19
|
+
# Whatever JSON parsed is a value it carries.
|
|
20
|
+
"value": lambda _: True,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
# The constraints wire.json carries from the Ruby structs, each with how a value breaks it.
|
|
24
|
+
CONSTRAINTS: Final[dict[str, tuple[Callable[[Any, Any], bool], str]]] = {
|
|
25
|
+
"min_size": (lambda value, size: len(value) >= size, "shorter than {}"),
|
|
26
|
+
"gteq": (lambda value, least: value >= least, "less than {}"),
|
|
27
|
+
"excludes": (lambda value, key: key not in value, "holds {}"),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# A kind of descriptor's reader: the value as the definition reads it, or a Mismatch saying where it departs.
|
|
32
|
+
type Loader = Callable[[dict[str, Any], JsonValue, str], object]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RefusedError(Exception):
|
|
36
|
+
"""A well-formed request the server will not run; nothing ran."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MismatchError(ValueError):
|
|
40
|
+
"""A line made only of values already read or checked breaks the definition: a fault in this package."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@overload
|
|
44
|
+
def read(line: bytes | str) -> FromRuby | Malformed: ...
|
|
45
|
+
@overload
|
|
46
|
+
def read(line: bytes | str, direction: Literal["from_python"]) -> FromPython | Malformed: ...
|
|
47
|
+
def read(
|
|
48
|
+
line: bytes | str,
|
|
49
|
+
direction: Literal["from_ruby", "from_python"] = "from_ruby",
|
|
50
|
+
) -> FromRuby | FromPython | Malformed:
|
|
51
|
+
"""Read Ruby's line, or one of Python's for the tests, checked against the definition; a broken one as Malformed."""
|
|
52
|
+
try:
|
|
53
|
+
data = cast("JsonValue", json.loads(line, object_pairs_hook=_distinct, parse_constant=_constant))
|
|
54
|
+
except ValueError as error:
|
|
55
|
+
return Malformed(Refused(reason=f"not JSON with distinct keys: {error}"))
|
|
56
|
+
|
|
57
|
+
loaded = _load(DEFINITION[direction], data, "")
|
|
58
|
+
|
|
59
|
+
if isinstance(loaded, Mismatch):
|
|
60
|
+
request_id = _id(data) if direction == "from_ruby" else None
|
|
61
|
+
kind = data.get("kind") if isinstance(data, dict) else None
|
|
62
|
+
|
|
63
|
+
return Malformed(Refused(id=request_id, reason=str(loaded)), kind if isinstance(kind, str) else None)
|
|
64
|
+
|
|
65
|
+
return cast("FromRuby | FromPython", loaded)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def line(message: FromPython) -> str | Mismatch:
|
|
69
|
+
"""Write `message` as one JSON line, or give where it breaks the definition or holds what JSON cannot carry."""
|
|
70
|
+
data = dump(message)
|
|
71
|
+
loaded = _load(DEFINITION["from_python"], data, "")
|
|
72
|
+
|
|
73
|
+
if isinstance(loaded, Mismatch):
|
|
74
|
+
return loaded
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
return json.dumps(data, allow_nan=False, ensure_ascii=False)
|
|
78
|
+
except (TypeError, ValueError) as error:
|
|
79
|
+
return Mismatch("", f"holds what JSON cannot carry ({error})")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def line_or_raise(message: FromPython) -> str:
|
|
83
|
+
"""Write a line made only of values already read or checked, raising MismatchError should it break all the same."""
|
|
84
|
+
written = line(message)
|
|
85
|
+
|
|
86
|
+
if isinstance(written, Mismatch):
|
|
87
|
+
raise MismatchError(str(written))
|
|
88
|
+
|
|
89
|
+
return written
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def dump(view: object) -> JsonValue:
|
|
93
|
+
"""Turn a typed view into JSON values, its absent keys left out."""
|
|
94
|
+
if isinstance(view, list):
|
|
95
|
+
return [dump(item) for item in cast("list[object]", view)]
|
|
96
|
+
|
|
97
|
+
if dataclasses.is_dataclass(view) and not isinstance(view, type):
|
|
98
|
+
present = ((key.name, getattr(view, key.name)) for key in dataclasses.fields(view))
|
|
99
|
+
|
|
100
|
+
return {name: dump(value) for name, value in present if value is not None}
|
|
101
|
+
|
|
102
|
+
return cast("JsonValue", view)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _distinct(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
|
106
|
+
data = dict(pairs)
|
|
107
|
+
|
|
108
|
+
if len(data) < len(pairs):
|
|
109
|
+
message = "a key is repeated"
|
|
110
|
+
|
|
111
|
+
raise ValueError(message)
|
|
112
|
+
|
|
113
|
+
return data
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# Python reads NaN and Infinity by default, which Ruby's reader and JSON itself refuse.
|
|
117
|
+
def _constant(name: str) -> NoReturn:
|
|
118
|
+
message = f"{name} is not JSON"
|
|
119
|
+
|
|
120
|
+
raise ValueError(message)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _load(descriptor: dict[str, Any], value: JsonValue, path: str) -> object:
|
|
124
|
+
loader = LOADERS.get(descriptor["type"])
|
|
125
|
+
|
|
126
|
+
if loader is None:
|
|
127
|
+
message = f"wire.json holds a descriptor this reader does not know: {descriptor}"
|
|
128
|
+
|
|
129
|
+
raise ValueError(message)
|
|
130
|
+
|
|
131
|
+
return loader(descriptor, value, path)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _tagged(descriptor: dict[str, Any], value: JsonValue, path: str) -> object:
|
|
135
|
+
tag: str = descriptor["tag"]
|
|
136
|
+
by_tag: dict[str, str] = descriptor["shapes"]
|
|
137
|
+
kind = value.get(tag) if isinstance(value, dict) else None
|
|
138
|
+
|
|
139
|
+
if not isinstance(kind, str) or kind not in by_tag:
|
|
140
|
+
return Mismatch(path, f"no {tag} the wire has")
|
|
141
|
+
|
|
142
|
+
return _view(by_tag[kind], value, path)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _shape(descriptor: dict[str, Any], value: JsonValue, path: str) -> object:
|
|
146
|
+
return _view(descriptor["name"], value, path)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _array(descriptor: dict[str, Any], value: JsonValue, path: str) -> object:
|
|
150
|
+
if not isinstance(value, list):
|
|
151
|
+
return Mismatch(path, "not an array")
|
|
152
|
+
|
|
153
|
+
loaded: list[object] = []
|
|
154
|
+
|
|
155
|
+
for index, item in enumerate(value):
|
|
156
|
+
each = _load(descriptor["items"], item, f"{path}[{index}]")
|
|
157
|
+
|
|
158
|
+
if isinstance(each, Mismatch):
|
|
159
|
+
return each
|
|
160
|
+
|
|
161
|
+
loaded.append(each)
|
|
162
|
+
|
|
163
|
+
return loaded
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _map(descriptor: dict[str, Any], value: JsonValue, path: str) -> object:
|
|
167
|
+
if not isinstance(value, dict):
|
|
168
|
+
return Mismatch(path, "not an object")
|
|
169
|
+
|
|
170
|
+
loaded: dict[str, object] = {}
|
|
171
|
+
|
|
172
|
+
for key, item in value.items():
|
|
173
|
+
where = f"{path}.{key}"
|
|
174
|
+
name = _load(descriptor["keys"], key, where)
|
|
175
|
+
each = _load(descriptor["values"], item, where)
|
|
176
|
+
|
|
177
|
+
if isinstance(name, Mismatch):
|
|
178
|
+
return name
|
|
179
|
+
|
|
180
|
+
if isinstance(each, Mismatch):
|
|
181
|
+
return each
|
|
182
|
+
|
|
183
|
+
loaded[key] = each
|
|
184
|
+
|
|
185
|
+
return loaded
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _union(descriptor: dict[str, Any], value: JsonValue, path: str) -> object:
|
|
189
|
+
mismatches: list[Mismatch] = []
|
|
190
|
+
|
|
191
|
+
for form in descriptor["of"]:
|
|
192
|
+
loaded = _load(form, value, path)
|
|
193
|
+
|
|
194
|
+
if not isinstance(loaded, Mismatch):
|
|
195
|
+
return loaded
|
|
196
|
+
|
|
197
|
+
mismatches.append(loaded)
|
|
198
|
+
|
|
199
|
+
# The form the value went furthest into is the one it meant.
|
|
200
|
+
deepest = max(mismatches, key=lambda mismatch: len(mismatch.path))
|
|
201
|
+
|
|
202
|
+
return deepest if len(deepest.path) > len(path) else Mismatch(path, "matches none of its forms")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _enum(descriptor: dict[str, Any], value: JsonValue, path: str) -> object:
|
|
206
|
+
allowed: list[str] = descriptor["values"]
|
|
207
|
+
|
|
208
|
+
return value if value in allowed else Mismatch(path, f"not one of {', '.join(allowed)}")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _primitive(descriptor: dict[str, Any], value: JsonValue, path: str) -> object:
|
|
212
|
+
primitive = descriptor["type"]
|
|
213
|
+
|
|
214
|
+
if not PRIMITIVES[primitive](value):
|
|
215
|
+
return Mismatch(path, f"not {primitive}")
|
|
216
|
+
|
|
217
|
+
for name, bound in descriptor.get("constraints", {}).items():
|
|
218
|
+
holds, problem = CONSTRAINTS[name]
|
|
219
|
+
|
|
220
|
+
if not holds(value, bound):
|
|
221
|
+
return Mismatch(path, problem.format(bound))
|
|
222
|
+
|
|
223
|
+
return value
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _view(name: str, value: JsonValue, path: str) -> object:
|
|
227
|
+
if not isinstance(value, dict):
|
|
228
|
+
return Mismatch(path, f"not an object ({name})")
|
|
229
|
+
|
|
230
|
+
keys: dict[str, Any] = DEFINITION["shapes"][name]
|
|
231
|
+
unknown = sorted(set(value) - set(keys))
|
|
232
|
+
|
|
233
|
+
if unknown:
|
|
234
|
+
return Mismatch(path, f"{name} has no key {unknown[0]}")
|
|
235
|
+
|
|
236
|
+
loaded: dict[str, object] = {}
|
|
237
|
+
|
|
238
|
+
for key, rule in keys.items():
|
|
239
|
+
if key in value:
|
|
240
|
+
each = _load(rule["value"], value[key], f"{path}.{key}" if path else key)
|
|
241
|
+
|
|
242
|
+
if isinstance(each, Mismatch):
|
|
243
|
+
return each
|
|
244
|
+
|
|
245
|
+
loaded[key] = each
|
|
246
|
+
elif rule["required"] and "default" not in rule:
|
|
247
|
+
return Mismatch(path, f"{name} needs {key}")
|
|
248
|
+
|
|
249
|
+
return VIEWS[name](**loaded)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
# Each kind of descriptor's loader, by its type, after the loaders it names.
|
|
253
|
+
LOADERS: Final[dict[str, Loader]] = {
|
|
254
|
+
"tagged": _tagged,
|
|
255
|
+
"shape": _shape,
|
|
256
|
+
"union": _union,
|
|
257
|
+
"array": _array,
|
|
258
|
+
"map": _map,
|
|
259
|
+
"enum": _enum,
|
|
260
|
+
**dict.fromkeys(PRIMITIVES, _primitive),
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _id(data: JsonValue) -> int | None:
|
|
265
|
+
match data:
|
|
266
|
+
case {"id": int() as request_id} if not isinstance(request_id, bool) and request_id >= 1:
|
|
267
|
+
return request_id
|
|
268
|
+
case _:
|
|
269
|
+
return None
|