clamator-protocol 0.1.0__tar.gz
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.
- clamator_protocol-0.1.0/.gitignore +41 -0
- clamator_protocol-0.1.0/LICENSE +215 -0
- clamator_protocol-0.1.0/PKG-INFO +64 -0
- clamator_protocol-0.1.0/README.md +52 -0
- clamator_protocol-0.1.0/pyproject.toml +24 -0
- clamator_protocol-0.1.0/src/clamator_protocol/__init__.py +29 -0
- clamator_protocol-0.1.0/src/clamator_protocol/client_core.py +63 -0
- clamator_protocol-0.1.0/src/clamator_protocol/contract.py +20 -0
- clamator_protocol-0.1.0/src/clamator_protocol/envelope.py +133 -0
- clamator_protocol-0.1.0/src/clamator_protocol/error.py +40 -0
- clamator_protocol-0.1.0/src/clamator_protocol/server_core.py +100 -0
- clamator_protocol-0.1.0/src/clamator_protocol/transport.py +16 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Node
|
|
2
|
+
node_modules/
|
|
3
|
+
*.log
|
|
4
|
+
npm-debug.log*
|
|
5
|
+
.pnpm-store/
|
|
6
|
+
|
|
7
|
+
# TypeScript build output
|
|
8
|
+
ts/packages/*/dist/
|
|
9
|
+
ts/packages/*/.tsbuildinfo
|
|
10
|
+
ts/packages/*/lib/
|
|
11
|
+
tests/interop/drivers/ts/dist/
|
|
12
|
+
tests/interop/drivers/ts/.tsbuildinfo
|
|
13
|
+
tests/interop/lib/dist/
|
|
14
|
+
tests/interop/lib/.tsbuildinfo
|
|
15
|
+
|
|
16
|
+
# Python
|
|
17
|
+
__pycache__/
|
|
18
|
+
*.pyc
|
|
19
|
+
.pytest_cache/
|
|
20
|
+
.ruff_cache/
|
|
21
|
+
.venv/
|
|
22
|
+
.uv-cache/
|
|
23
|
+
py/packages/*/dist/
|
|
24
|
+
py/packages/*/build/
|
|
25
|
+
py/packages/*/*.egg-info/
|
|
26
|
+
|
|
27
|
+
# Codegen artifacts
|
|
28
|
+
tests/interop/generated/
|
|
29
|
+
tests/interop/.tmp/
|
|
30
|
+
|
|
31
|
+
# Docker
|
|
32
|
+
tests/interop/.redis-data/
|
|
33
|
+
|
|
34
|
+
# IDE
|
|
35
|
+
.vscode/
|
|
36
|
+
.idea/
|
|
37
|
+
*.swp
|
|
38
|
+
.DS_Store
|
|
39
|
+
|
|
40
|
+
# Claude Code per-project state (local settings, worktrees)
|
|
41
|
+
.claude/
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
|
203
|
+
Copyright 2026 Kristof Csillag
|
|
204
|
+
|
|
205
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
206
|
+
you may not use this file except in compliance with the License.
|
|
207
|
+
You may obtain a copy of the License at
|
|
208
|
+
|
|
209
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
210
|
+
|
|
211
|
+
Unless required by applicable law or agreed to in writing, software
|
|
212
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
213
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
214
|
+
See the License for the specific language governing permissions and
|
|
215
|
+
limitations under the License.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: clamator-protocol
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Polyglot RPC protocol layer (pre-1.0; API may break in minor versions).
|
|
5
|
+
Project-URL: Homepage, https://github.com/csillag/clamator
|
|
6
|
+
Author: Kristof Csillag
|
|
7
|
+
License: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Requires-Dist: pydantic>=2.5
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# clamator-protocol
|
|
14
|
+
|
|
15
|
+
Pure JSON-RPC 2.0 protocol primitives plus Pydantic-derived envelope types for clamator. **No I/O, ever** — anything that touches a network, filesystem, or process belongs in a transport adapter.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install clamator-protocol
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## When you reach for this
|
|
24
|
+
|
|
25
|
+
- Defining a `Contract` (in tests, in custom tooling).
|
|
26
|
+
- Building a custom transport adapter that needs the wire-envelope models, the `Transport` and `Dispatcher` interfaces, or the reserved JSON-RPC error codes.
|
|
27
|
+
|
|
28
|
+
If you only consume generated clients and servers, you don't import this package directly — your transport package (`clamator-over-memory`, `clamator-over-redis`) re-exports the few symbols you need.
|
|
29
|
+
|
|
30
|
+
## Defining a contract
|
|
31
|
+
|
|
32
|
+
The Python counterpart of a Zod contract is a `Contract` with `MethodEntry` rows that bind Pydantic models to handler attribute names:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
arith = Contract(
|
|
36
|
+
service="arith",
|
|
37
|
+
methods={
|
|
38
|
+
"add": MethodEntry(params_model=AddP, result_model=AddR, handler_attr="add"),
|
|
39
|
+
"ping": MethodEntry(params_model=PingP, result_model=None, handler_attr="ping"),
|
|
40
|
+
},
|
|
41
|
+
)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
(Verbatim from `py/packages/over-memory/tests/test_loopback.py`.)
|
|
45
|
+
|
|
46
|
+
When `clamator-protocol` is consumed alongside generated wrappers from `@clamator/codegen`, the `Contract` and `MethodEntry` values are produced by codegen — the snippet above is what direct authors of test contracts or custom tooling write.
|
|
47
|
+
|
|
48
|
+
## Key exports
|
|
49
|
+
|
|
50
|
+
- `Contract`, `MethodEntry` — declare a service's methods and notifications with Pydantic models for params and results.
|
|
51
|
+
- `RpcError` — the error type you raise from a handler to surface a structured JSON-RPC error to the caller.
|
|
52
|
+
- `ClamatorProtocolError`, `ClamatorTransportError` — distinguishable error classes for protocol-level vs. transport-level failures.
|
|
53
|
+
- `Transport`, `Dispatcher` — interfaces a custom transport adapter implements.
|
|
54
|
+
|
|
55
|
+
## Codegen workflow
|
|
56
|
+
|
|
57
|
+
clamator's codegen tool is published to npm (`@clamator/codegen`) regardless of which language consumes the output. Python users run the TS-side tool against their Zod contract source and consume the emitted Python wrappers from their package. See [`@clamator/codegen`](https://www.npmjs.com/package/@clamator/codegen) for the CLI invocation.
|
|
58
|
+
|
|
59
|
+
## Links
|
|
60
|
+
|
|
61
|
+
- Sibling (TypeScript): [`@clamator/protocol`](https://www.npmjs.com/package/@clamator/protocol)
|
|
62
|
+
- Codegen: [`@clamator/codegen`](https://www.npmjs.com/package/@clamator/codegen) (run from TS side; consume the generated Python output)
|
|
63
|
+
- Design spec: [`docs/2026-05-07-clamator-design.md`](../../../docs/2026-05-07-clamator-design.md)
|
|
64
|
+
- Agent rules: [`AGENTS.md`](./AGENTS.md)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# clamator-protocol
|
|
2
|
+
|
|
3
|
+
Pure JSON-RPC 2.0 protocol primitives plus Pydantic-derived envelope types for clamator. **No I/O, ever** — anything that touches a network, filesystem, or process belongs in a transport adapter.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install clamator-protocol
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## When you reach for this
|
|
12
|
+
|
|
13
|
+
- Defining a `Contract` (in tests, in custom tooling).
|
|
14
|
+
- Building a custom transport adapter that needs the wire-envelope models, the `Transport` and `Dispatcher` interfaces, or the reserved JSON-RPC error codes.
|
|
15
|
+
|
|
16
|
+
If you only consume generated clients and servers, you don't import this package directly — your transport package (`clamator-over-memory`, `clamator-over-redis`) re-exports the few symbols you need.
|
|
17
|
+
|
|
18
|
+
## Defining a contract
|
|
19
|
+
|
|
20
|
+
The Python counterpart of a Zod contract is a `Contract` with `MethodEntry` rows that bind Pydantic models to handler attribute names:
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
arith = Contract(
|
|
24
|
+
service="arith",
|
|
25
|
+
methods={
|
|
26
|
+
"add": MethodEntry(params_model=AddP, result_model=AddR, handler_attr="add"),
|
|
27
|
+
"ping": MethodEntry(params_model=PingP, result_model=None, handler_attr="ping"),
|
|
28
|
+
},
|
|
29
|
+
)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
(Verbatim from `py/packages/over-memory/tests/test_loopback.py`.)
|
|
33
|
+
|
|
34
|
+
When `clamator-protocol` is consumed alongside generated wrappers from `@clamator/codegen`, the `Contract` and `MethodEntry` values are produced by codegen — the snippet above is what direct authors of test contracts or custom tooling write.
|
|
35
|
+
|
|
36
|
+
## Key exports
|
|
37
|
+
|
|
38
|
+
- `Contract`, `MethodEntry` — declare a service's methods and notifications with Pydantic models for params and results.
|
|
39
|
+
- `RpcError` — the error type you raise from a handler to surface a structured JSON-RPC error to the caller.
|
|
40
|
+
- `ClamatorProtocolError`, `ClamatorTransportError` — distinguishable error classes for protocol-level vs. transport-level failures.
|
|
41
|
+
- `Transport`, `Dispatcher` — interfaces a custom transport adapter implements.
|
|
42
|
+
|
|
43
|
+
## Codegen workflow
|
|
44
|
+
|
|
45
|
+
clamator's codegen tool is published to npm (`@clamator/codegen`) regardless of which language consumes the output. Python users run the TS-side tool against their Zod contract source and consume the emitted Python wrappers from their package. See [`@clamator/codegen`](https://www.npmjs.com/package/@clamator/codegen) for the CLI invocation.
|
|
46
|
+
|
|
47
|
+
## Links
|
|
48
|
+
|
|
49
|
+
- Sibling (TypeScript): [`@clamator/protocol`](https://www.npmjs.com/package/@clamator/protocol)
|
|
50
|
+
- Codegen: [`@clamator/codegen`](https://www.npmjs.com/package/@clamator/codegen) (run from TS side; consume the generated Python output)
|
|
51
|
+
- Design spec: [`docs/2026-05-07-clamator-design.md`](../../../docs/2026-05-07-clamator-design.md)
|
|
52
|
+
- Agent rules: [`AGENTS.md`](./AGENTS.md)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "clamator-protocol"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Polyglot RPC protocol layer (pre-1.0; API may break in minor versions)."
|
|
5
|
+
license = { text = "Apache-2.0" }
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
requires-python = ">=3.11"
|
|
8
|
+
authors = [{ name = "Kristof Csillag" }]
|
|
9
|
+
dependencies = ["pydantic>=2.5"]
|
|
10
|
+
|
|
11
|
+
[project.urls]
|
|
12
|
+
Homepage = "https://github.com/csillag/clamator"
|
|
13
|
+
|
|
14
|
+
[build-system]
|
|
15
|
+
requires = ["hatchling"]
|
|
16
|
+
build-backend = "hatchling.build"
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["src/clamator_protocol"]
|
|
20
|
+
include = ["LICENSE"]
|
|
21
|
+
|
|
22
|
+
[tool.hatch.build.targets.sdist]
|
|
23
|
+
include = ["src", "README.md", "pyproject.toml", "LICENSE"]
|
|
24
|
+
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""clamator-protocol: pure protocol layer for clamator polyglot RPC."""
|
|
2
|
+
|
|
3
|
+
from .contract import Contract, MethodEntry
|
|
4
|
+
from .envelope import (
|
|
5
|
+
Envelope, RequestEnvelope, NotificationEnvelope,
|
|
6
|
+
SuccessResponseEnvelope, ErrorResponseEnvelope,
|
|
7
|
+
EnvelopeKind, RpcId, SERVICE_RE, METHOD_RE,
|
|
8
|
+
parse_envelope, build_request, build_notification,
|
|
9
|
+
build_success_response, build_error_response,
|
|
10
|
+
)
|
|
11
|
+
from .error import (
|
|
12
|
+
RpcError, ClamatorProtocolError, ClamatorTransportError, exception_to_error_data,
|
|
13
|
+
)
|
|
14
|
+
from .transport import Transport, Dispatcher
|
|
15
|
+
from .server_core import RpcServerCore
|
|
16
|
+
from .client_core import RpcClientCore, ClamatorClient
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"Contract", "MethodEntry",
|
|
20
|
+
"Envelope", "RequestEnvelope", "NotificationEnvelope",
|
|
21
|
+
"SuccessResponseEnvelope", "ErrorResponseEnvelope",
|
|
22
|
+
"EnvelopeKind", "RpcId", "SERVICE_RE", "METHOD_RE",
|
|
23
|
+
"parse_envelope", "build_request", "build_notification",
|
|
24
|
+
"build_success_response", "build_error_response",
|
|
25
|
+
"RpcError", "ClamatorProtocolError", "ClamatorTransportError",
|
|
26
|
+
"exception_to_error_data",
|
|
27
|
+
"Transport", "Dispatcher",
|
|
28
|
+
"RpcServerCore", "RpcClientCore", "ClamatorClient",
|
|
29
|
+
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import uuid
|
|
3
|
+
from typing import Any, Protocol
|
|
4
|
+
|
|
5
|
+
from .envelope import (
|
|
6
|
+
SERVICE_RE, METHOD_RE, parse_envelope,
|
|
7
|
+
SuccessResponseEnvelope, ErrorResponseEnvelope,
|
|
8
|
+
build_request, build_notification,
|
|
9
|
+
)
|
|
10
|
+
from .error import RpcError, ClamatorProtocolError
|
|
11
|
+
from .transport import Transport
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ClamatorClient(Protocol):
|
|
15
|
+
async def call(self, service: str, method: str, params: Any) -> Any: ...
|
|
16
|
+
async def notify(self, service: str, method: str, params: Any) -> None: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RpcClientCore:
|
|
20
|
+
def __init__(self, transport: Transport, *, default_timeout_ms: int = 30_000) -> None:
|
|
21
|
+
self._transport = transport
|
|
22
|
+
self._default_timeout = default_timeout_ms / 1000
|
|
23
|
+
self._state = "idle"
|
|
24
|
+
|
|
25
|
+
async def call(self, service: str, method: str, params: Any) -> Any:
|
|
26
|
+
if not SERVICE_RE.match(service):
|
|
27
|
+
raise ValueError(f"invalid service \"{service}\"")
|
|
28
|
+
if not METHOD_RE.match(method):
|
|
29
|
+
raise ValueError(f"invalid method \"{method}\"")
|
|
30
|
+
rpc_id = str(uuid.uuid4())
|
|
31
|
+
env = build_request(f"{service}.{method}", params, rpc_id)
|
|
32
|
+
reply = await self._transport.send(env, timeout=self._default_timeout)
|
|
33
|
+
try:
|
|
34
|
+
parsed = parse_envelope(reply)
|
|
35
|
+
except ValueError as e:
|
|
36
|
+
raise ClamatorProtocolError(f"invalid response envelope: {e}") from e
|
|
37
|
+
if isinstance(parsed, SuccessResponseEnvelope):
|
|
38
|
+
return parsed.result
|
|
39
|
+
if isinstance(parsed, ErrorResponseEnvelope):
|
|
40
|
+
raise RpcError(parsed.error["code"], parsed.error["message"], parsed.error.get("data"))
|
|
41
|
+
raise ClamatorProtocolError(f"unexpected response kind: {parsed.kind}")
|
|
42
|
+
|
|
43
|
+
async def notify(self, service: str, method: str, params: Any) -> None:
|
|
44
|
+
if not SERVICE_RE.match(service):
|
|
45
|
+
raise ValueError(f"invalid service \"{service}\"")
|
|
46
|
+
if not METHOD_RE.match(method):
|
|
47
|
+
raise ValueError(f"invalid method \"{method}\"")
|
|
48
|
+
await self._transport.notify(build_notification(f"{service}.{method}", params))
|
|
49
|
+
|
|
50
|
+
async def start(self) -> None:
|
|
51
|
+
if self._state == "stopped":
|
|
52
|
+
raise RuntimeError("client has been stopped")
|
|
53
|
+
if self._state == "started":
|
|
54
|
+
return
|
|
55
|
+
await self._transport.start()
|
|
56
|
+
self._state = "started"
|
|
57
|
+
|
|
58
|
+
async def stop(self) -> None:
|
|
59
|
+
if self._state != "started":
|
|
60
|
+
self._state = "stopped"
|
|
61
|
+
return
|
|
62
|
+
await self._transport.stop()
|
|
63
|
+
self._state = "stopped"
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import Type
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class MethodEntry:
|
|
10
|
+
"""Runtime descriptor for a single method on a generated contract."""
|
|
11
|
+
params_model: Type[BaseModel]
|
|
12
|
+
result_model: Type[BaseModel] | None # None for notifications
|
|
13
|
+
handler_attr: str # attribute on the service-instance to invoke (snake_case)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Contract:
|
|
18
|
+
"""Runtime descriptor for a service contract. Codegen emits one of these per service."""
|
|
19
|
+
service: str
|
|
20
|
+
methods: dict[str, MethodEntry] = field(default_factory=dict)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import re
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Any, Union
|
|
6
|
+
|
|
7
|
+
SERVICE_RE = re.compile(r"^[a-z][a-z0-9-]*$")
|
|
8
|
+
METHOD_RE = re.compile(r"^[a-z][a-zA-Z0-9-]*$")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EnvelopeKind(Enum):
|
|
12
|
+
REQUEST = "request"
|
|
13
|
+
NOTIFICATION = "notification"
|
|
14
|
+
SUCCESS_RESPONSE = "success"
|
|
15
|
+
ERROR_RESPONSE = "error"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
RpcId = Union[str, int]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class RequestEnvelope:
|
|
23
|
+
service: str
|
|
24
|
+
method: str
|
|
25
|
+
full_method: str
|
|
26
|
+
params: Any
|
|
27
|
+
id: RpcId
|
|
28
|
+
raw: dict[str, Any] = field(repr=False)
|
|
29
|
+
kind: EnvelopeKind = EnvelopeKind.REQUEST
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class NotificationEnvelope:
|
|
34
|
+
service: str
|
|
35
|
+
method: str
|
|
36
|
+
full_method: str
|
|
37
|
+
params: Any
|
|
38
|
+
raw: dict[str, Any] = field(repr=False)
|
|
39
|
+
kind: EnvelopeKind = EnvelopeKind.NOTIFICATION
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class SuccessResponseEnvelope:
|
|
44
|
+
id: RpcId
|
|
45
|
+
result: Any
|
|
46
|
+
kind: EnvelopeKind = EnvelopeKind.SUCCESS_RESPONSE
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class ErrorResponseEnvelope:
|
|
51
|
+
id: RpcId | None
|
|
52
|
+
error: dict[str, Any]
|
|
53
|
+
kind: EnvelopeKind = EnvelopeKind.ERROR_RESPONSE
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
Envelope = Union[
|
|
57
|
+
RequestEnvelope, NotificationEnvelope, SuccessResponseEnvelope, ErrorResponseEnvelope
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _invalid(msg: str) -> ValueError:
|
|
62
|
+
return ValueError(f"-32600 Invalid Request: {msg}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_envelope(value: Any) -> Envelope:
|
|
66
|
+
if isinstance(value, list):
|
|
67
|
+
raise _invalid("batch requests not supported")
|
|
68
|
+
if not isinstance(value, dict):
|
|
69
|
+
raise _invalid("not an object")
|
|
70
|
+
if value.get("jsonrpc") != "2.0":
|
|
71
|
+
raise _invalid('jsonrpc must equal "2.0"')
|
|
72
|
+
|
|
73
|
+
has_method = isinstance(value.get("method"), str)
|
|
74
|
+
has_result = "result" in value
|
|
75
|
+
has_error = "error" in value
|
|
76
|
+
has_id = "id" in value and value["id"] is not None
|
|
77
|
+
|
|
78
|
+
if has_method:
|
|
79
|
+
full_method = value["method"]
|
|
80
|
+
if "." not in full_method:
|
|
81
|
+
raise _invalid('method must be "<service>.<method>"')
|
|
82
|
+
service, _, method = full_method.partition(".")
|
|
83
|
+
if not service or not method:
|
|
84
|
+
raise _invalid('method must be "<service>.<method>"')
|
|
85
|
+
if not SERVICE_RE.match(service):
|
|
86
|
+
raise _invalid("invalid service segment")
|
|
87
|
+
if not METHOD_RE.match(method):
|
|
88
|
+
raise _invalid("invalid method segment")
|
|
89
|
+
if has_id:
|
|
90
|
+
rpc_id = value["id"]
|
|
91
|
+
if isinstance(rpc_id, bool) or not isinstance(rpc_id, (str, int)):
|
|
92
|
+
raise _invalid("id must be string or number")
|
|
93
|
+
return RequestEnvelope(
|
|
94
|
+
service=service, method=method, full_method=full_method,
|
|
95
|
+
params=value.get("params", {}), id=rpc_id, raw=value,
|
|
96
|
+
)
|
|
97
|
+
return NotificationEnvelope(
|
|
98
|
+
service=service, method=method, full_method=full_method,
|
|
99
|
+
params=value.get("params", {}), raw=value,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
if has_result and not has_error:
|
|
103
|
+
if not has_id:
|
|
104
|
+
raise _invalid("response must have id")
|
|
105
|
+
return SuccessResponseEnvelope(id=value["id"], result=value["result"])
|
|
106
|
+
|
|
107
|
+
if has_error and not has_result:
|
|
108
|
+
err = value.get("error")
|
|
109
|
+
if not isinstance(err, dict) or not isinstance(err.get("code"), int) or not isinstance(err.get("message"), str):
|
|
110
|
+
raise _invalid("error must have numeric code + string message")
|
|
111
|
+
rpc_id = value["id"] if has_id else None
|
|
112
|
+
return ErrorResponseEnvelope(
|
|
113
|
+
id=rpc_id,
|
|
114
|
+
error={"code": err["code"], "message": err["message"], "data": err.get("data")},
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
raise _invalid("envelope must be request, notification, or response")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def build_request(full_method: str, params: Any, rpc_id: RpcId) -> dict[str, Any]:
|
|
121
|
+
return {"jsonrpc": "2.0", "method": full_method, "params": params, "id": rpc_id}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def build_notification(full_method: str, params: Any) -> dict[str, Any]:
|
|
125
|
+
return {"jsonrpc": "2.0", "method": full_method, "params": params}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build_success_response(rpc_id: RpcId, result: Any) -> dict[str, Any]:
|
|
129
|
+
return {"jsonrpc": "2.0", "id": rpc_id, "result": result}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def build_error_response(rpc_id: RpcId | None, code: int, message: str, data: Any = None) -> dict[str, Any]:
|
|
133
|
+
return {"jsonrpc": "2.0", "id": rpc_id, "error": {"code": code, "message": message, "data": data}}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class RpcError(Exception):
|
|
6
|
+
"""Application-defined JSON-RPC error. Throw from a handler to produce an error response."""
|
|
7
|
+
|
|
8
|
+
def __init__(self, code: int, message: str, data: Any = None) -> None:
|
|
9
|
+
super().__init__(message)
|
|
10
|
+
self.code = code
|
|
11
|
+
self.message = message
|
|
12
|
+
self.data = data
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ClamatorProtocolError(Exception):
|
|
16
|
+
"""Validation failure or malformed envelope."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ClamatorTransportError(Exception):
|
|
20
|
+
"""Transport-level failure (connection lost, timeout, etc.)."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, message: str, *, cause: BaseException | None = None) -> None:
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
if cause is not None:
|
|
25
|
+
self.__cause__ = cause
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_SERIALIZABLE = (str, int, float, bool, type(None))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def exception_to_error_data(err: BaseException) -> dict[str, Any]:
|
|
32
|
+
out: dict[str, Any] = {"name": type(err).__name__, "message": str(err)}
|
|
33
|
+
for k, v in vars(err).items():
|
|
34
|
+
if k in {"args", "__cause__", "__context__", "__traceback__"}:
|
|
35
|
+
continue
|
|
36
|
+
if isinstance(v, _SERIALIZABLE):
|
|
37
|
+
out[k] = v
|
|
38
|
+
elif isinstance(v, list) and all(isinstance(x, _SERIALIZABLE) for x in v):
|
|
39
|
+
out[k] = v
|
|
40
|
+
return out
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import asyncio
|
|
3
|
+
import time
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pydantic import ValidationError
|
|
8
|
+
|
|
9
|
+
from .contract import Contract
|
|
10
|
+
from .envelope import (
|
|
11
|
+
Envelope, RequestEnvelope, NotificationEnvelope,
|
|
12
|
+
build_success_response, build_error_response,
|
|
13
|
+
)
|
|
14
|
+
from .error import RpcError, exception_to_error_data
|
|
15
|
+
from .transport import Transport, Dispatcher
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class _ServiceEntry:
|
|
20
|
+
contract: Contract
|
|
21
|
+
handler_instance: Any
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RpcServerCore:
|
|
25
|
+
def __init__(self, transport: Transport) -> None:
|
|
26
|
+
self._transport = transport
|
|
27
|
+
self._services: dict[str, _ServiceEntry] = {}
|
|
28
|
+
self._state: str = "idle"
|
|
29
|
+
self._inflight: set[asyncio.Task[Any]] = set()
|
|
30
|
+
|
|
31
|
+
def register_service(self, contract: Contract, instance: Any) -> None:
|
|
32
|
+
if contract.service in self._services:
|
|
33
|
+
raise ValueError(f'service "{contract.service}" already registered on this server')
|
|
34
|
+
self._services[contract.service] = _ServiceEntry(contract=contract, handler_instance=instance)
|
|
35
|
+
|
|
36
|
+
def _dispatcher(self, service_name: str) -> Dispatcher:
|
|
37
|
+
async def dispatch(env: Envelope) -> dict[str, Any] | None:
|
|
38
|
+
entry = self._services.get(service_name)
|
|
39
|
+
if not isinstance(env, (RequestEnvelope, NotificationEnvelope)):
|
|
40
|
+
return None
|
|
41
|
+
is_notification = isinstance(env, NotificationEnvelope)
|
|
42
|
+
rpc_id = None if is_notification else env.id
|
|
43
|
+
if entry is None:
|
|
44
|
+
return None if is_notification else build_error_response(rpc_id, -32601, "Method not found")
|
|
45
|
+
method_entry = entry.contract.methods.get(env.method)
|
|
46
|
+
if method_entry is None:
|
|
47
|
+
return None if is_notification else build_error_response(rpc_id, -32601, "Method not found")
|
|
48
|
+
try:
|
|
49
|
+
params = method_entry.params_model.model_validate(env.params)
|
|
50
|
+
except ValidationError as e:
|
|
51
|
+
if is_notification:
|
|
52
|
+
return None
|
|
53
|
+
return build_error_response(rpc_id, -32602, "Invalid params", {"errors": e.errors()})
|
|
54
|
+
handler = getattr(entry.handler_instance, method_entry.handler_attr, None)
|
|
55
|
+
if handler is None:
|
|
56
|
+
return None if is_notification else build_error_response(rpc_id, -32601, "Method not found")
|
|
57
|
+
|
|
58
|
+
task = asyncio.create_task(handler(params))
|
|
59
|
+
self._inflight.add(task)
|
|
60
|
+
try:
|
|
61
|
+
result = await task
|
|
62
|
+
except RpcError as e:
|
|
63
|
+
if is_notification:
|
|
64
|
+
return None
|
|
65
|
+
return build_error_response(rpc_id, e.code, e.message, e.data)
|
|
66
|
+
except Exception as e: # noqa: BLE001
|
|
67
|
+
if is_notification:
|
|
68
|
+
return None
|
|
69
|
+
return build_error_response(rpc_id, -32603, "Internal error", exception_to_error_data(e))
|
|
70
|
+
finally:
|
|
71
|
+
self._inflight.discard(task)
|
|
72
|
+
|
|
73
|
+
if is_notification or method_entry.result_model is None:
|
|
74
|
+
return None
|
|
75
|
+
try:
|
|
76
|
+
validated = method_entry.result_model.model_validate(result)
|
|
77
|
+
except ValidationError as e:
|
|
78
|
+
return build_error_response(rpc_id, -32603, "Result validation failed", {"errors": e.errors()})
|
|
79
|
+
return build_success_response(rpc_id, validated.model_dump(by_alias=True))
|
|
80
|
+
return dispatch
|
|
81
|
+
|
|
82
|
+
async def start(self) -> None:
|
|
83
|
+
if self._state == "started":
|
|
84
|
+
return
|
|
85
|
+
if self._state == "stopped":
|
|
86
|
+
raise RuntimeError("server has been stopped")
|
|
87
|
+
for name in self._services:
|
|
88
|
+
await self._transport.register_service(name, self._dispatcher(name))
|
|
89
|
+
await self._transport.start()
|
|
90
|
+
self._state = "started"
|
|
91
|
+
|
|
92
|
+
async def stop(self, *, grace_ms: int = 5000) -> None:
|
|
93
|
+
if self._state != "started":
|
|
94
|
+
self._state = "stopped"
|
|
95
|
+
return
|
|
96
|
+
deadline = time.monotonic() + grace_ms / 1000
|
|
97
|
+
while self._inflight and time.monotonic() < deadline:
|
|
98
|
+
await asyncio.wait(self._inflight, timeout=0.05, return_when=asyncio.ALL_COMPLETED)
|
|
99
|
+
await self._transport.stop()
|
|
100
|
+
self._state = "stopped"
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Any, Awaitable, Callable, Protocol, runtime_checkable
|
|
3
|
+
|
|
4
|
+
from .envelope import Envelope
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
Dispatcher = Callable[[Envelope], Awaitable[dict[str, Any] | None]]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@runtime_checkable
|
|
11
|
+
class Transport(Protocol):
|
|
12
|
+
async def register_service(self, name: str, dispatch: Dispatcher) -> None: ...
|
|
13
|
+
async def send(self, env: dict[str, Any], *, timeout: float) -> dict[str, Any]: ...
|
|
14
|
+
async def notify(self, env: dict[str, Any]) -> None: ...
|
|
15
|
+
async def start(self) -> None: ...
|
|
16
|
+
async def stop(self) -> None: ...
|