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.
@@ -0,0 +1,151 @@
1
+ //----------------------
2
+ // <auto-generated>
3
+ // Generated by sprig from {{ source }} ({{ spec.protocol }} {{ spec.version }}). Do not edit: change the spec and regenerate.
4
+ // C# 5: Bonsai compiles its Extensions folder with a C# 5 compiler.
5
+ // </auto-generated>
6
+ //----------------------
7
+ using System;
8
+ using System.ComponentModel;
9
+ using System.Reactive.Linq;
10
+ using Bonsai;
11
+ using Sprig;
12
+ using Bonsai.Sprig;
13
+
14
+ namespace {{ namespace }}
15
+ {
16
+ public static class {{ cls }}Info
17
+ {
18
+ public const string Name = "{{ spec.protocol }}";
19
+ public const string Version = "{{ spec.version }}";
20
+ public const int DefaultRpcPort = {{ spec.endpoints.zmq_rpc }};
21
+ public const int DefaultEventsPort = {{ spec.endpoints.zmq_events }};
22
+
23
+ /// <summary>The normalized manifest, as describe returns it.</summary>
24
+ public const string ManifestJson = {{ manifest_json | verbatim }};
25
+
26
+ /// <summary>The spec this code was generated from; recordings carry a copy.</summary>
27
+ public const string SpecYaml = {{ spec_text | verbatim }};
28
+
29
+ public static readonly ProtocolInfo Instance = new ProtocolInfo(Name, Version, ManifestJson, SpecYaml,
30
+ typeof({{ cls }}Server), typeof({{ cls }}Client),
31
+ new[]
32
+ {
33
+ {%- for op in operations %}
34
+ new OperationInfo("{{ op.name }}", "{{ op.member }}", typeof({{ op.member }}Call), typeof({{ op.request }}), typeof({{ op.reply }}){% for e in op.errors %}, typeof({{ e }}){% endfor %}),
35
+ {%- endfor %}
36
+ },
37
+ new[]
38
+ {
39
+ {%- for ch in channels %}
40
+ new ChannelInfo("{{ ch.name }}", "{{ ch.member }}", typeof({{ ch.payload }}), {{ ch.server_to_client }}, {{ ch.retain_last }}),
41
+ {%- endfor %}
42
+ });
43
+ }
44
+
45
+ [Description("An operation of {{ spec.protocol }}.")]
46
+ public enum {{ cls }}Operation
47
+ {
48
+ Unspecified,
49
+ {%- for op in operations %}
50
+ {{ op.member }},
51
+ {%- endfor %}
52
+ }
53
+
54
+ [Description("A channel of {{ spec.protocol }}.")]
55
+ public enum {{ cls }}Channel
56
+ {
57
+ {%- for ch in channels %}
58
+ {{ ch.member }},
59
+ {%- endfor %}
60
+ }
61
+
62
+ /// <summary>The {{ spec.protocol }} operations and channels Parse can select, plus empty for every message.</summary>
63
+ public class {{ cls }}MessageNames : MessageNameConverter
64
+ {
65
+ protected override ProtocolInfo Protocol { get { return {{ cls }}Info.Instance; } }
66
+ }
67
+ {% for op in operations %}
68
+ /// <summary>A '{{ op.name }}' request. Answer it with Reply.</summary>
69
+ [RpcOperation("{{ op.name }}"{% for e in op.errors %}, typeof({{ e }}){% endfor %})]
70
+ public sealed class {{ op.member }}Call : RpcCall<{{ op.request }}, {{ op.reply }}>
71
+ {
72
+ public {{ op.member }}Call(RawMessage message) : base(message) { }
73
+ }
74
+ {% endfor %}
75
+ {%- for side in sides %}
76
+ /// <summary>A running {{ spec.protocol }} {{ side.lower }}. Feed it to Parse, Reply, Request or Publish.</summary>
77
+ public sealed class {{ cls }}{{ side.name }} : {{ side.base }}
78
+ {
79
+ public {{ cls }}{{ side.name }}(string name, string rpcAddress, string eventsAddress, TimeSpan timeout{% if side.server %}, TimeSpan heartbeatPeriod{% endif %})
80
+ : base({{ cls }}Info.Instance, name, rpcAddress, eventsAddress, timeout{% if side.server %}, heartbeatPeriod{% endif %}) { }
81
+ }
82
+
83
+ [Description("{{ side.doc }}")]
84
+ [WorkflowElementCategory(ElementCategory.Source)]
85
+ public class Create{{ cls }}{{ side.name }} : Source<{{ cls }}{{ side.name }}>
86
+ {
87
+ public Create{{ cls }}{{ side.name }}()
88
+ {
89
+ Name = "{{ spec.protocol }}";
90
+ RpcAddress = "tcp://{{ side.host }}:{{ spec.endpoints.zmq_rpc }}";
91
+ EventsAddress = "tcp://{{ side.host }}:{{ spec.endpoints.zmq_events }}";
92
+ Timeout = TimeSpan.FromSeconds(10);
93
+ {%- if side.server %}
94
+ HeartbeatPeriod = TimeSpan.FromSeconds(1);
95
+ {%- endif %}
96
+ }
97
+
98
+ [Description("The name this endpoint signs its messages with.")]
99
+ public string Name { get; set; }
100
+ public string RpcAddress { get; set; }
101
+ public string EventsAddress { get; set; }
102
+ {% for ts in side.timespans %}
103
+ [Description("{{ ts.doc }}")]
104
+ [System.Xml.Serialization.XmlIgnore]
105
+ public TimeSpan {{ ts.name }} { get; set; }
106
+
107
+ [Browsable(false)]
108
+ [System.Xml.Serialization.XmlElement("{{ ts.name }}")]
109
+ public string {{ ts.name }}Xml
110
+ {
111
+ get { return System.Xml.XmlConvert.ToString({{ ts.name }}); }
112
+ set { {{ ts.name }} = System.Xml.XmlConvert.ToTimeSpan(value); }
113
+ }
114
+ {% endfor %}
115
+ public override IObservable<{{ cls }}{{ side.name }}> Generate()
116
+ {
117
+ return Observable.Defer(() => Observable.Return(new {{ cls }}{{ side.name }}(Name, RpcAddress, EventsAddress, Timeout{% if side.server %}, HeartbeatPeriod{% endif %})));
118
+ }
119
+ }
120
+ {% endfor %}
121
+ [Description("Subscribes to a {{ spec.protocol }} server or client: every message, one operation's requests, or one channel.")]
122
+ public class Parse : ParseBuilder
123
+ {
124
+ [Description("An operation (server: claims it and emits its requests) or a channel. Empty: every message.")]
125
+ [TypeConverter(typeof({{ cls }}MessageNames))]
126
+ public string Type { get; set; }
127
+
128
+ protected override ProtocolInfo Protocol { get { return {{ cls }}Info.Instance; } }
129
+ protected override string Selected { get { return Type; } }
130
+ }
131
+
132
+ [Description("Sends {{ spec.protocol }} requests through a client (inputs: requests, then the client) and emits the replies.")]
133
+ public class Request : RequestBuilder
134
+ {
135
+ [Description("Needed only when several operations take the input type.")]
136
+ public {{ cls }}Operation Operation { get; set; }
137
+
138
+ protected override ProtocolInfo Protocol { get { return {{ cls }}Info.Instance; } }
139
+ protected override string Selected { get { return Operation == {{ cls }}Operation.Unspecified ? null : Operation.ToString(); } }
140
+ }
141
+
142
+ [Description("Publishes on a {{ spec.protocol }} channel (inputs: values, then the server or client).")]
143
+ public class Publish : PublishBuilder
144
+ {
145
+ [Description("The channel to publish on.")]
146
+ public {{ cls }}Channel Channel { get; set; }
147
+
148
+ protected override ProtocolInfo Protocol { get { return {{ cls }}Info.Instance; } }
149
+ protected override string Selected { get { return Channel.ToString(); } }
150
+ }
151
+ }
@@ -0,0 +1,58 @@
1
+ # Generated by sprig from {{ source }} ({{ spec.protocol }} {{ spec.version }}). Do not edit: change the spec and regenerate.
2
+ """{{ (spec.description or spec.protocol ~ " protocol") | replace('"""', "'''") }}"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import enum # noqa: F401
7
+ import typing as t # noqa: F401
8
+ from datetime import datetime # noqa: F401
9
+
10
+ from pydantic import Field # noqa: F401
11
+
12
+ from sprig import BaseProtocol, Bytes, Channel, Direction, Model, Rpc, channel, rpc # noqa: F401
13
+ {%- if module.imports %}
14
+ from sprig import {{ module.imports | join(", ") }}
15
+ {%- endif %}
16
+
17
+ SPEC = {{ spec_text | pyblock }}
18
+ """The spec this module was generated from."""
19
+ {% for e in module.enums %}
20
+
21
+ class {{ e.name }}({{ e.base }}):
22
+ {%- if e.description %}
23
+ """{{ e.description | docstring }}"""
24
+ {% endif %}
25
+ {%- for m in e.members %}
26
+ {{ m.name }} = {{ m.value }}
27
+ {%- endfor %}
28
+ {% endfor %}
29
+ {%- for m in module.models %}
30
+
31
+ class {{ m.name }}(Model):
32
+ {%- if m.description %}
33
+ """{{ m.description | docstring }}"""
34
+ {%- endif %}
35
+ {%- if not m.fields and not m.description %}
36
+ pass
37
+ {%- endif %}
38
+ {%- for f in m.fields %}
39
+ {{ f.name }}: {{ f.annotation }}{% if f.default is not none %} = {{ f.default }}{% endif %}
40
+ {%- endfor %}
41
+ {% endfor %}
42
+
43
+ class {{ spec.class_name }}(BaseProtocol, spec=SPEC):
44
+ """{{ (spec.description or spec.protocol) | docstring }}"""
45
+ {% for name, op in operations %}
46
+ {{ name }}: Rpc[{{ op.request }}, {{ op.reply }}] = rpc(
47
+ {%- if op.errors %}errors=[{{ op.errors | join(", ") }}], {% endif -%}
48
+ description={{ op.description | pyrepr }})
49
+ {%- endfor %}
50
+ {%- for name, ch in channels %}
51
+ {{ name }}: Channel[{{ ch.payload }}] = channel(
52
+ {%- if ch.direction == "client_to_server" %}direction=Direction.CLIENT_TO_SERVER, {% endif -%}
53
+ {%- if ch.retain_last %}retain_last=True, {% endif -%}
54
+ description={{ ch.description | pyrepr }})
55
+ {%- endfor %}
56
+ {%- if not operations and not channels %}
57
+ pass
58
+ {%- endif %}
sprig/envelope.py ADDED
@@ -0,0 +1,138 @@
1
+ """Wire messages. Every message shares one header; only the framing differs per transport.
2
+
3
+ ``name`` is the operation (request, reply, error) or channel (event, notification). The
4
+ payload type follows from ``(kind, name)`` through the manifest.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import enum
10
+ import typing as t
11
+ import uuid
12
+ from datetime import UTC, datetime
13
+
14
+ from pydantic import BaseModel, Field, TypeAdapter
15
+
16
+ P = t.TypeVar("P")
17
+
18
+
19
+ class MessageKind(enum.StrEnum):
20
+ REQUEST = "request"
21
+ REPLY = "reply"
22
+ ERROR = "error"
23
+ EVENT = "event"
24
+ NOTIFICATION = "notification"
25
+
26
+
27
+ class ErrorCode:
28
+ METHOD_NOT_FOUND = "method_not_found"
29
+ INVALID_PARAMS = "invalid_params"
30
+ INTERNAL_ERROR = "internal_error"
31
+ TIMEOUT = "timeout"
32
+ NO_REPLY = "no_reply"
33
+ SERVER_STOPPED = "server_stopped" # the server stopped before answering
34
+ # Declared errors use the error type's name, e.g. "AlreadyRunning".
35
+
36
+
37
+ def utcnow() -> datetime:
38
+ return datetime.now(UTC)
39
+
40
+
41
+ def new_id() -> str:
42
+ return uuid.uuid4().hex[:12]
43
+
44
+
45
+ class Message(BaseModel, t.Generic[P]):
46
+ """Root of every message."""
47
+
48
+ kind: MessageKind
49
+ name: str
50
+ timestamp: datetime = Field(default_factory=utcnow)
51
+ source: str = ""
52
+ payload: P
53
+
54
+
55
+ class Request(Message[P]):
56
+ kind: t.Literal[MessageKind.REQUEST] = MessageKind.REQUEST
57
+ id: str = Field(default_factory=new_id)
58
+
59
+
60
+ E = t.TypeVar("E", bound=BaseModel)
61
+
62
+
63
+ class ErrorInfo(BaseModel):
64
+ code: str
65
+ message: str
66
+ data: t.Any = None
67
+
68
+ def as_(self, model: type[E]) -> E:
69
+ """The error's data as a declared error model: ``reply.error.as_(AlreadyRunning)``."""
70
+ return model.model_validate(self.data or {})
71
+
72
+
73
+ class RemoteError(Exception):
74
+ """An error reply, raised by ``Reply.raise_from_error()``."""
75
+
76
+ def __init__(self, code: str, message: str, data: t.Any = None, error: BaseModel | None = None) -> None:
77
+ super().__init__(f"{code}: {message}")
78
+ self.code, self.message, self.data = code, message, data
79
+ self.error = error # the declared error's model, when the client knows it
80
+
81
+
82
+ class Reply(Message[P]):
83
+ """A reply. On the client, an error reply or a timeout is a Reply too, with ``error`` set and no payload.
84
+
85
+ ``request``, ``error`` and ``declared`` are filled in by the client and never sent.
86
+ """
87
+
88
+ kind: t.Literal[MessageKind.REPLY] = MessageKind.REPLY
89
+ id: str
90
+ payload: P | None = None # type: ignore[assignment] # None exactly when error is set
91
+ error: ErrorInfo | None = Field(default=None, exclude=True)
92
+ request: Request[t.Any] | None = Field(default=None, exclude=True, repr=False)
93
+ declared: BaseModel | None = Field(default=None, exclude=True, repr=False)
94
+
95
+ @property
96
+ def ok(self) -> bool:
97
+ return self.error is None
98
+
99
+ def raise_from_error(self) -> P:
100
+ """The payload, or ``RemoteError`` if this is an error reply (like ``raise_for_status``)."""
101
+ if self.error is not None:
102
+ raise RemoteError(self.error.code, self.error.message, self.error.data, self.declared)
103
+ return t.cast(P, self.payload)
104
+
105
+
106
+ class ErrorReply(Message[ErrorInfo]):
107
+ kind: t.Literal[MessageKind.ERROR] = MessageKind.ERROR
108
+ id: str
109
+
110
+
111
+ class Event(Message[P]):
112
+ """Server-to-client channel message."""
113
+
114
+ kind: t.Literal[MessageKind.EVENT] = MessageKind.EVENT
115
+ seq: int
116
+
117
+
118
+ class Notification(Message[P]):
119
+ """Client-to-server channel message. No reply."""
120
+
121
+ kind: t.Literal[MessageKind.NOTIFICATION] = MessageKind.NOTIFICATION
122
+ seq: int = 0
123
+
124
+
125
+ AnyMessage = t.Annotated[
126
+ Request[t.Any] | Reply[t.Any] | ErrorReply | Event[t.Any] | Notification[t.Any],
127
+ Field(discriminator="kind"),
128
+ ]
129
+ _any = TypeAdapter(AnyMessage)
130
+
131
+
132
+ def parse_message(raw: t.Any) -> Message[t.Any]:
133
+ """Parse any wire message into its kind's class. Payloads stay as plain JSON values."""
134
+ return t.cast(Message[t.Any], _any.validate_python(raw))
135
+
136
+
137
+ def dump(message: Message[t.Any]) -> dict[str, t.Any]:
138
+ return message.model_dump(mode="json")
sprig/loader.py ADDED
@@ -0,0 +1,42 @@
1
+ """Runtime generation: build a protocol module in memory from a spec, a server's manifest or a recording.
2
+
3
+ The module is the static generator's output, rendered and executed, so runtime and static modules are
4
+ identical by construction. Modules are cached by the spec's content hash.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ import types
11
+ import typing as t
12
+ from pathlib import Path
13
+
14
+ from .spec import Spec, load_spec
15
+
16
+ _CACHE: dict[str, types.ModuleType] = {}
17
+
18
+
19
+ def load(source: str | Path | Spec | t.Mapping[str, t.Any]) -> types.ModuleType:
20
+ """Return the generated module for a spec: a path, YAML text, a manifest mapping, or a ``Spec``.
21
+
22
+ ``fip = sprig.load("protocol.yml")`` gives ``fip.FipProtocol``, ``fip.StartRequest``, ... and ``fip.SPEC``.
23
+ """
24
+ from .codegen.render import render_python # deferred: jinja is only needed here and in the CLI
25
+
26
+ spec = source if isinstance(source, Spec) else load_spec(source)
27
+ key = f"{spec.protocol}_{spec.digest()}"
28
+ module = _CACHE.get(key)
29
+ if module is not None:
30
+ return module
31
+ code = render_python(spec, source=f"<sprig.load {spec.protocol} {spec.version}>")
32
+ name = f"sprig.loaded.{key}"
33
+ module = types.ModuleType(name)
34
+ module.__file__ = f"<{name}>"
35
+ sys.modules[name] = module # pydantic resolves annotations through the module
36
+ try:
37
+ exec(compile(code, module.__file__, "exec"), module.__dict__) # noqa: S102 - code rendered from a checked spec
38
+ except BaseException:
39
+ del sys.modules[name]
40
+ raise
41
+ _CACHE[key] = module
42
+ return module
sprig/protocol.py ADDED
@@ -0,0 +1,233 @@
1
+ """Protocol classes, as generated from a spec.
2
+
3
+ A protocol is a class whose annotations are ``Rpc[Request, Reply]`` (request/reply)
4
+ or ``Channel[Payload]`` (pub/sub). The class is never instantiated; it is read once,
5
+ when it is defined, and checked. Generated classes pass ``spec=`` (the spec text they
6
+ were generated from); ``Protocol.spec()`` returns it loaded.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import enum
12
+ import inspect
13
+ import re
14
+ import typing as t
15
+ from dataclasses import dataclass
16
+
17
+ from pydantic import BaseModel, ConfigDict, PlainSerializer
18
+
19
+ from .spec import Direction, Spec, load_spec, pascal_case
20
+
21
+ __all__ = ["Channel", "Direction", "Empty", "Model", "Protocol", "ProtocolError", "Rpc", "channel", "rpc"]
22
+
23
+ TRequest = t.TypeVar("TRequest", bound=BaseModel)
24
+ TReply = t.TypeVar("TReply", bound=BaseModel)
25
+ TPayload = t.TypeVar("TPayload", bound=BaseModel)
26
+
27
+ RESERVED_NAMES = frozenset({"describe"})
28
+ _NAME = re.compile(r"^[a-z][a-z0-9_]*$")
29
+
30
+
31
+ class ProtocolError(TypeError):
32
+ """A protocol definition is invalid."""
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Rpc(t.Generic[TRequest, TReply]):
37
+ """A request/reply operation: ``start: Rpc[StartRequest, StartReply]``.
38
+
39
+ On a protocol class, ``FipProtocol.start`` is the operation itself, typed by its annotation.
40
+ ``name`` is the spec's (and the wire's) PascalCase name: ``Start``.
41
+ """
42
+
43
+ name: str
44
+ request: type[TRequest]
45
+ reply: type[TReply]
46
+ errors: tuple[type[BaseModel], ...] = ()
47
+ description: str | None = None
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Channel(t.Generic[TPayload]):
52
+ """A pub/sub channel: ``trial: Channel[TrialOutcome]``. ``FipProtocol.trial`` is the channel itself.
53
+
54
+ ``name`` is the spec's (and the wire's) PascalCase name: ``Trial``.
55
+ """
56
+
57
+ name: str
58
+ payload: type[TPayload]
59
+ direction: Direction = Direction.SERVER_TO_CLIENT
60
+ retain_last: bool = False
61
+ description: str | None = None
62
+
63
+
64
+ class Model(BaseModel):
65
+ """Base of every payload model. Python fields are snake_case; on the wire they carry the spec's PascalCase
66
+ names (``frame_rate_hz`` <-> ``FrameRateHz``). Either name is accepted when building a model."""
67
+
68
+ model_config = ConfigDict(
69
+ alias_generator=pascal_case, validate_by_name=True, validate_by_alias=True, serialize_by_alias=True
70
+ )
71
+
72
+
73
+ class Empty(Model):
74
+ """No parameters or no result."""
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class _RpcOptions:
79
+ errors: tuple[type[BaseModel], ...] = ()
80
+ description: str | None = None
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class _ChannelOptions:
85
+ direction: Direction = Direction.SERVER_TO_CLIENT
86
+ retain_last: bool = False
87
+ description: str | None = None
88
+
89
+
90
+ def rpc(*, errors: t.Sequence[type[BaseModel]] = (), description: str | None = None) -> t.Any:
91
+ """Options for an ``Rpc`` field. ``errors`` lists the typed errors the operation may return."""
92
+ return _RpcOptions(tuple(errors), description)
93
+
94
+
95
+ def channel(
96
+ *,
97
+ direction: Direction = Direction.SERVER_TO_CLIENT,
98
+ retain_last: bool = False,
99
+ description: str | None = None,
100
+ ) -> t.Any:
101
+ """Options for a ``Channel`` field. ``retain_last`` sends the latest value to new subscribers."""
102
+ return _ChannelOptions(direction, retain_last, description)
103
+
104
+
105
+ class Protocol:
106
+ """Base class for protocol declarations.
107
+
108
+ Subclass with ``name=`` and ``version=`` keywords; subclasses inherit the
109
+ operations and channels of their bases.
110
+ """
111
+
112
+ __protocol_name__: t.ClassVar[str | None] = None
113
+ __protocol_version__: t.ClassVar[str | None] = None
114
+ __protocol_spec__: t.ClassVar[Spec | None] = None
115
+ __operations__: t.ClassVar[dict[str, Rpc[t.Any, t.Any]]] = {}
116
+ __channels__: t.ClassVar[dict[str, Channel[t.Any]]] = {}
117
+
118
+ def __init_subclass__(
119
+ cls, *, name: str | None = None, version: str | None = None, spec: str | None = None, **kwargs: t.Any
120
+ ) -> None:
121
+ super().__init_subclass__(**kwargs)
122
+ if spec is not None:
123
+ loaded = load_spec(spec, name=f"{cls.__name__} spec")
124
+ cls.__protocol_spec__ = loaded
125
+ name, version = loaded.protocol, loaded.version
126
+ operations = dict(cls.__operations__)
127
+ channels = dict(cls.__channels__)
128
+ hints = t.get_type_hints(cls)
129
+ for field in inspect.get_annotations(cls):
130
+ hint = hints[field]
131
+ origin = t.get_origin(hint)
132
+ if origin is t.ClassVar:
133
+ continue
134
+ default = cls.__dict__.get(field)
135
+ _check_name(cls, field)
136
+ wire = pascal_case(field)
137
+ if wire in operations or wire in channels:
138
+ raise ProtocolError(f"{cls.__name__}.{field}: already defined by a base protocol")
139
+ member: Rpc[t.Any, t.Any] | Channel[t.Any]
140
+ if origin is Rpc:
141
+ request, reply = t.get_args(hint)
142
+ ropts = default if isinstance(default, _RpcOptions) else _RpcOptions()
143
+ for m in (request, reply, *ropts.errors):
144
+ _check_model(cls, field, m)
145
+ member = operations[wire] = Rpc(wire, request, reply, ropts.errors, ropts.description)
146
+ elif origin is Channel:
147
+ (payload,) = t.get_args(hint)
148
+ _check_model(cls, field, payload)
149
+ copts = default if isinstance(default, _ChannelOptions) else _ChannelOptions()
150
+ member = channels[wire] = Channel(wire, payload, copts.direction, copts.retain_last, copts.description)
151
+ else:
152
+ raise ProtocolError(
153
+ f"{cls.__name__}.{field}: annotation must be Rpc[Request, Reply] or Channel[Payload], got {hint!r}"
154
+ )
155
+ setattr(cls, field, member)
156
+ cls.__operations__ = operations
157
+ cls.__channels__ = channels
158
+ if name is not None:
159
+ cls.__protocol_name__ = name
160
+ if version is not None:
161
+ cls.__protocol_version__ = version
162
+ _check_unique_type_names(cls)
163
+ loaded_spec = cls.__protocol_spec__
164
+ if spec is not None and loaded_spec is not None:
165
+ declared = set(loaded_spec.operations) | set(loaded_spec.channels)
166
+ defined = set(operations) | set(channels)
167
+ if declared != defined:
168
+ raise ProtocolError(f"{cls.__name__} does not match its spec: {sorted(declared ^ defined)}")
169
+
170
+ @classmethod
171
+ def spec(cls) -> Spec:
172
+ """The spec this protocol was generated from."""
173
+ if cls.__protocol_spec__ is None:
174
+ raise ProtocolError(f"{cls.__name__} has no spec: protocols are generated from protocol.yml")
175
+ return cls.__protocol_spec__
176
+
177
+ @classmethod
178
+ def models(cls) -> list[type[BaseModel]]:
179
+ """Every model the protocol references directly, in declaration order."""
180
+ seen: dict[type[BaseModel], None] = {}
181
+ for op in cls.__operations__.values():
182
+ for m in (op.request, op.reply, *op.errors):
183
+ seen.setdefault(m)
184
+ for ch in cls.__channels__.values():
185
+ seen.setdefault(ch.payload)
186
+ return list(seen)
187
+
188
+
189
+ def _check_name(cls: type, field: str) -> None:
190
+ if not _NAME.match(field):
191
+ raise ProtocolError(f"{cls.__name__}.{field}: names must be snake_case")
192
+ if field in RESERVED_NAMES:
193
+ raise ProtocolError(f"{cls.__name__}.{field}: '{field}' is reserved")
194
+
195
+
196
+ def _check_model(cls: type, field: str, model: t.Any) -> None:
197
+ if not (isinstance(model, type) and issubclass(model, BaseModel)):
198
+ raise ProtocolError(f"{cls.__name__}.{field}: {model!r} is not a pydantic model")
199
+
200
+
201
+ def _walk_models(model: type[BaseModel], found: dict[type[BaseModel], None]) -> None:
202
+ if model in found:
203
+ return
204
+ found[model] = None
205
+ for name, f in model.model_fields.items():
206
+ if f.annotation is bytes and not any(isinstance(m, PlainSerializer) for m in f.metadata):
207
+ raise ProtocolError(f"{model.__name__}.{name}: use sprig.Bytes for binary data (base64 on the wire)")
208
+ _walk_annotation(f.annotation, found)
209
+
210
+
211
+ def _walk_annotation(annotation: t.Any, found: dict[type[BaseModel], None]) -> None:
212
+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):
213
+ _walk_models(annotation, found)
214
+ elif isinstance(annotation, type) and issubclass(annotation, enum.Enum):
215
+ found[annotation] = None # type: ignore[index]
216
+ for arg in t.get_args(annotation):
217
+ _walk_annotation(arg, found)
218
+
219
+
220
+ def _check_unique_type_names(cls: type[Protocol]) -> None:
221
+ """Two different classes with one name would become ``module__Name`` in C#. Refuse instead."""
222
+ found: dict[type[BaseModel], None] = {}
223
+ for m in cls.models():
224
+ _walk_models(m, found)
225
+ by_name: dict[str, list[type]] = {}
226
+ for m in found:
227
+ by_name.setdefault(m.__name__, []).append(m)
228
+ clashes = {n: ms for n, ms in by_name.items() if len(ms) > 1}
229
+ if clashes:
230
+ detail = "; ".join(
231
+ f"{n}: " + ", ".join(f"{m.__module__}.{m.__qualname__}" for m in ms) for n, ms in clashes.items()
232
+ )
233
+ raise ProtocolError(f"{cls.__name__}: type names must be unique across the protocol ({detail})")
sprig/py.typed ADDED
File without changes