sprigpy 0.1.0.dev1__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.
- sprig/__init__.py +52 -0
- sprig/base.py +47 -0
- sprig/client.py +415 -0
- sprig/codegen/__init__.py +1 -0
- sprig/codegen/cli.py +212 -0
- sprig/codegen/python.py +237 -0
- sprig/codegen/render.py +165 -0
- sprig/codegen/templates/bonsai/operators.cs.j2 +151 -0
- sprig/codegen/templates/python/protocol.py.j2 +58 -0
- sprig/envelope.py +138 -0
- sprig/loader.py +42 -0
- sprig/protocol.py +233 -0
- sprig/py.typed +0 -0
- sprig/recording.py +226 -0
- sprig/server.py +322 -0
- sprig/spec.py +497 -0
- sprig/transports/__init__.py +24 -0
- sprig/transports/http.py +180 -0
- sprig/transports/zmq.py +186 -0
- sprig/types.py +29 -0
- sprigpy-0.1.0.dev1.dist-info/METADATA +175 -0
- sprigpy-0.1.0.dev1.dist-info/RECORD +25 -0
- sprigpy-0.1.0.dev1.dist-info/WHEEL +4 -0
- sprigpy-0.1.0.dev1.dist-info/entry_points.txt +2 -0
- sprigpy-0.1.0.dev1.dist-info/licenses/LICENSE +21 -0
sprig/spec.py
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
"""The protocol spec: ``protocol.yml`` is where a protocol is written; everything else is generated from it.
|
|
2
|
+
|
|
3
|
+
``load_spec`` reads a spec (authoring YAML, or the normalized manifest a server returns from ``describe``),
|
|
4
|
+
checks it, and returns a ``Spec``. Normalizing fills defaults, implies ``type: object``, expands the
|
|
5
|
+
``$ref: Name`` shorthand to ``#/$defs/Name``, and adds what every protocol carries (the ``Heartbeat`` and
|
|
6
|
+
``Lifecycle`` channels, ``Empty`` and the base types). A normalized spec loads back unchanged.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import copy
|
|
12
|
+
import enum
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import keyword
|
|
16
|
+
import re
|
|
17
|
+
import typing as t
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import jsonschema
|
|
21
|
+
import yaml
|
|
22
|
+
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, ValidationError, field_validator
|
|
23
|
+
|
|
24
|
+
SPEC_FORMAT = 1
|
|
25
|
+
DESCRIBE, HEARTBEAT, LIFECYCLE = "Describe", "Heartbeat", "Lifecycle"
|
|
26
|
+
ALIVE = "_Alive" # internal notification: client liveness; never declared, never recorded
|
|
27
|
+
RESERVED_NAMES = frozenset({DESCRIBE, HEARTBEAT, LIFECYCLE})
|
|
28
|
+
|
|
29
|
+
_PASCAL = re.compile(r"^[A-Z][A-Za-z0-9]*$")
|
|
30
|
+
_NAME = re.compile(r"^[A-Z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$") # no runs of capitals: converts to snake_case and back
|
|
31
|
+
_SEMVER = re.compile(r"^\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$")
|
|
32
|
+
|
|
33
|
+
# The JSON Schema subset generated code understands, per schema object.
|
|
34
|
+
_KEYWORDS = frozenset(
|
|
35
|
+
{
|
|
36
|
+
"type", "properties", "required", "items", "enum", "$ref", "oneOf", "format", "default", "description",
|
|
37
|
+
"title", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "pattern",
|
|
38
|
+
"minItems", "maxItems", "additionalProperties", "x-enumNames", "contentEncoding",
|
|
39
|
+
}
|
|
40
|
+
) # fmt: skip
|
|
41
|
+
_TYPES = frozenset({"object", "string", "number", "integer", "boolean", "array", "null"})
|
|
42
|
+
_FORMATS = frozenset({"byte", "date-time"})
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Direction(enum.StrEnum):
|
|
46
|
+
SERVER_TO_CLIENT = "server_to_client"
|
|
47
|
+
CLIENT_TO_SERVER = "client_to_server"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class SpecError(ValueError):
|
|
51
|
+
"""A spec is invalid. The message names the file, line and key."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# -- the model ---------------------------------------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
DEFAULT_ZMQ_RPC = 5555
|
|
58
|
+
DEFAULT_ZMQ_EVENTS = 5556
|
|
59
|
+
DEFAULT_HTTP_PORT = 8080
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ZmqPorts(BaseModel):
|
|
63
|
+
model_config = ConfigDict(extra="forbid")
|
|
64
|
+
rpc: int | None = None
|
|
65
|
+
events: int | None = None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class HttpPorts(BaseModel):
|
|
69
|
+
model_config = ConfigDict(extra="forbid")
|
|
70
|
+
port: int | None = None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Endpoints(BaseModel):
|
|
74
|
+
"""Optional default ports: a deployment hint, not part of the protocol contract.
|
|
75
|
+
|
|
76
|
+
An address given to a server or client always wins; then these; then the library defaults (5555, 5556, 8080).
|
|
77
|
+
Only ports the spec declares are kept, so a normalized spec does not pretend to have chosen the library defaults.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
model_config = ConfigDict(extra="forbid")
|
|
81
|
+
zmq: ZmqPorts = Field(default_factory=ZmqPorts)
|
|
82
|
+
http: HttpPorts = Field(default_factory=HttpPorts)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def zmq_rpc(self) -> int:
|
|
86
|
+
return self.zmq.rpc if self.zmq.rpc is not None else DEFAULT_ZMQ_RPC
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def zmq_events(self) -> int:
|
|
90
|
+
return self.zmq.events if self.zmq.events is not None else DEFAULT_ZMQ_EVENTS
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def http_port(self) -> int:
|
|
94
|
+
return self.http.port if self.http.port is not None else DEFAULT_HTTP_PORT
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class OperationSpec(BaseModel):
|
|
98
|
+
model_config = ConfigDict(extra="forbid")
|
|
99
|
+
request: str
|
|
100
|
+
reply: str
|
|
101
|
+
errors: list[str] = Field(default_factory=list)
|
|
102
|
+
description: str | None = None
|
|
103
|
+
handled: bool | None = Field(default=None, description="Filled in by a running server")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ChannelSpec(BaseModel):
|
|
107
|
+
model_config = ConfigDict(extra="forbid")
|
|
108
|
+
payload: str
|
|
109
|
+
direction: Direction = Direction.SERVER_TO_CLIENT
|
|
110
|
+
retain_last: bool = False
|
|
111
|
+
description: str | None = None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class Spec(BaseModel):
|
|
115
|
+
"""A loaded, checked, normalized protocol spec."""
|
|
116
|
+
|
|
117
|
+
model_config = ConfigDict(extra="forbid")
|
|
118
|
+
sprig: int = SPEC_FORMAT
|
|
119
|
+
protocol: str
|
|
120
|
+
version: str
|
|
121
|
+
description: str | None = None
|
|
122
|
+
endpoints: Endpoints = Field(default_factory=Endpoints)
|
|
123
|
+
operations: dict[str, OperationSpec] = Field(default_factory=dict)
|
|
124
|
+
channels: dict[str, ChannelSpec] = Field(default_factory=dict)
|
|
125
|
+
types: dict[str, dict[str, t.Any]] = Field(default_factory=dict)
|
|
126
|
+
bound: dict[str, str] = Field(default_factory=dict, description="Addresses a running server bound")
|
|
127
|
+
_source_text: str | None = PrivateAttr(default=None)
|
|
128
|
+
|
|
129
|
+
@field_validator("types", mode="before")
|
|
130
|
+
@classmethod
|
|
131
|
+
def _types_may_be_empty(cls, value: t.Any) -> t.Any:
|
|
132
|
+
return {} if value is None else value
|
|
133
|
+
|
|
134
|
+
# -- derived ---------------------------------------------------------------------------------------------
|
|
135
|
+
@property
|
|
136
|
+
def class_name(self) -> str:
|
|
137
|
+
"""The generated protocol class: ``Fip`` -> ``FipProtocol``."""
|
|
138
|
+
return self.protocol + "Protocol"
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def user_types(self) -> dict[str, dict[str, t.Any]]:
|
|
142
|
+
"""Types the spec declares (without ``Empty`` and the base types the runtimes ship)."""
|
|
143
|
+
return {n: s for n, s in self.types.items() if n not in BUILTIN_TYPES}
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def major(self) -> int:
|
|
147
|
+
return int(self.version.split(".")[0])
|
|
148
|
+
|
|
149
|
+
def type_schema(self, name: str) -> dict[str, t.Any]:
|
|
150
|
+
"""A standalone JSON Schema for one type (for validating values)."""
|
|
151
|
+
return {"$ref": f"#/$defs/{name}", "$defs": self.types}
|
|
152
|
+
|
|
153
|
+
def manifest(self) -> dict[str, t.Any]:
|
|
154
|
+
"""The normalized form, as JSON-compatible data (what ``describe`` returns)."""
|
|
155
|
+
return self.model_dump(mode="json", exclude_none=True)
|
|
156
|
+
|
|
157
|
+
def to_yaml(self) -> str:
|
|
158
|
+
return yaml.safe_dump(self.manifest(), sort_keys=False, width=110, allow_unicode=True)
|
|
159
|
+
|
|
160
|
+
def digest(self) -> str:
|
|
161
|
+
"""Content hash of the normalized spec, ignoring runtime fields."""
|
|
162
|
+
body = self.model_dump(mode="json", exclude_none=True, exclude={"bound"})
|
|
163
|
+
for op in body["operations"].values():
|
|
164
|
+
op.pop("handled", None)
|
|
165
|
+
return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()[:16]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# -- what every protocol carries -----------------------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
BUILTIN_TYPES: dict[str, dict[str, t.Any]] = {
|
|
171
|
+
"Empty": {"type": "object", "description": "No parameters or no result.", "properties": {}},
|
|
172
|
+
"HeartbeatCode": {
|
|
173
|
+
"type": "integer",
|
|
174
|
+
"enum": [0, 1, 2, 3],
|
|
175
|
+
"x-enumNames": ["Ok", "Warning", "Error", "Critical"],
|
|
176
|
+
},
|
|
177
|
+
"Heartbeat": {
|
|
178
|
+
"type": "object",
|
|
179
|
+
"properties": {
|
|
180
|
+
"Code": {"$ref": "#/$defs/HeartbeatCode", "default": 0},
|
|
181
|
+
"Message": {"type": "string", "default": ""},
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
"LifecycleState": {"type": "string", "enum": ["started", "stopping", "lost"]},
|
|
185
|
+
"Lifecycle": {
|
|
186
|
+
"type": "object",
|
|
187
|
+
"properties": {
|
|
188
|
+
"State": {"$ref": "#/$defs/LifecycleState"},
|
|
189
|
+
"Instance": {
|
|
190
|
+
"type": "string",
|
|
191
|
+
"description": "Unique per server run; a new value means the server restarted",
|
|
192
|
+
},
|
|
193
|
+
"HeartbeatPeriodS": {
|
|
194
|
+
"type": "number",
|
|
195
|
+
"description": "How often the server sends a heartbeat; 0 for never",
|
|
196
|
+
},
|
|
197
|
+
},
|
|
198
|
+
"required": ["State", "Instance", "HeartbeatPeriodS"],
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
BASE_CHANNELS: dict[str, ChannelSpec] = {
|
|
203
|
+
HEARTBEAT: ChannelSpec(
|
|
204
|
+
payload="Heartbeat", retain_last=True, description="Health code and message, re-sent every heartbeat period"
|
|
205
|
+
),
|
|
206
|
+
LIFECYCLE: ChannelSpec(
|
|
207
|
+
payload="Lifecycle",
|
|
208
|
+
retain_last=True,
|
|
209
|
+
description="Server started or stopping; clients add 'lost' when heartbeats stop",
|
|
210
|
+
),
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# -- names ---------------------------------------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def snake_case(name: str) -> str:
|
|
218
|
+
"""A spec name in a Python identifier's form: ``FrameRateHz`` -> ``frame_rate_hz``, ``Led2Power`` -> ``led2_power``."""
|
|
219
|
+
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def pascal_case(name: str) -> str:
|
|
223
|
+
"""The inverse of ``snake_case``: ``frame_rate_hz`` -> ``FrameRateHz``."""
|
|
224
|
+
return "".join(part[:1].upper() + part[1:] for part in name.split("_") if part)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _name_problem(name: str) -> str | None:
|
|
228
|
+
if _NAME.match(name) and not re.search(r"[A-Z]{2}", name):
|
|
229
|
+
return None
|
|
230
|
+
hint = f"; try '{pascal_case(name.lower())}'" if re.match(r"^[A-Za-z][A-Za-z0-9_]*$", name) else ""
|
|
231
|
+
return f"'{name}' must be PascalCase, with acronyms written as words (HttpPort, not HTTPPort){hint}"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# -- loading -------------------------------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class _Lines:
|
|
238
|
+
"""Maps key paths to line numbers in the YAML source, for error messages."""
|
|
239
|
+
|
|
240
|
+
def __init__(self, source: str, text: str) -> None:
|
|
241
|
+
self.source = source
|
|
242
|
+
self._lines: dict[tuple[str | int, ...], int] = {}
|
|
243
|
+
try:
|
|
244
|
+
node = yaml.compose(text, Loader=yaml.SafeLoader)
|
|
245
|
+
except yaml.YAMLError:
|
|
246
|
+
node = None
|
|
247
|
+
if node is not None:
|
|
248
|
+
self._walk(node, ())
|
|
249
|
+
|
|
250
|
+
def _walk(self, node: yaml.Node, path: tuple[str | int, ...]) -> None:
|
|
251
|
+
self._lines[path] = node.start_mark.line + 1
|
|
252
|
+
if isinstance(node, yaml.MappingNode):
|
|
253
|
+
for key, value in node.value:
|
|
254
|
+
self._lines[(*path, key.value)] = key.start_mark.line + 1
|
|
255
|
+
self._walk(value, (*path, key.value))
|
|
256
|
+
elif isinstance(node, yaml.SequenceNode):
|
|
257
|
+
for i, value in enumerate(node.value):
|
|
258
|
+
self._walk(value, (*path, i))
|
|
259
|
+
|
|
260
|
+
def error(self, path: t.Sequence[str | int], message: str) -> SpecError:
|
|
261
|
+
key = tuple(path)
|
|
262
|
+
while key and key not in self._lines:
|
|
263
|
+
key = key[:-1]
|
|
264
|
+
line = self._lines.get(key)
|
|
265
|
+
where = f"{self.source}:{line}" if line else self.source
|
|
266
|
+
dotted = ".".join(str(p) for p in path)
|
|
267
|
+
return SpecError(f"{where}: {dotted}: {message}" if dotted else f"{where}: {message}")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def load_spec(source: str | Path | t.Mapping[str, t.Any], *, name: str | None = None) -> Spec:
|
|
271
|
+
"""Load and check a spec from a path, YAML/JSON text, or already-parsed data (a manifest)."""
|
|
272
|
+
text: str | None = None
|
|
273
|
+
if isinstance(source, Path) or (
|
|
274
|
+
isinstance(source, str) and "\n" not in source and source.endswith((".yml", ".yaml", ".json"))
|
|
275
|
+
):
|
|
276
|
+
path = Path(source)
|
|
277
|
+
text = path.read_text(encoding="utf-8")
|
|
278
|
+
label = name or str(path)
|
|
279
|
+
data = _parse(text, label)
|
|
280
|
+
elif isinstance(source, str):
|
|
281
|
+
text = source
|
|
282
|
+
label = name or "<spec>"
|
|
283
|
+
data = _parse(text, label)
|
|
284
|
+
else:
|
|
285
|
+
label = name or "<manifest>"
|
|
286
|
+
data = copy.deepcopy(dict(source))
|
|
287
|
+
lines = _Lines(label, text) if text is not None else _Lines(label, "")
|
|
288
|
+
if text is None:
|
|
289
|
+
# A manifest from a server: the base types are the runtimes' own; take ours whatever version sent them.
|
|
290
|
+
for builtin in BUILTIN_TYPES:
|
|
291
|
+
(data.get("types") or {}).pop(builtin, None)
|
|
292
|
+
spec = _build(data, lines)
|
|
293
|
+
_check(spec, lines)
|
|
294
|
+
spec._source_text = text
|
|
295
|
+
return spec
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def spec_text(spec: Spec) -> str:
|
|
299
|
+
"""The text a spec was loaded from, or its normalized YAML when it came from data."""
|
|
300
|
+
return spec._source_text or spec.to_yaml()
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _parse(text: str, label: str) -> dict[str, t.Any]:
|
|
304
|
+
try:
|
|
305
|
+
data = yaml.safe_load(text)
|
|
306
|
+
except yaml.YAMLError as e:
|
|
307
|
+
raise SpecError(f"{label}: not valid YAML: {e}") from None
|
|
308
|
+
if not isinstance(data, dict):
|
|
309
|
+
raise SpecError(f"{label}: a spec is a mapping with protocol, version, operations, channels and types")
|
|
310
|
+
return data
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _build(data: dict[str, t.Any], lines: _Lines) -> Spec:
|
|
314
|
+
data.pop("manifest_version", None) # older manifests
|
|
315
|
+
fmt = data.get("sprig", SPEC_FORMAT)
|
|
316
|
+
if fmt != SPEC_FORMAT:
|
|
317
|
+
raise lines.error(["sprig"], f"spec format {fmt} is not supported (this sprig reads {SPEC_FORMAT})")
|
|
318
|
+
raw_types = data.get("types") or {}
|
|
319
|
+
if not isinstance(raw_types, dict):
|
|
320
|
+
raise lines.error(["types"], "must be a mapping of type names to JSON Schemas")
|
|
321
|
+
for builtin, schema in BUILTIN_TYPES.items():
|
|
322
|
+
given = raw_types.get(builtin)
|
|
323
|
+
if given is not None and _normalize_schema(given) != schema:
|
|
324
|
+
raise lines.error(["types", builtin], f"'{builtin}' is built in and cannot be redefined")
|
|
325
|
+
data["types"] = {
|
|
326
|
+
**{n: copy.deepcopy(s) for n, s in BUILTIN_TYPES.items()},
|
|
327
|
+
**{n: _normalize_schema(s) for n, s in raw_types.items() if n not in BUILTIN_TYPES},
|
|
328
|
+
}
|
|
329
|
+
channels = data.get("channels") or {}
|
|
330
|
+
if not isinstance(channels, dict):
|
|
331
|
+
raise lines.error(["channels"], "must be a mapping of channel names to channels")
|
|
332
|
+
for base, base_spec in BASE_CHANNELS.items():
|
|
333
|
+
if base in channels and ChannelSpec.model_validate(channels[base]) != base_spec:
|
|
334
|
+
raise lines.error(["channels", base], f"'{base}' is reserved: every protocol carries it")
|
|
335
|
+
data["channels"] = {
|
|
336
|
+
**{n: c.model_dump() for n, c in BASE_CHANNELS.items()},
|
|
337
|
+
**{n: c for n, c in channels.items() if n not in BASE_CHANNELS},
|
|
338
|
+
}
|
|
339
|
+
data["operations"] = data.get("operations") or {}
|
|
340
|
+
data.setdefault("endpoints", {})
|
|
341
|
+
for key in ("zmq", "http"):
|
|
342
|
+
if data["endpoints"].get(key) is None:
|
|
343
|
+
data["endpoints"][key] = {}
|
|
344
|
+
try:
|
|
345
|
+
return Spec.model_validate(data)
|
|
346
|
+
except ValidationError as e:
|
|
347
|
+
err = e.errors()[0]
|
|
348
|
+
loc = [str(p) for p in err["loc"]]
|
|
349
|
+
message = err["msg"]
|
|
350
|
+
if err["type"] == "extra_forbidden":
|
|
351
|
+
message = f"unknown key '{loc[-1]}'" + (
|
|
352
|
+
" (in {...} flow style, quote values that contain commas)" if " " in loc[-1] else ""
|
|
353
|
+
)
|
|
354
|
+
raise lines.error(loc, message) from None
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _normalize_schema(schema: t.Any) -> dict[str, t.Any]:
|
|
358
|
+
"""``{}`` and ``properties`` imply ``type: object``; ``$ref: Name`` becomes ``#/$defs/Name``."""
|
|
359
|
+
if schema is None:
|
|
360
|
+
schema = {}
|
|
361
|
+
if not isinstance(schema, dict):
|
|
362
|
+
return t.cast(dict[str, t.Any], schema) # not a mapping: reported by _check
|
|
363
|
+
out = {k: _normalize_value(k, v) for k, v in schema.items()}
|
|
364
|
+
if "type" not in out and "$ref" not in out and "enum" not in out and "oneOf" not in out:
|
|
365
|
+
out["type"] = "object"
|
|
366
|
+
if out.get("type") == "object" and "properties" not in out and "additionalProperties" not in out:
|
|
367
|
+
out["properties"] = {}
|
|
368
|
+
if "enum" in out and "type" not in out:
|
|
369
|
+
kinds = {type(v) for v in out["enum"]}
|
|
370
|
+
out["type"] = "integer" if kinds == {int} else "number" if kinds <= {int, float} else "string"
|
|
371
|
+
# order: type first, then the rest as written (stable, readable output)
|
|
372
|
+
return {k: out[k] for k in sorted(out, key=lambda k: (k != "type", k != "$ref"))}
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _normalize_value(key: str, value: t.Any) -> t.Any:
|
|
376
|
+
if key == "$ref" and isinstance(value, str) and not value.startswith("#"):
|
|
377
|
+
return f"#/$defs/{value}"
|
|
378
|
+
if key == "properties" and isinstance(value, dict):
|
|
379
|
+
return {name: _normalize_inline(s) for name, s in value.items()}
|
|
380
|
+
if key in ("items", "additionalProperties") and isinstance(value, dict):
|
|
381
|
+
return _normalize_inline(value)
|
|
382
|
+
if key == "oneOf" and isinstance(value, list):
|
|
383
|
+
return [_normalize_inline(s) for s in value]
|
|
384
|
+
return value
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _normalize_inline(schema: t.Any) -> t.Any:
|
|
388
|
+
"""Property, item and union schemas: only expand refs (an inline object is reported by _check)."""
|
|
389
|
+
if not isinstance(schema, dict):
|
|
390
|
+
return schema
|
|
391
|
+
return {k: _normalize_value(k, v) for k, v in schema.items()}
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
# -- checks --------------------------------------------------------------------------------------------------
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _check(spec: Spec, lines: _Lines) -> None:
|
|
398
|
+
if problem := _name_problem(spec.protocol):
|
|
399
|
+
raise lines.error(["protocol"], problem)
|
|
400
|
+
if not _SEMVER.match(spec.version):
|
|
401
|
+
raise lines.error(["version"], f"'{spec.version}' is not a semantic version like 1.2.0")
|
|
402
|
+
for key, port in (
|
|
403
|
+
("zmq.rpc", spec.endpoints.zmq.rpc),
|
|
404
|
+
("zmq.events", spec.endpoints.zmq.events),
|
|
405
|
+
("http.port", spec.endpoints.http.port),
|
|
406
|
+
):
|
|
407
|
+
if port is not None and not 1 <= port <= 65535:
|
|
408
|
+
raise lines.error(["endpoints", *key.split(".")], f"port {port} is outside 1-65535")
|
|
409
|
+
if spec.endpoints.zmq_rpc == spec.endpoints.zmq_events:
|
|
410
|
+
raise lines.error(["endpoints", "zmq"], "rpc and events need different ports")
|
|
411
|
+
|
|
412
|
+
for name, s in spec.types.items():
|
|
413
|
+
if not _PASCAL.match(name):
|
|
414
|
+
raise lines.error(["types", name], f"type names are PascalCase, not '{name}'")
|
|
415
|
+
_check_schema(spec, s, ["types", name], lines, top=True)
|
|
416
|
+
|
|
417
|
+
seen: set[str] = set()
|
|
418
|
+
for kind, members in (("operations", spec.operations), ("channels", spec.channels)):
|
|
419
|
+
for name in members:
|
|
420
|
+
if name in BASE_CHANNELS and kind == "channels":
|
|
421
|
+
continue
|
|
422
|
+
if problem := _name_problem(name):
|
|
423
|
+
raise lines.error([kind, name], problem)
|
|
424
|
+
if name in RESERVED_NAMES:
|
|
425
|
+
raise lines.error([kind, name], f"'{name}' is reserved")
|
|
426
|
+
if name in seen:
|
|
427
|
+
raise lines.error([kind, name], f"'{name}' is both an operation and a channel")
|
|
428
|
+
seen.add(name)
|
|
429
|
+
for name, op in spec.operations.items():
|
|
430
|
+
for field in ("request", "reply"):
|
|
431
|
+
_check_type_ref(spec, getattr(op, field), ["operations", name, field], lines)
|
|
432
|
+
for i, err in enumerate(op.errors):
|
|
433
|
+
_check_type_ref(spec, err, ["operations", name, "errors", i], lines)
|
|
434
|
+
for name, ch in spec.channels.items():
|
|
435
|
+
_check_type_ref(spec, ch.payload, ["channels", name, "payload"], lines)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _check_type_ref(spec: Spec, type_name: str, path: list[str | int], lines: _Lines) -> None:
|
|
439
|
+
schema = spec.types.get(type_name)
|
|
440
|
+
if schema is None:
|
|
441
|
+
known = ", ".join(sorted(spec.user_types)) or "none"
|
|
442
|
+
raise lines.error(path, f"no type '{type_name}' (types: {known})")
|
|
443
|
+
if schema.get("type") != "object":
|
|
444
|
+
raise lines.error(path, f"'{type_name}' must be an object type to be a payload")
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _check_schema(spec: Spec, schema: t.Any, path: list[str | int], lines: _Lines, top: bool = False) -> None:
|
|
448
|
+
if not isinstance(schema, dict):
|
|
449
|
+
raise lines.error(path, "a schema is a mapping")
|
|
450
|
+
unknown = sorted(set(schema) - _KEYWORDS)
|
|
451
|
+
if unknown:
|
|
452
|
+
raise lines.error([*path, unknown[0]], f"'{unknown[0]}' is not supported in sprig schemas")
|
|
453
|
+
kind = schema.get("type")
|
|
454
|
+
kinds = kind if isinstance(kind, list) else [kind] if kind else []
|
|
455
|
+
for k in kinds:
|
|
456
|
+
if k not in _TYPES:
|
|
457
|
+
raise lines.error([*path, "type"], f"unknown type '{k}'")
|
|
458
|
+
if "$ref" in schema:
|
|
459
|
+
ref = schema["$ref"]
|
|
460
|
+
target = ref.removeprefix("#/$defs/")
|
|
461
|
+
if not ref.startswith("#/$defs/") or target not in spec.types:
|
|
462
|
+
raise lines.error([*path, "$ref"], f"no type '{target}'")
|
|
463
|
+
if "format" in schema and schema["format"] not in _FORMATS:
|
|
464
|
+
raise lines.error([*path, "format"], f"format '{schema['format']}' is not supported (byte, date-time)")
|
|
465
|
+
if "properties" in schema:
|
|
466
|
+
if not top:
|
|
467
|
+
raise lines.error(path, "inline objects are not supported: declare the object under types and $ref it")
|
|
468
|
+
for prop, sub in schema["properties"].items():
|
|
469
|
+
if problem := _name_problem(prop):
|
|
470
|
+
raise lines.error([*path, "properties", prop], problem)
|
|
471
|
+
if keyword.iskeyword(snake_case(prop)):
|
|
472
|
+
raise lines.error(
|
|
473
|
+
[*path, "properties", prop], f"'{prop}' becomes the Python keyword '{snake_case(prop)}'"
|
|
474
|
+
)
|
|
475
|
+
_check_schema(spec, sub, [*path, "properties", prop], lines)
|
|
476
|
+
for req in schema.get("required", []):
|
|
477
|
+
if req not in schema["properties"]:
|
|
478
|
+
raise lines.error([*path, "required"], f"'{req}' is required but not a property")
|
|
479
|
+
if "enum" in schema and not top:
|
|
480
|
+
values = schema["enum"]
|
|
481
|
+
if not all(isinstance(v, str) for v in values):
|
|
482
|
+
raise lines.error([*path, "enum"], "inline enums must be strings; declare others under types")
|
|
483
|
+
if isinstance(schema.get("items"), dict):
|
|
484
|
+
_check_schema(spec, schema["items"], [*path, "items"], lines)
|
|
485
|
+
if isinstance(schema.get("additionalProperties"), dict):
|
|
486
|
+
_check_schema(spec, schema["additionalProperties"], [*path, "additionalProperties"], lines)
|
|
487
|
+
for i, sub in enumerate(schema.get("oneOf", [])):
|
|
488
|
+
_check_schema(spec, sub, [*path, "oneOf", i], lines)
|
|
489
|
+
if "default" in schema:
|
|
490
|
+
try:
|
|
491
|
+
jsonschema.validate(
|
|
492
|
+
schema["default"], {**{k: v for k, v in schema.items() if k != "default"}, "$defs": spec.types}
|
|
493
|
+
)
|
|
494
|
+
except jsonschema.ValidationError as e:
|
|
495
|
+
raise lines.error(
|
|
496
|
+
[*path, "default"], f"default {schema['default']!r} does not match its schema: {e.message}"
|
|
497
|
+
) from None
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Transports. ZeroMQ is always available; HTTP needs the ``http`` extra (``pip install sprigpy[http]``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import typing as t
|
|
6
|
+
|
|
7
|
+
from .zmq import ZmqClientTransport, ZmqServerTransport
|
|
8
|
+
|
|
9
|
+
if t.TYPE_CHECKING:
|
|
10
|
+
from .http import HttpClientTransport, HttpServerTransport
|
|
11
|
+
|
|
12
|
+
__all__ = ["HttpClientTransport", "HttpServerTransport", "ZmqClientTransport", "ZmqServerTransport"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def __getattr__(name: str) -> t.Any:
|
|
16
|
+
if name in ("HttpClientTransport", "HttpServerTransport"):
|
|
17
|
+
try:
|
|
18
|
+
from . import http
|
|
19
|
+
except ModuleNotFoundError as e:
|
|
20
|
+
raise ModuleNotFoundError(
|
|
21
|
+
f"{name} needs the http extra: pip install 'sprigpy[http]' ({e.name} missing)"
|
|
22
|
+
) from e
|
|
23
|
+
return getattr(http, name)
|
|
24
|
+
raise AttributeError(name)
|