python-repl-mcp 0.2.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_repl_mcp/__init__.py +5 -0
- python_repl_mcp/_helper.py +197 -0
- python_repl_mcp/_winjob.py +175 -0
- python_repl_mcp/config.py +84 -0
- python_repl_mcp/errors.py +63 -0
- python_repl_mcp/fileio.py +130 -0
- python_repl_mcp/kernel.py +724 -0
- python_repl_mcp/launcher.py +43 -0
- python_repl_mcp/opencode.py +195 -0
- python_repl_mcp/protocol.py +210 -0
- python_repl_mcp/server.py +318 -0
- python_repl_mcp/service.py +866 -0
- python_repl_mcp/worker.py +549 -0
- python_repl_mcp-0.2.5.dist-info/METADATA +218 -0
- python_repl_mcp-0.2.5.dist-info/RECORD +19 -0
- python_repl_mcp-0.2.5.dist-info/WHEEL +5 -0
- python_repl_mcp-0.2.5.dist-info/entry_points.txt +2 -0
- python_repl_mcp-0.2.5.dist-info/licenses/LICENSE +21 -0
- python_repl_mcp-0.2.5.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Gated bootstrap that starts the real worker.
|
|
2
|
+
|
|
3
|
+
The launcher runs isolated (``-I -S -u``) so no user site hook can disturb it.
|
|
4
|
+
It waits for exactly one start byte, passes its own stdin/stdout to the worker
|
|
5
|
+
and then waits on the worker's process handle. Waiting on the handle, never on
|
|
6
|
+
pipe EOF, is what makes the server's ``process_exited()`` mean "the worker is
|
|
7
|
+
gone" even when a descendant still holds an inherited pipe.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import subprocess # nosec B404
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv: list[str]) -> int:
|
|
18
|
+
if len(argv) != 3:
|
|
19
|
+
return 2
|
|
20
|
+
package_root, worker_python = argv[1], argv[2]
|
|
21
|
+
gate = os.read(0, 1)
|
|
22
|
+
if gate != b"\x01":
|
|
23
|
+
return 2
|
|
24
|
+
|
|
25
|
+
environment = dict(os.environ)
|
|
26
|
+
existing = environment.get("PYTHONPATH")
|
|
27
|
+
environment["PYTHONPATH"] = package_root if not existing else os.pathsep.join([package_root, existing])
|
|
28
|
+
# The server decodes captured output as UTF-8; keep the worker and its
|
|
29
|
+
# Python children on the same encoding instead of the console code page.
|
|
30
|
+
environment["PYTHONIOENCODING"] = "utf-8"
|
|
31
|
+
process = subprocess.Popen( # nosec B603
|
|
32
|
+
[worker_python, "-P", "-u", "-m", "python_repl_mcp.worker"],
|
|
33
|
+
stdin=0,
|
|
34
|
+
stdout=1,
|
|
35
|
+
stderr=subprocess.DEVNULL,
|
|
36
|
+
env=environment,
|
|
37
|
+
close_fds=True,
|
|
38
|
+
)
|
|
39
|
+
return process.wait()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
sys.exit(main(sys.argv))
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Resolve a chat directory through the configured local OpenCode owner."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Final, cast
|
|
14
|
+
|
|
15
|
+
from python_repl_mcp._helper import (
|
|
16
|
+
BeforePublish,
|
|
17
|
+
ExitUnconfirmed,
|
|
18
|
+
HelperFailed,
|
|
19
|
+
HelperOutput,
|
|
20
|
+
HelperTimeout,
|
|
21
|
+
base_environment,
|
|
22
|
+
run_helper,
|
|
23
|
+
)
|
|
24
|
+
from python_repl_mcp.errors import SessionDirectoryUnavailable
|
|
25
|
+
|
|
26
|
+
SERVER_ENV: Final = "PYTHON_REPL_MCP_OPENCODE_SERVER"
|
|
27
|
+
CLI_ENV: Final = "PYTHON_REPL_MCP_OPENCODE_CLI"
|
|
28
|
+
AUTH_ENV: Final = ("OPENCODE_PASSWORD", "OPENCODE_USERNAME")
|
|
29
|
+
_PROXY_ENV: Final = ("ALL_PROXY", "HTTP_PROXY", "HTTPS_PROXY")
|
|
30
|
+
_LOOKUP_SECONDS: Final = 5.0
|
|
31
|
+
_EXIT_SECONDS: Final = 5.0
|
|
32
|
+
_MAX_REPLY_BYTES: Final = 256 * 1024
|
|
33
|
+
_SESSION_ID: Final = re.compile(r"[A-Za-z0-9_-]+")
|
|
34
|
+
_CHECK_CODE: Final = "import os, sys\nraise SystemExit(0 if os.path.isdir(sys.argv[1]) else 3)\n"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class LookupFailed(Exception):
|
|
38
|
+
"""Internal: this attempt cannot produce a usable chat directory."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def valid_session_id(value: str) -> bool:
|
|
42
|
+
"""Keep chat metadata a single CLI value and HTTP path segment."""
|
|
43
|
+
return _SESSION_ID.fullmatch(value) is not None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _cli_environment() -> dict[str, str]:
|
|
47
|
+
"""The selected loopback owner is the only destination for the host credential."""
|
|
48
|
+
return {name: value for name, value in os.environ.items() if name.upper() not in _PROXY_ENV}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _checker_environment() -> dict[str, str]:
|
|
52
|
+
return base_environment()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _checker_python() -> str:
|
|
56
|
+
# A venv ``python.exe`` is only a redirector; the check needs no venv.
|
|
57
|
+
return getattr(sys, "_base_executable", sys.executable)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class OpenCode:
|
|
62
|
+
server: str | None
|
|
63
|
+
cli: Path | None
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_environment(cls) -> OpenCode | None:
|
|
67
|
+
server = os.environ.get(SERVER_ENV)
|
|
68
|
+
if server is None:
|
|
69
|
+
return None
|
|
70
|
+
if server.strip().lower() == "auto":
|
|
71
|
+
server = None
|
|
72
|
+
else:
|
|
73
|
+
address = re.fullmatch(r"http://(?:127\.0\.0\.1|\[::1\]):([0-9]{1,5})", server)
|
|
74
|
+
if address is None or not 0 < int(address[1]) <= 65535:
|
|
75
|
+
raise ValueError(f"{SERVER_ENV} must be 'auto' or a literal loopback HTTP endpoint with a port")
|
|
76
|
+
executable = os.environ.get(CLI_ENV)
|
|
77
|
+
cli = Path(executable) if executable else None
|
|
78
|
+
if cli is not None and (not cli.is_absolute() or cli.suffix.lower() != ".exe"):
|
|
79
|
+
raise ValueError(f"{CLI_ENV} must be the absolute path to the native OpenCode .exe")
|
|
80
|
+
return cls(server, cli)
|
|
81
|
+
|
|
82
|
+
async def workdir(
|
|
83
|
+
self,
|
|
84
|
+
session_id: str,
|
|
85
|
+
dispatcher_workdir: Path,
|
|
86
|
+
*,
|
|
87
|
+
deadline: float | None = None,
|
|
88
|
+
abandoned: asyncio.Event | None = None,
|
|
89
|
+
before_publish: BeforePublish | None = None,
|
|
90
|
+
) -> Path:
|
|
91
|
+
if self.cli is None or (self.server is not None and not os.environ.get(AUTH_ENV[0])):
|
|
92
|
+
raise SessionDirectoryUnavailable(
|
|
93
|
+
"pooled OpenCode requires a native CLI; an explicit endpoint also requires host authentication"
|
|
94
|
+
)
|
|
95
|
+
if deadline is None:
|
|
96
|
+
deadline = asyncio.get_running_loop().time() + _LOOKUP_SECONDS
|
|
97
|
+
try:
|
|
98
|
+
if abandoned is not None and abandoned.is_set():
|
|
99
|
+
raise LookupFailed("the caller left before the lookup started")
|
|
100
|
+
reply = await self._session_reply(session_id, dispatcher_workdir, deadline, before_publish=before_publish)
|
|
101
|
+
if abandoned is not None and abandoned.is_set():
|
|
102
|
+
raise LookupFailed("the caller left before the directory check")
|
|
103
|
+
path = _directory(reply, session_id)
|
|
104
|
+
if path is not None and await self._is_directory(path, dispatcher_workdir, deadline, before_publish):
|
|
105
|
+
return path
|
|
106
|
+
except ExitUnconfirmed:
|
|
107
|
+
raise
|
|
108
|
+
except LookupFailed, OSError, RecursionError, TimeoutError, ValueError:
|
|
109
|
+
# Never expose the CLI's output, argv, or authentication in a tool reply.
|
|
110
|
+
pass
|
|
111
|
+
raise SessionDirectoryUnavailable("could not resolve this chat's directory from the configured OpenCode host")
|
|
112
|
+
|
|
113
|
+
async def _session_reply(
|
|
114
|
+
self,
|
|
115
|
+
session_id: str,
|
|
116
|
+
dispatcher_workdir: Path,
|
|
117
|
+
deadline: float,
|
|
118
|
+
before_publish: BeforePublish | None = None,
|
|
119
|
+
) -> bytes:
|
|
120
|
+
argv = [str(self.cli), "api"]
|
|
121
|
+
if self.server is not None:
|
|
122
|
+
argv.extend(["--server", self.server])
|
|
123
|
+
argv.extend(["session.get", "--param", f"sessionID={session_id}"])
|
|
124
|
+
status, output = await self._run(
|
|
125
|
+
argv,
|
|
126
|
+
cwd=dispatcher_workdir,
|
|
127
|
+
env=_cli_environment(),
|
|
128
|
+
deadline=deadline,
|
|
129
|
+
before_publish=before_publish,
|
|
130
|
+
)
|
|
131
|
+
if status != 0:
|
|
132
|
+
raise LookupFailed("OpenCode session lookup failed")
|
|
133
|
+
return output
|
|
134
|
+
|
|
135
|
+
async def _is_directory(
|
|
136
|
+
self,
|
|
137
|
+
path: Path,
|
|
138
|
+
dispatcher_workdir: Path,
|
|
139
|
+
deadline: float,
|
|
140
|
+
before_publish: BeforePublish | None = None,
|
|
141
|
+
) -> bool:
|
|
142
|
+
# The check runs in its own process so a stalled filesystem cannot hold
|
|
143
|
+
# the dispatcher open; its cwd never depends on the directory it checks.
|
|
144
|
+
status, _ = await self._run(
|
|
145
|
+
[str(_checker_python()), "-I", "-S", "-B", "-c", _CHECK_CODE, str(path)],
|
|
146
|
+
cwd=dispatcher_workdir,
|
|
147
|
+
env=_checker_environment(),
|
|
148
|
+
deadline=deadline,
|
|
149
|
+
before_publish=before_publish,
|
|
150
|
+
)
|
|
151
|
+
return status == 0
|
|
152
|
+
|
|
153
|
+
async def _run(
|
|
154
|
+
self,
|
|
155
|
+
argv: list[str],
|
|
156
|
+
*,
|
|
157
|
+
cwd: Path,
|
|
158
|
+
env: Mapping[str, str],
|
|
159
|
+
deadline: float,
|
|
160
|
+
before_publish: BeforePublish | None = None,
|
|
161
|
+
) -> tuple[int, bytes]:
|
|
162
|
+
try:
|
|
163
|
+
return await run_helper(
|
|
164
|
+
argv,
|
|
165
|
+
cwd=cwd,
|
|
166
|
+
env=dict(env),
|
|
167
|
+
deadline=deadline,
|
|
168
|
+
max_output=_MAX_REPLY_BYTES,
|
|
169
|
+
exit_seconds=_EXIT_SECONDS,
|
|
170
|
+
before_publish=before_publish,
|
|
171
|
+
)
|
|
172
|
+
except HelperTimeout as exc:
|
|
173
|
+
raise LookupFailed("the OpenCode helper deadline expired") from exc
|
|
174
|
+
except HelperOutput as exc:
|
|
175
|
+
raise LookupFailed("OpenCode helper output exceeded its limit") from exc
|
|
176
|
+
except HelperFailed as exc:
|
|
177
|
+
raise LookupFailed("the OpenCode helper could not report a usable exit") from exc
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _directory(reply: bytes, session_id: str) -> Path | None:
|
|
181
|
+
payload: object = json.loads(reply)
|
|
182
|
+
if not isinstance(payload, dict):
|
|
183
|
+
return None
|
|
184
|
+
data = cast("dict[str, object]", payload).get("data")
|
|
185
|
+
if not isinstance(data, dict):
|
|
186
|
+
return None
|
|
187
|
+
session = cast("dict[str, object]", data)
|
|
188
|
+
location = session.get("location")
|
|
189
|
+
if session.get("id") != session_id or not isinstance(location, dict):
|
|
190
|
+
return None
|
|
191
|
+
directory = cast("dict[str, object]", location).get("directory")
|
|
192
|
+
if not isinstance(directory, str) or "\0" in directory:
|
|
193
|
+
return None
|
|
194
|
+
path = Path(directory)
|
|
195
|
+
return path if path.is_absolute() else None
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Private JSON Lines protocol shared by the server and the worker.
|
|
2
|
+
|
|
3
|
+
The wire is deliberately small: one ``ready`` frame, then exactly one reply per
|
|
4
|
+
submitted request. Both ends validate with the same Pydantic models, so framing,
|
|
5
|
+
strict types (``true`` is not ``1``) and size limits cannot drift apart. A
|
|
6
|
+
violation is fatal for the worker: there is no resynchronisation.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Final, Literal, cast
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
|
|
16
|
+
|
|
17
|
+
MAX_FRAME_BYTES: Final = 2 * 1024 * 1024
|
|
18
|
+
MAX_CODE_CHARS: Final = 200_000
|
|
19
|
+
MAX_RESULT_CHARS: Final = 8_192
|
|
20
|
+
MAX_RESULT_JSON_CHARS: Final = 32_768
|
|
21
|
+
MAX_MESSAGE_CHARS: Final = 2_048
|
|
22
|
+
MAX_TRACEBACK_CHARS: Final = 8_192
|
|
23
|
+
MAX_ERROR_TYPE_CHARS: Final = 128
|
|
24
|
+
MAX_FILENAME_CHARS: Final = 4_096
|
|
25
|
+
MAX_ARGV: Final = 65 # argv[0] is the script path
|
|
26
|
+
MAX_ARG_CHARS: Final = 4_096
|
|
27
|
+
MAX_CONTEXT_CHARS: Final = 512
|
|
28
|
+
MAX_CAPTURE_CHARS: Final = 16_384
|
|
29
|
+
CAPTURE_BYTES: Final = MAX_CAPTURE_CHARS * 4 + 16
|
|
30
|
+
_MAX_REPORTED_ERROR_CHARS: Final = 500
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ProtocolError(Exception):
|
|
34
|
+
"""The peer sent something that is not a valid protocol frame."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _Frame(BaseModel):
|
|
38
|
+
"""Strict base: no unknown keys, exact JSON types, no non-finite numbers."""
|
|
39
|
+
|
|
40
|
+
model_config = ConfigDict(extra="forbid", strict=True, frozen=True, allow_inf_nan=False)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _require_utf8(value: str) -> str:
|
|
44
|
+
"""Reject lone surrogates, which JSON permits but UTF-8 cannot encode."""
|
|
45
|
+
try:
|
|
46
|
+
value.encode("utf-8")
|
|
47
|
+
except UnicodeEncodeError as exc:
|
|
48
|
+
raise ValueError("text contains an unpaired surrogate") from exc
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Ready(_Frame):
|
|
53
|
+
type: Literal["ready"]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Request(_Frame):
|
|
57
|
+
id: int = Field(ge=0)
|
|
58
|
+
# File mode is bounded by the encoded frame, not the public cell limit.
|
|
59
|
+
code: str = Field(min_length=1, max_length=MAX_FRAME_BYTES)
|
|
60
|
+
stdout: str
|
|
61
|
+
stderr: str
|
|
62
|
+
mode: Literal["cell", "file"] = "cell"
|
|
63
|
+
filename: str = Field(default="<cell>", max_length=MAX_FILENAME_CHARS)
|
|
64
|
+
argv: list[str] = Field(default_factory=list)
|
|
65
|
+
|
|
66
|
+
@field_validator("code", "stdout", "stderr", "filename")
|
|
67
|
+
@classmethod
|
|
68
|
+
def _text(cls, value: str) -> str:
|
|
69
|
+
return _require_utf8(value)
|
|
70
|
+
|
|
71
|
+
@field_validator("argv")
|
|
72
|
+
@classmethod
|
|
73
|
+
def _arguments(cls, value: list[str]) -> list[str]:
|
|
74
|
+
if len(value) > MAX_ARGV:
|
|
75
|
+
raise ValueError("too many script arguments")
|
|
76
|
+
for item in value:
|
|
77
|
+
if len(item) > MAX_ARG_CHARS:
|
|
78
|
+
raise ValueError("script argument exceeds the size limit")
|
|
79
|
+
_require_utf8(item)
|
|
80
|
+
return value
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class WorkerError(_Frame):
|
|
84
|
+
type: str = Field(min_length=1, max_length=MAX_ERROR_TYPE_CHARS)
|
|
85
|
+
message: str = Field(max_length=MAX_MESSAGE_CHARS)
|
|
86
|
+
traceback: str | None = Field(default=None, max_length=MAX_TRACEBACK_CHARS)
|
|
87
|
+
line: int | None = None
|
|
88
|
+
offset: int | None = None
|
|
89
|
+
context: str | None = Field(default=None, max_length=MAX_CONTEXT_CHARS)
|
|
90
|
+
|
|
91
|
+
@field_validator("type", "message", "traceback", "context")
|
|
92
|
+
@classmethod
|
|
93
|
+
def _text(cls, value: str | None) -> str | None:
|
|
94
|
+
return None if value is None else _require_utf8(value)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Reply(_Frame):
|
|
98
|
+
id: int = Field(ge=0)
|
|
99
|
+
ok: bool
|
|
100
|
+
result: str | None = Field(default=None, max_length=MAX_RESULT_CHARS)
|
|
101
|
+
result_type: str | None = Field(default=None, max_length=MAX_ERROR_TYPE_CHARS)
|
|
102
|
+
result_truncated: bool = False
|
|
103
|
+
result_json: str | None = Field(default=None, max_length=MAX_RESULT_JSON_CHARS)
|
|
104
|
+
stdout: str = Field(default="", max_length=MAX_CAPTURE_CHARS)
|
|
105
|
+
stderr: str = Field(default="", max_length=MAX_CAPTURE_CHARS)
|
|
106
|
+
truncated: bool = False
|
|
107
|
+
capture_complete: bool = True
|
|
108
|
+
error: WorkerError | None = None
|
|
109
|
+
|
|
110
|
+
@field_validator("result", "result_type", "result_json", "stdout", "stderr")
|
|
111
|
+
@classmethod
|
|
112
|
+
def _text(cls, value: str | None) -> str | None:
|
|
113
|
+
return None if value is None else _require_utf8(value)
|
|
114
|
+
|
|
115
|
+
@model_validator(mode="after")
|
|
116
|
+
def _consistent(self) -> Reply:
|
|
117
|
+
if self.ok and self.error is not None:
|
|
118
|
+
raise ValueError("a successful reply cannot carry an error")
|
|
119
|
+
if not self.ok and self.error is None:
|
|
120
|
+
raise ValueError("a failed reply must carry an error")
|
|
121
|
+
return self
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
type Frame = Ready | Request | Reply
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _describe(exc: ValidationError) -> str:
|
|
128
|
+
parts: list[str] = []
|
|
129
|
+
for error in exc.errors():
|
|
130
|
+
path = cast("tuple[object, ...]", error["loc"])
|
|
131
|
+
location = ".".join(str(item) for item in path) or "<frame>"
|
|
132
|
+
parts.append(f"{location}: {error['msg']}")
|
|
133
|
+
return "; ".join(parts)[:_MAX_REPORTED_ERROR_CHARS]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _parse[T: BaseModel](model: type[T], frame: object) -> T:
|
|
137
|
+
try:
|
|
138
|
+
return model.model_validate(frame)
|
|
139
|
+
except ValidationError as exc:
|
|
140
|
+
raise ProtocolError(_describe(exc)) from exc
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def parse_ready(frame: object) -> Ready:
|
|
144
|
+
ready = _parse(Ready, frame)
|
|
145
|
+
if ready.type != "ready": # pragma: no cover - Literal already guarantees it
|
|
146
|
+
raise ProtocolError("first frame must be the ready frame")
|
|
147
|
+
return ready
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def parse_request(frame: object) -> Request:
|
|
151
|
+
return _parse(Request, frame)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def parse_reply(frame: object) -> Reply:
|
|
155
|
+
return _parse(Reply, frame)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def encode_frame(frame: Frame) -> bytes:
|
|
159
|
+
"""Encode one frame, including its terminating LF, or raise ``ProtocolError``."""
|
|
160
|
+
try:
|
|
161
|
+
body = frame.model_dump_json().encode("utf-8")
|
|
162
|
+
except (UnicodeEncodeError, ValueError) as exc:
|
|
163
|
+
raise ProtocolError("frame cannot be encoded") from exc
|
|
164
|
+
if len(body) + 1 > MAX_FRAME_BYTES:
|
|
165
|
+
raise ProtocolError("outgoing frame exceeds the size limit")
|
|
166
|
+
return body + b"\n"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _reject_constant(token: str) -> object:
|
|
170
|
+
raise ValueError(f"non-finite JSON number: {token}")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _decode_line(line: bytes) -> object:
|
|
174
|
+
if not line:
|
|
175
|
+
raise ProtocolError("empty frame")
|
|
176
|
+
if len(line) + 1 > MAX_FRAME_BYTES:
|
|
177
|
+
raise ProtocolError("frame exceeds the size limit")
|
|
178
|
+
try:
|
|
179
|
+
text = line.decode("utf-8")
|
|
180
|
+
except UnicodeDecodeError as exc:
|
|
181
|
+
raise ProtocolError("frame is not valid UTF-8") from exc
|
|
182
|
+
try:
|
|
183
|
+
return json.loads(text, parse_constant=_reject_constant)
|
|
184
|
+
except (ValueError, RecursionError) as exc:
|
|
185
|
+
raise ProtocolError("frame is not valid JSON") from exc
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@dataclass(slots=True)
|
|
189
|
+
class FrameReader:
|
|
190
|
+
"""Incremental line splitter with a hard size limit."""
|
|
191
|
+
|
|
192
|
+
_buffer: bytearray = field(default_factory=bytearray)
|
|
193
|
+
|
|
194
|
+
@property
|
|
195
|
+
def has_partial(self) -> bool:
|
|
196
|
+
return bool(self._buffer)
|
|
197
|
+
|
|
198
|
+
def feed(self, chunk: bytes) -> list[object]:
|
|
199
|
+
self._buffer.extend(chunk)
|
|
200
|
+
frames: list[object] = []
|
|
201
|
+
while True:
|
|
202
|
+
newline = self._buffer.find(b"\n")
|
|
203
|
+
if newline < 0:
|
|
204
|
+
break
|
|
205
|
+
line = bytes(self._buffer[:newline])
|
|
206
|
+
del self._buffer[: newline + 1]
|
|
207
|
+
frames.append(_decode_line(line))
|
|
208
|
+
if len(self._buffer) + 1 > MAX_FRAME_BYTES:
|
|
209
|
+
raise ProtocolError("unterminated frame exceeds the size limit")
|
|
210
|
+
return frames
|