bazaar-contrib-sidecar 0.3.0rc1__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.
- bazaar_contrib_sidecar-0.3.0rc1/LICENSE +202 -0
- bazaar_contrib_sidecar-0.3.0rc1/PKG-INFO +47 -0
- bazaar_contrib_sidecar-0.3.0rc1/README.md +36 -0
- bazaar_contrib_sidecar-0.3.0rc1/pyproject.toml +29 -0
- bazaar_contrib_sidecar-0.3.0rc1/pyproject.toml.orig +29 -0
- bazaar_contrib_sidecar-0.3.0rc1/src/bazaar_contrib_sidecar/__init__.py +35 -0
- bazaar_contrib_sidecar-0.3.0rc1/src/bazaar_contrib_sidecar/contracts.py +26 -0
- bazaar_contrib_sidecar-0.3.0rc1/src/bazaar_contrib_sidecar/handlers.py +124 -0
- bazaar_contrib_sidecar-0.3.0rc1/src/bazaar_contrib_sidecar/py.typed +0 -0
- bazaar_contrib_sidecar-0.3.0rc1/src/bazaar_contrib_sidecar/remote.py +104 -0
- bazaar_contrib_sidecar-0.3.0rc1/src/bazaar_contrib_sidecar/streams.py +34 -0
- bazaar_contrib_sidecar-0.3.0rc1/src/bazaar_contrib_sidecar/wire.py +134 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bazaar-contrib-sidecar
|
|
3
|
+
Version: 0.3.0rc1
|
|
4
|
+
Summary: Transport-independent sidecar contracts and Context handlers
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: bazaar-core~=0.3.0rc1
|
|
8
|
+
Requires-Python: >=3.15
|
|
9
|
+
Project-URL: Repository, https://github.com/yuchanns/bazaar-compute-node
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# bazaar-contrib-sidecar
|
|
13
|
+
|
|
14
|
+
Enable local calls to node services. Select the transport for your platform:
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
bcn contrib add sidecar --enable
|
|
18
|
+
bcn contrib add sidecar-unix --enable
|
|
19
|
+
# On Windows, use: bcn contrib add sidecar-windows --enable
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The corresponding entries in `config.toml`:
|
|
23
|
+
|
|
24
|
+
```toml
|
|
25
|
+
version = "5"
|
|
26
|
+
|
|
27
|
+
[[contribs]]
|
|
28
|
+
package = "bazaar-contrib-sidecar~=0.3.0rc1"
|
|
29
|
+
[[contribs.enabled]]
|
|
30
|
+
entry = "sidecar"
|
|
31
|
+
|
|
32
|
+
[[contribs]]
|
|
33
|
+
package = "bazaar-contrib-sidecar-unix~=0.3.0rc1; sys_platform != 'win32'"
|
|
34
|
+
[[contribs.enabled]]
|
|
35
|
+
entry = "sidecar-unix"
|
|
36
|
+
[contribs.enabled.config]
|
|
37
|
+
timeout = 30
|
|
38
|
+
|
|
39
|
+
[[contribs]]
|
|
40
|
+
package = "bazaar-contrib-sidecar-windows~=0.3.0rc1; sys_platform == 'win32'"
|
|
41
|
+
[[contribs.enabled]]
|
|
42
|
+
entry = "sidecar-windows"
|
|
43
|
+
[contribs.enabled.config]
|
|
44
|
+
timeout = 30
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Consumers accept `CLIENT`; handlers are served while the owning contrib is running.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# bazaar-contrib-sidecar
|
|
2
|
+
|
|
3
|
+
Enable local calls to node services. Select the transport for your platform:
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
bcn contrib add sidecar --enable
|
|
7
|
+
bcn contrib add sidecar-unix --enable
|
|
8
|
+
# On Windows, use: bcn contrib add sidecar-windows --enable
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The corresponding entries in `config.toml`:
|
|
12
|
+
|
|
13
|
+
```toml
|
|
14
|
+
version = "5"
|
|
15
|
+
|
|
16
|
+
[[contribs]]
|
|
17
|
+
package = "bazaar-contrib-sidecar~=0.3.0rc1"
|
|
18
|
+
[[contribs.enabled]]
|
|
19
|
+
entry = "sidecar"
|
|
20
|
+
|
|
21
|
+
[[contribs]]
|
|
22
|
+
package = "bazaar-contrib-sidecar-unix~=0.3.0rc1; sys_platform != 'win32'"
|
|
23
|
+
[[contribs.enabled]]
|
|
24
|
+
entry = "sidecar-unix"
|
|
25
|
+
[contribs.enabled.config]
|
|
26
|
+
timeout = 30
|
|
27
|
+
|
|
28
|
+
[[contribs]]
|
|
29
|
+
package = "bazaar-contrib-sidecar-windows~=0.3.0rc1; sys_platform == 'win32'"
|
|
30
|
+
[[contribs.enabled]]
|
|
31
|
+
entry = "sidecar-windows"
|
|
32
|
+
[contribs.enabled.config]
|
|
33
|
+
timeout = 30
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Consumers accept `CLIENT`; handlers are served while the owning contrib is running.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "bazaar-contrib-sidecar"
|
|
3
|
+
version = "0.3.0rc1"
|
|
4
|
+
description = "Transport-independent sidecar contracts and Context handlers"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.15"
|
|
9
|
+
dependencies = ["bazaar-core~=0.3.0rc1"]
|
|
10
|
+
|
|
11
|
+
[project.entry-points."bazaar_compute_node.contribs"]
|
|
12
|
+
sidecar = "bazaar_contrib_sidecar:sidecar"
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Repository = "https://github.com/yuchanns/bazaar-compute-node"
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["uv_build>=0.13.0,<0.14.0"]
|
|
19
|
+
build-backend = "uv_build"
|
|
20
|
+
|
|
21
|
+
[tool.bcn.ci]
|
|
22
|
+
skip = true
|
|
23
|
+
|
|
24
|
+
[tool.pyright]
|
|
25
|
+
extends = "../../pyrightconfig.json"
|
|
26
|
+
include = ["src"]
|
|
27
|
+
|
|
28
|
+
[tool.ruff]
|
|
29
|
+
extend = "../../pyproject.toml"
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "bazaar-contrib-sidecar"
|
|
3
|
+
version = "0.3.0rc1"
|
|
4
|
+
description = "Transport-independent sidecar contracts and Context handlers"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.15"
|
|
9
|
+
dependencies = ["bazaar-core~=0.3.0rc1"]
|
|
10
|
+
|
|
11
|
+
[project.entry-points."bazaar_compute_node.contribs"]
|
|
12
|
+
sidecar = "bazaar_contrib_sidecar:sidecar"
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Repository = "https://github.com/yuchanns/bazaar-compute-node"
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["uv_build>=0.13.0,<0.14.0"]
|
|
19
|
+
build-backend = "uv_build"
|
|
20
|
+
|
|
21
|
+
[tool.bcn.ci]
|
|
22
|
+
skip = true
|
|
23
|
+
|
|
24
|
+
[tool.pyright]
|
|
25
|
+
extends = "../../pyrightconfig.json"
|
|
26
|
+
include = ["src"]
|
|
27
|
+
|
|
28
|
+
[tool.ruff]
|
|
29
|
+
extend = "../../pyproject.toml"
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Sidecar contracts and an ordinary plugin exposing its Context handlers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
|
|
7
|
+
from bazaar_core import Context, Contrib
|
|
8
|
+
|
|
9
|
+
from .contracts import CLIENT, SERVER, Handler, Server, Sessions
|
|
10
|
+
lazy from .handlers import Session
|
|
11
|
+
lazy from .remote import Client, Remote, RemoteError
|
|
12
|
+
lazy from .wire import Construct, Symbol
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"CLIENT",
|
|
16
|
+
"SERVER",
|
|
17
|
+
"Client",
|
|
18
|
+
"Construct",
|
|
19
|
+
"Handler",
|
|
20
|
+
"Remote",
|
|
21
|
+
"RemoteError",
|
|
22
|
+
"Server",
|
|
23
|
+
"Sessions",
|
|
24
|
+
"Symbol",
|
|
25
|
+
"sidecar",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@asynccontextmanager
|
|
30
|
+
async def lifespan(ctx: Context):
|
|
31
|
+
async with ctx.accept(SERVER).serve(lambda: Session(ctx)):
|
|
32
|
+
yield
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
sidecar = Contrib(accepts=[SERVER], lifespan=lifespan)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Transport-independent server sessions and the offered client service."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from contextlib import AbstractAsyncContextManager
|
|
7
|
+
from typing import Protocol
|
|
8
|
+
|
|
9
|
+
from bazaar_core import ServiceKey
|
|
10
|
+
|
|
11
|
+
from .remote import Client
|
|
12
|
+
from .wire import Failure, Request, Result
|
|
13
|
+
|
|
14
|
+
type Response = Result | Failure
|
|
15
|
+
type Handler = Callable[[Request], Awaitable[Response]]
|
|
16
|
+
type Sessions = Callable[[], AbstractAsyncContextManager[Handler]]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Server(Protocol):
|
|
20
|
+
"""Bind session handlers for the duration of their owning plugin lifespan."""
|
|
21
|
+
|
|
22
|
+
def serve(self, sessions: Sessions) -> AbstractAsyncContextManager[None]: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
SERVER = ServiceKey[Server]("sidecar.server")
|
|
26
|
+
CLIENT = ServiceKey[Client]("sidecar.client")
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Shared handlers for an instance Context and the objects it returns."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import AsyncExitStack, asynccontextmanager
|
|
6
|
+
lazy import asyncio
|
|
7
|
+
lazy import inspect
|
|
8
|
+
lazy from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
from bazaar_core import Composition, Context, Contrib, ContribEntry, ServiceKey
|
|
11
|
+
|
|
12
|
+
from .wire import Failure, Reference, Request, Result, decode, encode
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class _Caller:
|
|
16
|
+
"""Forward framework operations with connection-owned service consumers."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, ctx: Context, resources: AsyncExitStack) -> None:
|
|
19
|
+
self._ctx = ctx
|
|
20
|
+
self._resources = resources
|
|
21
|
+
|
|
22
|
+
def __getattr__(self, name: str) -> Any:
|
|
23
|
+
return getattr(self._ctx, name)
|
|
24
|
+
|
|
25
|
+
async def accept[T](self, key: ServiceKey[T]) -> T:
|
|
26
|
+
service: T | None = None
|
|
27
|
+
|
|
28
|
+
@asynccontextmanager
|
|
29
|
+
async def lifespan(ctx: Context):
|
|
30
|
+
nonlocal service
|
|
31
|
+
service = ctx.accept(key)
|
|
32
|
+
yield
|
|
33
|
+
|
|
34
|
+
await self._resources.enter_async_context(
|
|
35
|
+
self._ctx.enable(
|
|
36
|
+
Composition(
|
|
37
|
+
entries=[
|
|
38
|
+
ContribEntry(
|
|
39
|
+
name="sidecar-caller",
|
|
40
|
+
definition=Contrib(accepts=[key], lifespan=lifespan),
|
|
41
|
+
)
|
|
42
|
+
]
|
|
43
|
+
)
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
return cast(T, service)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Session:
|
|
50
|
+
"""One caller owns its object table and remotely entered resources."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, ctx: Context) -> None:
|
|
53
|
+
self._resources = AsyncExitStack()
|
|
54
|
+
caller = _Caller(ctx, self._resources)
|
|
55
|
+
self.objects: dict[int, Any] = {0: caller}
|
|
56
|
+
self._identities = {id(caller): 0}
|
|
57
|
+
self._next = 1
|
|
58
|
+
self._entered: dict[int, AsyncExitStack] = {}
|
|
59
|
+
|
|
60
|
+
async def __aenter__(self):
|
|
61
|
+
return self.dispatch
|
|
62
|
+
|
|
63
|
+
async def __aexit__(self, *_: object) -> None:
|
|
64
|
+
try:
|
|
65
|
+
async with AsyncExitStack() as cleanup:
|
|
66
|
+
cleanup.push_async_callback(self._resources.aclose)
|
|
67
|
+
for stack in self._entered.values():
|
|
68
|
+
cleanup.push_async_callback(stack.aclose)
|
|
69
|
+
finally:
|
|
70
|
+
self._entered.clear()
|
|
71
|
+
self.objects.clear()
|
|
72
|
+
self._identities.clear()
|
|
73
|
+
|
|
74
|
+
def reference(self, value: object) -> Reference:
|
|
75
|
+
identity = id(value)
|
|
76
|
+
if identity not in self._identities:
|
|
77
|
+
self._identities[identity] = self._next
|
|
78
|
+
self.objects[self._next] = value
|
|
79
|
+
self._next += 1
|
|
80
|
+
return Reference(id=self._identities[identity])
|
|
81
|
+
|
|
82
|
+
async def dispatch(self, request: Request) -> Result | Failure:
|
|
83
|
+
try:
|
|
84
|
+
target = self.objects[request.target]
|
|
85
|
+
value = None
|
|
86
|
+
match request.operation:
|
|
87
|
+
case "get":
|
|
88
|
+
value = getattr(target, request.method)
|
|
89
|
+
case "call":
|
|
90
|
+
args, kwargs = await asyncio.to_thread(
|
|
91
|
+
lambda: (
|
|
92
|
+
tuple(
|
|
93
|
+
decode(item, lambda ref: self.objects[ref.id])
|
|
94
|
+
for item in request.args
|
|
95
|
+
),
|
|
96
|
+
{
|
|
97
|
+
key: decode(item, lambda ref: self.objects[ref.id])
|
|
98
|
+
for key, item in request.kwargs.items()
|
|
99
|
+
},
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
value = getattr(target, request.method)(*args, **kwargs)
|
|
103
|
+
if inspect.isawaitable(value):
|
|
104
|
+
value = await value
|
|
105
|
+
case "enter":
|
|
106
|
+
if request.target in self._entered:
|
|
107
|
+
raise ValueError("the remote context has already been entered")
|
|
108
|
+
stack = AsyncExitStack()
|
|
109
|
+
value = await stack.enter_async_context(target)
|
|
110
|
+
self._entered[request.target] = stack
|
|
111
|
+
case "exit":
|
|
112
|
+
await self._entered.pop(request.target).aclose()
|
|
113
|
+
case "release":
|
|
114
|
+
if request.target == 0:
|
|
115
|
+
raise ValueError(
|
|
116
|
+
"the root Context belongs to the server lifespan"
|
|
117
|
+
)
|
|
118
|
+
if request.target in self._entered:
|
|
119
|
+
await self._entered.pop(request.target).aclose()
|
|
120
|
+
del self.objects[request.target]
|
|
121
|
+
del self._identities[id(target)]
|
|
122
|
+
return Result(value=encode(value, self.reference))
|
|
123
|
+
except Exception as error: # noqa: BLE001 - Keep one failed call within its own session.
|
|
124
|
+
return Failure(type=type(error).__name__, message=str(error))
|
|
File without changes
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""The offered client and its connection-scoped remote objects."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from enum import Enum, auto
|
|
7
|
+
lazy import asyncio
|
|
8
|
+
lazy from collections.abc import Awaitable, Callable
|
|
9
|
+
lazy from typing import Any
|
|
10
|
+
|
|
11
|
+
from .wire import Failure, Reference, Request, Result, decode, encode
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _State(Enum):
|
|
15
|
+
OPEN = auto()
|
|
16
|
+
CLOSED = auto()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RemoteError(RuntimeError):
|
|
20
|
+
"""A public server method failed; its type and message are preserved."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, type: str, message: str) -> None:
|
|
23
|
+
self.type = type
|
|
24
|
+
super().__init__(f"{type}: {message}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Remote:
|
|
28
|
+
"""A server object retained by one client session."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, client: Client, id: int) -> None:
|
|
31
|
+
self.client = client
|
|
32
|
+
self.id = id
|
|
33
|
+
|
|
34
|
+
async def get(self, name: str) -> Any:
|
|
35
|
+
return await self.client.request(
|
|
36
|
+
Request(operation="get", target=self.id, method=name)
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
async def call(self, name: str, *args: object, **kwargs: object) -> Any:
|
|
40
|
+
return await self.client.request(
|
|
41
|
+
Request(
|
|
42
|
+
operation="call",
|
|
43
|
+
target=self.id,
|
|
44
|
+
method=name,
|
|
45
|
+
args=tuple(encode(value, self.client.reference) for value in args),
|
|
46
|
+
kwargs={
|
|
47
|
+
key: encode(value, self.client.reference)
|
|
48
|
+
for key, value in kwargs.items()
|
|
49
|
+
},
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
@asynccontextmanager
|
|
54
|
+
async def enter(self):
|
|
55
|
+
value = await self.client.request(Request(operation="enter", target=self.id))
|
|
56
|
+
try:
|
|
57
|
+
yield value
|
|
58
|
+
finally:
|
|
59
|
+
if self.client._state is _State.OPEN:
|
|
60
|
+
await self.client.request(Request(operation="exit", target=self.id))
|
|
61
|
+
|
|
62
|
+
async def release(self) -> None:
|
|
63
|
+
await self.client.request(Request(operation="release", target=self.id))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Client:
|
|
67
|
+
"""Expose remote objects over a provider's request and close operations."""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
send: Callable[[Request], Awaitable[Result | Failure]],
|
|
72
|
+
close: Callable[[], Awaitable[None]],
|
|
73
|
+
*,
|
|
74
|
+
timeout: float | None = 30,
|
|
75
|
+
) -> None:
|
|
76
|
+
self.context = Remote(self, 0)
|
|
77
|
+
self.send = send
|
|
78
|
+
self.close = close
|
|
79
|
+
self.timeout = timeout
|
|
80
|
+
self._lock = asyncio.Lock()
|
|
81
|
+
self._state = _State.OPEN
|
|
82
|
+
|
|
83
|
+
def reference(self, value: object) -> Reference:
|
|
84
|
+
if not isinstance(value, Remote) or value.client is not self:
|
|
85
|
+
raise TypeError("use a Symbol, Construct, or object from this connection")
|
|
86
|
+
return Reference(id=value.id)
|
|
87
|
+
|
|
88
|
+
async def request(self, request: Request) -> Any:
|
|
89
|
+
async with self._lock:
|
|
90
|
+
if self._state is _State.CLOSED:
|
|
91
|
+
raise ConnectionError("the sidecar connection has closed")
|
|
92
|
+
try:
|
|
93
|
+
async with asyncio.timeout(self.timeout):
|
|
94
|
+
response = await self.send(request)
|
|
95
|
+
except BaseException:
|
|
96
|
+
await self.aclose()
|
|
97
|
+
raise
|
|
98
|
+
if isinstance(response, Failure):
|
|
99
|
+
raise RemoteError(response.type, response.message)
|
|
100
|
+
return decode(response.value, lambda value: Remote(self, value.id))
|
|
101
|
+
|
|
102
|
+
async def aclose(self) -> None:
|
|
103
|
+
self._state = _State.CLOSED
|
|
104
|
+
await self.close()
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Read complete JSONL frames independently of asyncio's stream buffer limit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
lazy import asyncio
|
|
6
|
+
|
|
7
|
+
_READ_CHUNK_BYTES = 64 * 1024
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class UnlimitedLineReader:
|
|
11
|
+
"""Retain trailing bytes while reading complete lines in fixed-size chunks."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, reader: asyncio.StreamReader) -> None:
|
|
14
|
+
self._reader = reader
|
|
15
|
+
self._buffer = bytearray()
|
|
16
|
+
self._eof = False
|
|
17
|
+
|
|
18
|
+
async def readline(self) -> bytes:
|
|
19
|
+
while True:
|
|
20
|
+
boundary = self._buffer.find(b"\n")
|
|
21
|
+
if boundary >= 0:
|
|
22
|
+
boundary += 1
|
|
23
|
+
line = bytes(self._buffer[:boundary])
|
|
24
|
+
del self._buffer[:boundary]
|
|
25
|
+
return line
|
|
26
|
+
if self._eof:
|
|
27
|
+
line = bytes(self._buffer)
|
|
28
|
+
self._buffer.clear()
|
|
29
|
+
return line
|
|
30
|
+
chunk = await self._reader.read(_READ_CHUNK_BYTES)
|
|
31
|
+
if chunk:
|
|
32
|
+
self._buffer.extend(chunk)
|
|
33
|
+
else:
|
|
34
|
+
self._eof = True
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""JSON values, installed symbols, and connection-owned object references."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Annotated, Any, Literal
|
|
7
|
+
lazy from collections.abc import Callable, Mapping
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, Field, ImportString, TypeAdapter
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True, slots=True)
|
|
13
|
+
class Symbol:
|
|
14
|
+
"""An installed public symbol resolved in the server process."""
|
|
15
|
+
|
|
16
|
+
path: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, slots=True)
|
|
20
|
+
class Construct:
|
|
21
|
+
"""Construct an installed type in the server process with encoded parameters."""
|
|
22
|
+
|
|
23
|
+
path: str
|
|
24
|
+
fields: Mapping[str, object]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Message(BaseModel):
|
|
28
|
+
model_config = ConfigDict(extra="forbid", frozen=True, allow_inf_nan=False)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Atom(Message):
|
|
32
|
+
kind: Literal["value"] = "value"
|
|
33
|
+
value: None | bool | int | float | str
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Reference(Message):
|
|
37
|
+
kind: Literal["reference"] = "reference"
|
|
38
|
+
id: int = Field(ge=0)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Imported(Message):
|
|
42
|
+
kind: Literal["import"] = "import"
|
|
43
|
+
path: str = Field(min_length=1)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Built(Message):
|
|
47
|
+
kind: Literal["construct"] = "construct"
|
|
48
|
+
path: str = Field(min_length=1)
|
|
49
|
+
fields: dict[str, Value]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Sequence(Message):
|
|
53
|
+
kind: Literal["list", "tuple"]
|
|
54
|
+
items: tuple[Value, ...]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Fields(Message):
|
|
58
|
+
kind: Literal["dict"] = "dict"
|
|
59
|
+
items: dict[str, Value]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
type Value = Annotated[
|
|
63
|
+
Atom | Reference | Imported | Built | Sequence | Fields,
|
|
64
|
+
Field(discriminator="kind"),
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Request(Message):
|
|
69
|
+
operation: Literal["get", "call", "enter", "exit", "release"]
|
|
70
|
+
target: int = Field(default=0, ge=0)
|
|
71
|
+
method: str = Field(default="", pattern=r"^(?:[A-Za-z][A-Za-z0-9_]*|)$")
|
|
72
|
+
args: tuple[Value, ...] = ()
|
|
73
|
+
kwargs: dict[str, Value] = Field(default_factory=dict)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Result(Message):
|
|
77
|
+
kind: Literal["result"] = "result"
|
|
78
|
+
value: Value
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Failure(Message):
|
|
82
|
+
kind: Literal["error"] = "error"
|
|
83
|
+
type: str
|
|
84
|
+
message: str
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
for model in (Built, Sequence, Fields, Request, Result):
|
|
88
|
+
model.model_rebuild()
|
|
89
|
+
|
|
90
|
+
RESPONSE = TypeAdapter(Annotated[Result | Failure, Field(discriminator="kind")])
|
|
91
|
+
IMPORT = TypeAdapter(ImportString[Any])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def encode(value: object, reference: Callable[[object], Reference]) -> Value:
|
|
95
|
+
match value:
|
|
96
|
+
case Symbol(path):
|
|
97
|
+
return Imported(path=path)
|
|
98
|
+
case Construct(path, fields):
|
|
99
|
+
return Built(
|
|
100
|
+
path=path,
|
|
101
|
+
fields={key: encode(item, reference) for key, item in fields.items()},
|
|
102
|
+
)
|
|
103
|
+
case None | bool() | int() | float() | str():
|
|
104
|
+
return Atom(value=value)
|
|
105
|
+
case list() | tuple():
|
|
106
|
+
return Sequence(
|
|
107
|
+
kind="tuple" if isinstance(value, tuple) else "list",
|
|
108
|
+
items=tuple(encode(item, reference) for item in value),
|
|
109
|
+
)
|
|
110
|
+
case dict() if all(isinstance(key, str) for key in value):
|
|
111
|
+
return Fields(
|
|
112
|
+
items={key: encode(item, reference) for key, item in value.items()}
|
|
113
|
+
)
|
|
114
|
+
case _:
|
|
115
|
+
return reference(value)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def decode(value: Value, reference: Callable[[Reference], object]) -> Any:
|
|
119
|
+
match value:
|
|
120
|
+
case Atom():
|
|
121
|
+
return value.value
|
|
122
|
+
case Reference():
|
|
123
|
+
return reference(value)
|
|
124
|
+
case Imported():
|
|
125
|
+
return IMPORT.validate_python(value.path)
|
|
126
|
+
case Built():
|
|
127
|
+
return IMPORT.validate_python(value.path)(
|
|
128
|
+
**{key: decode(item, reference) for key, item in value.fields.items()}
|
|
129
|
+
)
|
|
130
|
+
case Sequence():
|
|
131
|
+
items = [decode(item, reference) for item in value.items]
|
|
132
|
+
return tuple(items) if value.kind == "tuple" else items
|
|
133
|
+
case Fields():
|
|
134
|
+
return {key: decode(item, reference) for key, item in value.items.items()}
|