jupywire 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.
- jupywire-0.1.0/CHANGELOG.md +8 -0
- jupywire-0.1.0/LICENSE +202 -0
- jupywire-0.1.0/MANIFEST.in +3 -0
- jupywire-0.1.0/PKG-INFO +43 -0
- jupywire-0.1.0/README.md +22 -0
- jupywire-0.1.0/jupywire/__init__.py +1 -0
- jupywire-0.1.0/jupywire/connect.py +55 -0
- jupywire-0.1.0/jupywire/ops.py +91 -0
- jupywire-0.1.0/jupywire/session.py +184 -0
- jupywire-0.1.0/jupywire.egg-info/PKG-INFO +43 -0
- jupywire-0.1.0/jupywire.egg-info/SOURCES.txt +15 -0
- jupywire-0.1.0/jupywire.egg-info/dependency_links.txt +1 -0
- jupywire-0.1.0/jupywire.egg-info/requires.txt +8 -0
- jupywire-0.1.0/jupywire.egg-info/top_level.txt +1 -0
- jupywire-0.1.0/pyproject.toml +36 -0
- jupywire-0.1.0/setup.cfg +4 -0
- jupywire-0.1.0/tests/test_session.py +128 -0
jupywire-0.1.0/LICENSE
ADDED
|
@@ -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.
|
jupywire-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jupywire
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Minimal Jupyter protocol commons: wire-format sessions and kernel-client call conventions
|
|
5
|
+
Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/AnswerDotAI/jupywire
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: fastcore>=2.1.18
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: fastship; extra == "dev"
|
|
16
|
+
Requires-Dist: build; extra == "dev"
|
|
17
|
+
Requires-Dist: twine; extra == "dev"
|
|
18
|
+
Requires-Dist: pytest; extra == "dev"
|
|
19
|
+
Requires-Dist: jupyter_client>=8.0; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# jupywire
|
|
23
|
+
|
|
24
|
+
Minimal Jupyter protocol commons: wire-format sessions (message construction, HMAC signing, frame serialize/deserialize) and kernel-client call conventions, shared by kernmini, jupygate, jupyasyncclient, and conkernelclient.
|
|
25
|
+
|
|
26
|
+
## What's here
|
|
27
|
+
|
|
28
|
+
- `jupywire.session`: `Session` — Jupyter protocol messages: construction, HMAC signing, frame (de)serialization, replay protection — plus the websocket JSON/binary frame helpers (`dumps`/`loads`, `serialize_binary_message`/`deserialize_binary_message`) and `validate_string_dict`.
|
|
29
|
+
- `jupywire.connect`: `write_connection_file` — kernel connection files with random free-port selection, written 0600.
|
|
30
|
+
- `jupywire.ops`: `EvalOps` — a mixin giving any kernel client the calling conventions (`eval`, `ipy`, the `ipyfuncs` service methods, `xpush`/`retr`/`xenv`) over one abstract `reply` method supplied by the transport.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install jupywire
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
## Credits
|
|
40
|
+
|
|
41
|
+
`jupywire.session` and `jupywire.connect` are adapted from [jupyter_client](https://github.com/jupyter/jupyter_client) (`jupyter_client.session`, `jupyter_client.connect`, `jupyter_client.client`), Copyright (c) Jupyter Development Team, distributed under the terms of the Modified BSD License (BSD-3-Clause); see that project's COPYING.md.
|
|
42
|
+
|
|
43
|
+
The adaptations are trimmed, traitlets-free mirrors that stay wire-compatible. Divergences are noted in each module's docstring.
|
jupywire-0.1.0/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# jupywire
|
|
2
|
+
|
|
3
|
+
Minimal Jupyter protocol commons: wire-format sessions (message construction, HMAC signing, frame serialize/deserialize) and kernel-client call conventions, shared by kernmini, jupygate, jupyasyncclient, and conkernelclient.
|
|
4
|
+
|
|
5
|
+
## What's here
|
|
6
|
+
|
|
7
|
+
- `jupywire.session`: `Session` — Jupyter protocol messages: construction, HMAC signing, frame (de)serialization, replay protection — plus the websocket JSON/binary frame helpers (`dumps`/`loads`, `serialize_binary_message`/`deserialize_binary_message`) and `validate_string_dict`.
|
|
8
|
+
- `jupywire.connect`: `write_connection_file` — kernel connection files with random free-port selection, written 0600.
|
|
9
|
+
- `jupywire.ops`: `EvalOps` — a mixin giving any kernel client the calling conventions (`eval`, `ipy`, the `ipyfuncs` service methods, `xpush`/`retr`/`xenv`) over one abstract `reply` method supplied by the transport.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install jupywire
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## Credits
|
|
19
|
+
|
|
20
|
+
`jupywire.session` and `jupywire.connect` are adapted from [jupyter_client](https://github.com/jupyter/jupyter_client) (`jupyter_client.session`, `jupyter_client.connect`, `jupyter_client.client`), Copyright (c) Jupyter Development Team, distributed under the terms of the Modified BSD License (BSD-3-Clause); see that project's COPYING.md.
|
|
21
|
+
|
|
22
|
+
The adaptations are trimmed, traitlets-free mirrors that stay wire-compatible. Divergences are noted in each module's docstring.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Kernel connection files: `write_connection_file` with random free-port selection.
|
|
2
|
+
|
|
3
|
+
Adapted from `jupyter_client.connect` (BSD-3-Clause, Copyright (c) Jupyter Development Team; see
|
|
4
|
+
the Credits section of the README). Trimmed: no CurveZMQ key support, `ip` defaults to 127.0.0.1
|
|
5
|
+
rather than probing local interfaces, and `secure_write` is inlined as an 0600 open.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json, os, socket, stat, tempfile
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _secure_open(fname: str):
|
|
12
|
+
"Open `fname` for writing, created 0600 (the file carries the kernel's signing key)."
|
|
13
|
+
return os.fdopen(os.open(fname, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w")
|
|
14
|
+
|
|
15
|
+
def write_connection_file(fname=None, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0, control_port=0,
|
|
16
|
+
ip="", key=b"", transport="tcp", signature_scheme="hmac-sha256", kernel_name="", **kwargs) -> tuple[str, dict]:
|
|
17
|
+
"Write a Jupyter connection-file JSON dict to `fname` (0600), picking random free ports for any left 0; returns `(fname, cfg)`."
|
|
18
|
+
if not ip: ip = "127.0.0.1"
|
|
19
|
+
if not fname:
|
|
20
|
+
fd, fname = tempfile.mkstemp(".json")
|
|
21
|
+
os.close(fd)
|
|
22
|
+
ports, sockets = [], []
|
|
23
|
+
ports_needed = sum(int(p <= 0) for p in (shell_port, iopub_port, stdin_port, control_port, hb_port))
|
|
24
|
+
if transport == "tcp":
|
|
25
|
+
for _ in range(ports_needed):
|
|
26
|
+
sock = socket.socket()
|
|
27
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b"\0" * 8) # 8 null bytes = struct.pack('ii', (0,0))
|
|
28
|
+
sock.bind((ip, 0))
|
|
29
|
+
sockets.append(sock)
|
|
30
|
+
for sock in sockets:
|
|
31
|
+
port = sock.getsockname()[1]
|
|
32
|
+
sock.close()
|
|
33
|
+
ports.append(port)
|
|
34
|
+
else: # ipc: sequentially numbered paths that don't exist yet
|
|
35
|
+
N = 1
|
|
36
|
+
for _ in range(ports_needed):
|
|
37
|
+
while os.path.exists(f"{ip}-{N!s}"): N += 1
|
|
38
|
+
ports.append(N)
|
|
39
|
+
N += 1
|
|
40
|
+
if shell_port <= 0: shell_port = ports.pop(0)
|
|
41
|
+
if iopub_port <= 0: iopub_port = ports.pop(0)
|
|
42
|
+
if stdin_port <= 0: stdin_port = ports.pop(0)
|
|
43
|
+
if control_port <= 0: control_port = ports.pop(0)
|
|
44
|
+
if hb_port <= 0: hb_port = ports.pop(0)
|
|
45
|
+
cfg = dict(shell_port=shell_port, iopub_port=iopub_port, stdin_port=stdin_port, control_port=control_port,
|
|
46
|
+
hb_port=hb_port, ip=ip, key=key.decode(), transport=transport, signature_scheme=signature_scheme, kernel_name=kernel_name)
|
|
47
|
+
cfg.update(kwargs)
|
|
48
|
+
with _secure_open(fname) as f: f.write(json.dumps(cfg, indent=2))
|
|
49
|
+
if hasattr(stat, "S_ISVTX"):
|
|
50
|
+
# sticky-bit the parent dir, so only the owner can remove the file (EPERM etc suppressed: we may not own the dir)
|
|
51
|
+
runtime_dir = os.path.dirname(fname)
|
|
52
|
+
if runtime_dir:
|
|
53
|
+
try: os.chmod(runtime_dir, os.stat(runtime_dir).st_mode | stat.S_ISVTX)
|
|
54
|
+
except OSError: pass
|
|
55
|
+
return fname, cfg
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Client-side call conventions for a Jupyter kernel: `eval`, `ipy`, and friends over one abstract `reply` seam.
|
|
2
|
+
|
|
3
|
+
`EvalOps` is a mixin for kernel clients (conkernelclient's `ConKernelClient`, jupyasyncclient's
|
|
4
|
+
`JupyAsyncKernelClient`): the inheritor supplies `reply(code, user_expressions=, timeout=,
|
|
5
|
+
priority=, **kw)` awaiting its transport's `execute_reply` message, and gets the whole calling
|
|
6
|
+
surface: `eval` (call a kernel-side function by name, result reconstructed by repr), `ipy`
|
|
7
|
+
(`get_ipython()` methods), the generated `ipyfuncs` service methods, `xpush`/`retr`/`xenv`.
|
|
8
|
+
`priority=` routes via a dedicated subshell: only hosts that create one set `self.priority`, and
|
|
9
|
+
`reply` implementations assert otherwise. `_pre_ipy` is a liveness hook (default no-op).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
from ast import literal_eval
|
|
14
|
+
from fastcore.utils import rtoken_hex, nested_idx
|
|
15
|
+
from fastcore.ansi import strip_ansi
|
|
16
|
+
from fastcore.nbio import preferred_out
|
|
17
|
+
|
|
18
|
+
class EvalException(Exception): pass
|
|
19
|
+
|
|
20
|
+
_prims = str, int, float, complex, bool, tuple, list, dict, set, frozenset
|
|
21
|
+
|
|
22
|
+
def try_eval(s, typ:str|None=None):
|
|
23
|
+
"Like `literal_eval`, but wraps in dynamic class named `typ` if succeeds, and returns `s` if fails"
|
|
24
|
+
try:
|
|
25
|
+
res = literal_eval(s)
|
|
26
|
+
if typ and isinstance(res, _prims): res = type(typ, (type(res),), {})(res)
|
|
27
|
+
return res
|
|
28
|
+
except: return s
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class EvalOps:
|
|
32
|
+
"Kernel-client calling conventions over the inheritor's `reply`: see the module docstring."
|
|
33
|
+
priority = None # a subshell id for out-of-band evals; only hosts that create one (e.g. solveit) set it
|
|
34
|
+
|
|
35
|
+
def reply(self, code, user_expressions=None, timeout=None, priority=False, **kw):
|
|
36
|
+
"The transport seam: run `code`, returning an awaitable of the `execute_reply` message."
|
|
37
|
+
raise NotImplementedError
|
|
38
|
+
|
|
39
|
+
def _pre_ipy(self): pass # liveness hook: transports may raise their dead-kernel error here
|
|
40
|
+
|
|
41
|
+
async def eval(self, func:str, *args, _timeout=60, _literal=True, _priority=False, _call=True, _msg_id=None, **kw):
|
|
42
|
+
"Result of running `func(*args, **kw)`"
|
|
43
|
+
if _priority: assert self.priority, 'no priority subshell configured'
|
|
44
|
+
vname = f'__{rtoken_hex(4)}'
|
|
45
|
+
if _call:
|
|
46
|
+
code = f'''import asyncio
|
|
47
|
+
{vname} = {func}(*{args!r}, **{kw!r})
|
|
48
|
+
if asyncio.iscoroutine({vname}): {vname} = await {vname}
|
|
49
|
+
'''
|
|
50
|
+
else: code = f'{vname} = {func}'
|
|
51
|
+
exprs = dict(__res=vname, __typ=f"type({vname}).__name__", __del=f"globals().pop('{vname}', None)")
|
|
52
|
+
kw2 = dict(user_expressions=exprs, timeout=_timeout, store_history=False, priority=_priority)
|
|
53
|
+
if _msg_id is not None: kw2['msg_id'] = _msg_id
|
|
54
|
+
try: cts = (await self.reply(code, **kw2))['content']
|
|
55
|
+
except TimeoutError: return 'timeout'
|
|
56
|
+
except TypeError as e: raise EvalException(f"Eval failed: {e}") # e.g. kernel not running
|
|
57
|
+
if cts['status']!='ok': return strip_ansi('\n'.join(cts.get('traceback', ['err'])))
|
|
58
|
+
typ = nested_idx(cts, 'user_expressions', '__typ', 'data', 'text/plain')
|
|
59
|
+
if typ: typ = typ.strip("'")
|
|
60
|
+
res = nested_idx(cts, 'user_expressions', '__res', 'data')
|
|
61
|
+
if not res: return res
|
|
62
|
+
res = preferred_out(res, html1st=False)[1]
|
|
63
|
+
try: return try_eval(res, typ) if _literal else res
|
|
64
|
+
except Exception as e: return str(e)
|
|
65
|
+
|
|
66
|
+
async def ipy(self, meth, *args, priority=False, timeout=5, **kwargs):
|
|
67
|
+
if not hasattr(self, '_ipylock'): self._ipylock = asyncio.Lock()
|
|
68
|
+
self._pre_ipy()
|
|
69
|
+
async with self._ipylock: return await self.eval('get_ipython().'+meth, _priority=priority, _timeout=timeout, *args, **kwargs)
|
|
70
|
+
|
|
71
|
+
async def xpush(self, priority=False, **kwargs): await self.reply(f'get_ipython().push({kwargs!r})', priority=priority)
|
|
72
|
+
|
|
73
|
+
async def retr(self, nm:str, priority=False):
|
|
74
|
+
"Retrieve a single variable value"
|
|
75
|
+
return await self.eval(nm, _call=False, _priority=priority, _timeout=60)
|
|
76
|
+
|
|
77
|
+
async def xenv(self, priority=False, **kw):
|
|
78
|
+
"Put all of `kw` in os.environ"
|
|
79
|
+
code = 'import os as __os\n'
|
|
80
|
+
code += '\n'.join(f'__os.environ[{k!r}]={str(v)!r}' for k,v in kw.items())
|
|
81
|
+
return await self.reply(code, priority=priority)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _mk_ipy(meth):
|
|
85
|
+
async def f(self, *args, priority=False, **kwargs): return await self.ipy(meth, *args, priority=priority, **kwargs)
|
|
86
|
+
f.__name__ = meth
|
|
87
|
+
setattr(EvalOps, meth, f)
|
|
88
|
+
|
|
89
|
+
_ipy_funcs = ['user_items', 'get_vars', 'eval_exprs', 'get_schemas', 'publish', 'ranked_complete', 'sig_help']
|
|
90
|
+
for o in _ipy_funcs: _mk_ipy(o)
|
|
91
|
+
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Jupyter wire-format sessions: message construction, HMAC signing, and (de)serialization.
|
|
2
|
+
|
|
3
|
+
Adapted from `jupyter_client.session` (BSD-3-Clause, Copyright (c) Jupyter Development Team;
|
|
4
|
+
see the Credits section of the README), trimmed to the surface this ecosystem needs and stripped
|
|
5
|
+
of traitlets. Wire-compatible with jupyter_client: same frame layout (`<IDS|MSG>` delimiter, hex
|
|
6
|
+
HMAC signature, header/parent/metadata/content JSON, raw buffer frames), same replay protection
|
|
7
|
+
("Duplicate Signature"), same error strings. Deliberate simplifications, none of which change
|
|
8
|
+
bytes on the wire: header dates stay ISO-8601 strings on deserialize (jupyter_client converts
|
|
9
|
+
them to datetimes client-side); no v4-protocol adaptation (our kernels speak 5.3 only); no fork
|
|
10
|
+
guard. Socket-facing `send`/`recv` live with the transports (kernmini's `MiniSession` subclass);
|
|
11
|
+
the websocket JSON/binary helpers below are the frame layer jupygate's channel protocol uses.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import hashlib, hmac, json, numbers, os, uuid
|
|
15
|
+
from binascii import b2a_base64
|
|
16
|
+
from collections.abc import Iterable
|
|
17
|
+
from datetime import date, datetime, timezone
|
|
18
|
+
from fastcore.basics import xdumps, revive_dates
|
|
19
|
+
from fastcore.nbio import pack_frames, unpack_frames
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
DELIM = b"<IDS|MSG>"
|
|
23
|
+
protocol_version = "5.3"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def utcnow() -> datetime: return datetime.now(timezone.utc)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def json_default(obj):
|
|
30
|
+
"JSON serializer mirroring `jupyter_client.jsonutil.json_default`: ISO-8601 Z-suffix datetimes, b64 bytes, listified iterables, coerced numerics."
|
|
31
|
+
if isinstance(obj, datetime):
|
|
32
|
+
if obj.tzinfo is None: obj = obj.replace(tzinfo=timezone.utc)
|
|
33
|
+
return obj.isoformat().replace("+00:00", "Z")
|
|
34
|
+
if isinstance(obj, date): return obj.isoformat()
|
|
35
|
+
if isinstance(obj, bytes): return b2a_base64(obj, newline=False).decode("ascii")
|
|
36
|
+
if isinstance(obj, Iterable): return list(obj)
|
|
37
|
+
if isinstance(obj, numbers.Integral): return int(obj)
|
|
38
|
+
if isinstance(obj, numbers.Real): return float(obj)
|
|
39
|
+
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def json_packer(obj) -> bytes:
|
|
43
|
+
return json.dumps(obj, default=json_default, ensure_ascii=False, allow_nan=False,
|
|
44
|
+
separators=(",", ":")).encode("utf8", errors="surrogateescape")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def extract_header(msg_or_header: dict) -> dict:
|
|
48
|
+
"Given a message or header, return the header."
|
|
49
|
+
if not msg_or_header: return {}
|
|
50
|
+
if "header" in msg_or_header: return msg_or_header["header"]
|
|
51
|
+
if "msg_id" in msg_or_header: return msg_or_header
|
|
52
|
+
raise KeyError("no header found")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _bytes(m) -> bytes:
|
|
56
|
+
"A frame as bytes, whether it arrived as bytes or a non-copying frame (e.g. zmq.Frame), without importing any transport."
|
|
57
|
+
return m if isinstance(m, bytes) else m.bytes
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Session:
|
|
61
|
+
"Build, sign, serialize, and deserialize Jupyter protocol messages over one session identity."
|
|
62
|
+
|
|
63
|
+
def __init__(self, key: bytes | None = None, signature_scheme: str = "hmac-sha256", username: str = "",
|
|
64
|
+
session: str | None = None, digest_history_size: int = 2**16):
|
|
65
|
+
self.session = session or str(uuid.uuid4())
|
|
66
|
+
self.username = username or os.environ.get("USER", "username")
|
|
67
|
+
self.metadata = {}
|
|
68
|
+
if key is None: key = uuid.uuid4().hex.encode("ascii") # jupyter_client parity: a fresh random key when unspecified
|
|
69
|
+
if key:
|
|
70
|
+
if not signature_scheme.startswith("hmac-"): raise ValueError(f"unsupported signature scheme: {signature_scheme!r}")
|
|
71
|
+
digest = signature_scheme.removeprefix("hmac-")
|
|
72
|
+
if digest not in hashlib.algorithms_available: raise ValueError(f"unsupported digest: {digest!r}")
|
|
73
|
+
self.auth = hmac.HMAC(key, digestmod=getattr(hashlib, digest))
|
|
74
|
+
else: self.auth = None
|
|
75
|
+
self.digest_history = set()
|
|
76
|
+
self.digest_history_size = digest_history_size
|
|
77
|
+
self.message_count = 0
|
|
78
|
+
self.pack, self.unpack = json_packer, json.loads
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def msg_id(self) -> str:
|
|
82
|
+
n = self.message_count
|
|
83
|
+
self.message_count += 1
|
|
84
|
+
return f"{self.session}_{os.getpid()}_{n}"
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def bsession(self) -> bytes: return self.session.encode("ascii")
|
|
88
|
+
|
|
89
|
+
def msg_header(self, msg_type: str) -> dict:
|
|
90
|
+
return dict(msg_id=self.msg_id, msg_type=msg_type, username=self.username, session=self.session,
|
|
91
|
+
date=utcnow(), version=protocol_version)
|
|
92
|
+
|
|
93
|
+
def msg(self, msg_type: str, content: dict | None = None, parent: dict | None = None,
|
|
94
|
+
header: dict | None = None, metadata: dict | None = None) -> dict:
|
|
95
|
+
"Return the nested message dict (the pre-wire form; `serialize` makes the frame list)."
|
|
96
|
+
header = self.msg_header(msg_type) if header is None else header
|
|
97
|
+
parent_h = {} if parent is None else extract_header(parent)
|
|
98
|
+
msg = dict(header=header, msg_id=header["msg_id"], msg_type=header["msg_type"], parent_header=parent_h,
|
|
99
|
+
content=content or {}, metadata=self.metadata.copy())
|
|
100
|
+
if metadata is not None: msg["metadata"].update(metadata)
|
|
101
|
+
return msg
|
|
102
|
+
|
|
103
|
+
def sign(self, msg_list: list) -> bytes:
|
|
104
|
+
"Hex HMAC digest of the [p_header,p_parent,p_metadata,p_content] frames; b'' when unauthenticated."
|
|
105
|
+
if self.auth is None: return b""
|
|
106
|
+
h = self.auth.copy()
|
|
107
|
+
for m in msg_list: h.update(_bytes(m))
|
|
108
|
+
return h.hexdigest().encode()
|
|
109
|
+
|
|
110
|
+
def serialize(self, msg: dict, ident: list[bytes] | bytes | None = None) -> list[bytes]:
|
|
111
|
+
"Frame list [ident..., DELIM, signature, p_header, p_parent, p_metadata, p_content] for `msg`."
|
|
112
|
+
content = msg.get("content", {})
|
|
113
|
+
if content is None: content = self.pack({})
|
|
114
|
+
elif isinstance(content, dict): content = self.pack(content)
|
|
115
|
+
elif isinstance(content, str): content = content.encode("utf8")
|
|
116
|
+
elif not isinstance(content, bytes): raise TypeError(f"content incorrect type: {type(content)}")
|
|
117
|
+
real_message = [self.pack(msg["header"]), self.pack(msg["parent_header"]), self.pack(msg["metadata"]), content]
|
|
118
|
+
to_send = list(ident) if isinstance(ident, list) else [ident] if ident is not None else []
|
|
119
|
+
to_send.append(DELIM)
|
|
120
|
+
to_send.append(self.sign(real_message))
|
|
121
|
+
to_send.extend(real_message)
|
|
122
|
+
return to_send
|
|
123
|
+
|
|
124
|
+
def feed_identities(self, msg_list: list, copy: bool = True) -> tuple[list[bytes], list]:
|
|
125
|
+
"Split a received frame list at DELIM into (idents, remainder)."
|
|
126
|
+
for idx, m in enumerate(msg_list):
|
|
127
|
+
if _bytes(m) == DELIM: return [bytes(_bytes(i)) for i in msg_list[:idx]], msg_list[idx + 1:]
|
|
128
|
+
raise ValueError("DELIM not in msg_list")
|
|
129
|
+
|
|
130
|
+
def _add_digest(self, signature: bytes):
|
|
131
|
+
if self.digest_history_size == 0: return
|
|
132
|
+
self.digest_history.add(signature)
|
|
133
|
+
if len(self.digest_history) > self.digest_history_size:
|
|
134
|
+
import random
|
|
135
|
+
to_cull = random.sample(tuple(sorted(self.digest_history)), len(self.digest_history) // 10)
|
|
136
|
+
self.digest_history.difference_update(to_cull)
|
|
137
|
+
|
|
138
|
+
def deserialize(self, msg_list: list, content: bool = True, copy: bool = True) -> dict:
|
|
139
|
+
"Verify signature and unpack a [signature, p_header, p_parent, p_metadata, p_content, buffer...] frame list."
|
|
140
|
+
msg_list = [_bytes(m) for m in msg_list[:5]] + list(msg_list[5:])
|
|
141
|
+
if self.auth is not None:
|
|
142
|
+
signature = msg_list[0]
|
|
143
|
+
if not signature: raise ValueError("Unsigned Message")
|
|
144
|
+
if signature in self.digest_history: raise ValueError("Duplicate Signature: %r" % signature)
|
|
145
|
+
if content: self._add_digest(signature) # only record when unpacking, not peeking
|
|
146
|
+
if not hmac.compare_digest(signature, self.sign(msg_list[1:5])): raise ValueError("Invalid Signature: %r" % signature)
|
|
147
|
+
if len(msg_list) < 5: raise TypeError("malformed message, must have at least 5 elements")
|
|
148
|
+
header = self.unpack(msg_list[1])
|
|
149
|
+
content_v = self.unpack(msg_list[4]) if content else msg_list[4]
|
|
150
|
+
bufs = [memoryview(_bytes(b)) for b in msg_list[5:]]
|
|
151
|
+
return dict(header=header, msg_id=header["msg_id"], msg_type=header["msg_type"], parent_header=self.unpack(msg_list[2]),
|
|
152
|
+
metadata=self.unpack(msg_list[3]), content=content_v, buffers=bufs)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def dumps(msg): return xdumps(msg)
|
|
156
|
+
|
|
157
|
+
def loads(s: str):
|
|
158
|
+
msg = json.loads(s)
|
|
159
|
+
if isinstance(msg, dict):
|
|
160
|
+
for k in ("header", "parent_header"):
|
|
161
|
+
if isinstance(msg.get(k), dict): msg[k] = revive_dates(msg[k])
|
|
162
|
+
return msg
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def serialize_binary_message(msg):
|
|
166
|
+
msg = msg.copy()
|
|
167
|
+
buffers = msg.pop("buffers")
|
|
168
|
+
return pack_frames(dumps(msg).encode("utf8"), buffers)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def deserialize_binary_message(bmsg: bytes):
|
|
172
|
+
body, bufs = unpack_frames(bmsg)
|
|
173
|
+
msg = loads(body.decode("utf8"))
|
|
174
|
+
msg["buffers"] = [memoryview(b) for b in bufs]
|
|
175
|
+
return msg
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def validate_string_dict(dct: dict[str, str]) -> None:
|
|
179
|
+
"""Validate that the input is a dict with string keys and values.
|
|
180
|
+
|
|
181
|
+
Raises ValueError if not."""
|
|
182
|
+
for k, v in dct.items():
|
|
183
|
+
if not isinstance(k, str): raise ValueError("key %r in dict must be a string" % k)
|
|
184
|
+
if not isinstance(v, str): raise ValueError("value %r in dict must be a string" % v)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jupywire
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Minimal Jupyter protocol commons: wire-format sessions and kernel-client call conventions
|
|
5
|
+
Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/AnswerDotAI/jupywire
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: fastcore>=2.1.18
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: fastship; extra == "dev"
|
|
16
|
+
Requires-Dist: build; extra == "dev"
|
|
17
|
+
Requires-Dist: twine; extra == "dev"
|
|
18
|
+
Requires-Dist: pytest; extra == "dev"
|
|
19
|
+
Requires-Dist: jupyter_client>=8.0; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# jupywire
|
|
23
|
+
|
|
24
|
+
Minimal Jupyter protocol commons: wire-format sessions (message construction, HMAC signing, frame serialize/deserialize) and kernel-client call conventions, shared by kernmini, jupygate, jupyasyncclient, and conkernelclient.
|
|
25
|
+
|
|
26
|
+
## What's here
|
|
27
|
+
|
|
28
|
+
- `jupywire.session`: `Session` — Jupyter protocol messages: construction, HMAC signing, frame (de)serialization, replay protection — plus the websocket JSON/binary frame helpers (`dumps`/`loads`, `serialize_binary_message`/`deserialize_binary_message`) and `validate_string_dict`.
|
|
29
|
+
- `jupywire.connect`: `write_connection_file` — kernel connection files with random free-port selection, written 0600.
|
|
30
|
+
- `jupywire.ops`: `EvalOps` — a mixin giving any kernel client the calling conventions (`eval`, `ipy`, the `ipyfuncs` service methods, `xpush`/`retr`/`xenv`) over one abstract `reply` method supplied by the transport.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install jupywire
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
## Credits
|
|
40
|
+
|
|
41
|
+
`jupywire.session` and `jupywire.connect` are adapted from [jupyter_client](https://github.com/jupyter/jupyter_client) (`jupyter_client.session`, `jupyter_client.connect`, `jupyter_client.client`), Copyright (c) Jupyter Development Team, distributed under the terms of the Modified BSD License (BSD-3-Clause); see that project's COPYING.md.
|
|
42
|
+
|
|
43
|
+
The adaptations are trimmed, traitlets-free mirrors that stay wire-compatible. Divergences are noted in each module's docstring.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
CHANGELOG.md
|
|
2
|
+
LICENSE
|
|
3
|
+
MANIFEST.in
|
|
4
|
+
README.md
|
|
5
|
+
pyproject.toml
|
|
6
|
+
jupywire/__init__.py
|
|
7
|
+
jupywire/connect.py
|
|
8
|
+
jupywire/ops.py
|
|
9
|
+
jupywire/session.py
|
|
10
|
+
jupywire.egg-info/PKG-INFO
|
|
11
|
+
jupywire.egg-info/SOURCES.txt
|
|
12
|
+
jupywire.egg-info/dependency_links.txt
|
|
13
|
+
jupywire.egg-info/requires.txt
|
|
14
|
+
jupywire.egg-info/top_level.txt
|
|
15
|
+
tests/test_session.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
jupywire
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "jupywire"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Minimal Jupyter protocol commons: wire-format sessions and kernel-client call conventions"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{name = "Jeremy Howard", email = "github@jhoward.fastmail.fm"}]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
dependencies = ['fastcore>=2.1.18']
|
|
19
|
+
|
|
20
|
+
[project.optional-dependencies]
|
|
21
|
+
dev = [
|
|
22
|
+
"fastship",
|
|
23
|
+
"build",
|
|
24
|
+
"twine",
|
|
25
|
+
"pytest",
|
|
26
|
+
"jupyter_client>=8.0",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/AnswerDotAI/jupywire"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.dynamic]
|
|
33
|
+
version = { attr = "jupywire.__version__" }
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.packages.find]
|
|
36
|
+
include = ["jupywire"]
|
jupywire-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"Wire-format tests, cross-verified against jupyter_client (dev dep): same bytes, same signatures, same errors."
|
|
2
|
+
import json, os, stat
|
|
3
|
+
from datetime import datetime, timezone, date
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from jupyter_client.session import Session as JCSession
|
|
7
|
+
|
|
8
|
+
from jupywire.session import (Session, json_default, json_packer, serialize_binary_message,
|
|
9
|
+
deserialize_binary_message, validate_string_dict, dumps, loads, DELIM)
|
|
10
|
+
from jupywire.connect import write_connection_file
|
|
11
|
+
|
|
12
|
+
KEY = b"secret-key"
|
|
13
|
+
|
|
14
|
+
def _wire(sess, msg, ident=None):
|
|
15
|
+
frames = sess.serialize(msg, ident=ident)
|
|
16
|
+
idents, rest = sess.feed_identities(frames)
|
|
17
|
+
return idents, list(rest)
|
|
18
|
+
|
|
19
|
+
def test_sign_matches_jupyter_client():
|
|
20
|
+
s, jc = Session(key=KEY), JCSession(key=KEY)
|
|
21
|
+
frames = [b'{"a":1}', b'{}', b'{}', b'{"code":"6*7"}']
|
|
22
|
+
assert s.sign(frames) == jc.sign(frames)
|
|
23
|
+
assert Session(key=b"").sign(frames) == b""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_roundtrip_via_jupyter_client():
|
|
27
|
+
s, jc = Session(key=KEY, session="abc"), JCSession(key=KEY, session="abc")
|
|
28
|
+
msg = s.msg("execute_request", dict(code="6*7", silent=False))
|
|
29
|
+
wire = s.serialize(msg)
|
|
30
|
+
assert wire[0] == DELIM
|
|
31
|
+
idents, rest = jc.feed_identities(wire)
|
|
32
|
+
got = jc.deserialize(rest)
|
|
33
|
+
assert got["content"] == msg["content"] and got["msg_type"] == "execute_request"
|
|
34
|
+
# and the reverse: jupyter_client-built frames verify and unpack here
|
|
35
|
+
jmsg = jc.msg("kernel_info_request")
|
|
36
|
+
idents, rest = s.feed_identities(jc.serialize(jmsg))
|
|
37
|
+
got = s.deserialize(rest)
|
|
38
|
+
assert got["msg_id"] == jmsg["header"]["msg_id"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_json_default_parity():
|
|
43
|
+
from jupyter_client.jsonutil import json_default as jc_default
|
|
44
|
+
aware = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
|
|
45
|
+
for v in (aware, date(2026, 1, 2), b"some bytes", {1, 2, 3}): assert json_default(v) == jc_default(v)
|
|
46
|
+
naive = datetime(2026, 1, 2, 3, 4, 5)
|
|
47
|
+
assert json_default(naive) == "2026-01-02T03:04:05Z" # naive treated as UTC (jupyter_client's local-time reading is deprecated)
|
|
48
|
+
with pytest.raises(TypeError): json_default(object())
|
|
49
|
+
assert json.loads(json_packer(dict(b=b"xy", t=aware)).decode()) == json.loads(
|
|
50
|
+
json.dumps(dict(b=b"xy", t=aware), default=jc_default))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_default_key_is_random_like_jupyter_client():
|
|
54
|
+
a, b = Session(), Session()
|
|
55
|
+
assert a.auth is not None and b.auth is not None
|
|
56
|
+
assert a.sign([b"x"]) != b.sign([b"x"])
|
|
57
|
+
assert Session(session="abc").bsession == b"abc"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_binary_message_roundtrip():
|
|
61
|
+
s = Session(key=KEY)
|
|
62
|
+
msg = s.msg("display_data", dict(data={"text/plain": "hi"}))
|
|
63
|
+
msg["buffers"] = [b"bufone", b"buftwo"]
|
|
64
|
+
got = deserialize_binary_message(serialize_binary_message(msg))
|
|
65
|
+
assert got["content"] == msg["content"]
|
|
66
|
+
assert [bytes(b) for b in got["buffers"]] == [b"bufone", b"buftwo"]
|
|
67
|
+
assert loads(dumps(s.msg("status", dict(execution_state="idle"))))["content"]["execution_state"] == "idle"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_validate_string_dict():
|
|
71
|
+
validate_string_dict(dict(a="b"))
|
|
72
|
+
with pytest.raises(ValueError): validate_string_dict({"a": 1})
|
|
73
|
+
with pytest.raises(ValueError): validate_string_dict({1: "a"})
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_write_connection_file(tmp_path):
|
|
77
|
+
fname = str(tmp_path/"kernel.json")
|
|
78
|
+
fname2, cfg = write_connection_file(fname, ip="127.0.0.1", key=b"deadbeef")
|
|
79
|
+
assert fname2 == fname and os.path.exists(fname)
|
|
80
|
+
assert stat.S_IMODE(os.stat(fname).st_mode) == 0o600
|
|
81
|
+
on_disk = json.loads(open(fname).read())
|
|
82
|
+
ports = [cfg[k] for k in ("shell_port", "iopub_port", "stdin_port", "control_port", "hb_port")]
|
|
83
|
+
assert len(set(ports)) == 5 and all(p > 0 for p in ports)
|
|
84
|
+
assert on_disk == cfg
|
|
85
|
+
assert cfg["key"] == "deadbeef" and cfg["transport"] == "tcp" and cfg["ip"] == "127.0.0.1"
|
|
86
|
+
from jupyter_client.connect import write_connection_file as jc_wcf
|
|
87
|
+
_, jc_cfg = jc_wcf(str(tmp_path/"jc.json"), ip="127.0.0.1", key=b"deadbeef")
|
|
88
|
+
assert set(cfg) == set(jc_cfg)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_content_coercions():
|
|
92
|
+
"Bytes b64-encode, dates ISO-format, and iterables listify at pack time, as jupyter_client does (image display bundles rely on this)"
|
|
93
|
+
from binascii import b2a_base64
|
|
94
|
+
from datetime import date
|
|
95
|
+
s = Session(key=b"k")
|
|
96
|
+
png = b"\x89PNG fake bytes"
|
|
97
|
+
msg = s.msg("display_data", dict(data={"image/png": png}, when=date(2026, 8, 4), tags={"a"}))
|
|
98
|
+
_, rest = _wire(s, msg)
|
|
99
|
+
c = s.deserialize(rest)["content"]
|
|
100
|
+
assert c["data"]["image/png"] == b2a_base64(png, newline=False).decode("ascii")
|
|
101
|
+
assert c["when"] == "2026-08-04"
|
|
102
|
+
assert c["tags"] == ["a"]
|
|
103
|
+
jcs = pytest.importorskip("jupyter_client.session")
|
|
104
|
+
js = jcs.Session(key=b"k")
|
|
105
|
+
_, jrest = js.feed_identities(js.serialize(js.msg("display_data", msg["content"])))
|
|
106
|
+
assert js.deserialize(jrest)["content"] == c
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_replay_tamper_unsigned():
|
|
110
|
+
s = Session(key=b"secret")
|
|
111
|
+
_, rest = _wire(s, s.msg("a_request", dict(x=1)))
|
|
112
|
+
s.deserialize(list(rest))
|
|
113
|
+
with pytest.raises(ValueError, match="Duplicate Signature"): s.deserialize(list(rest))
|
|
114
|
+
bad = list(rest)
|
|
115
|
+
bad[0], bad[4] = b"0" * len(bad[0]), b'{"x":2}'
|
|
116
|
+
with pytest.raises(ValueError, match="Invalid Signature"): s.deserialize(bad)
|
|
117
|
+
with pytest.raises(ValueError, match="Unsigned Message"): s.deserialize([b""] + list(rest)[1:])
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_parent_and_buffers():
|
|
121
|
+
s = Session(key=b"k")
|
|
122
|
+
parent = s.msg("a_request", {})
|
|
123
|
+
reply = s.msg("a_reply", dict(status="ok"), parent=parent)
|
|
124
|
+
frames = s.serialize(reply) + [b"rawbuf"]
|
|
125
|
+
_, rest = s.feed_identities(frames)
|
|
126
|
+
out = s.deserialize(rest)
|
|
127
|
+
assert out["parent_header"]["msg_id"] == parent["header"]["msg_id"]
|
|
128
|
+
assert bytes(out["buffers"][0]) == b"rawbuf"
|