cloudsprite 0.11.0__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.
- cloudsprite/__init__.py +451 -0
- cloudsprite/_antenna.py +83 -0
- cloudsprite/_auth.py +295 -0
- cloudsprite/_client.py +502 -0
- cloudsprite/_config.py +203 -0
- cloudsprite/_consent.py +104 -0
- cloudsprite/_context.py +945 -0
- cloudsprite/_exceptions.py +136 -0
- cloudsprite/_figure_models.py +158 -0
- cloudsprite/_figure_validation.py +168 -0
- cloudsprite/_filter_foster.py +165 -0
- cloudsprite/_filter_synthesis.py +400 -0
- cloudsprite/_filtering.py +134 -0
- cloudsprite/_impedance_matching.py +262 -0
- cloudsprite/_interpolation.py +47 -0
- cloudsprite/_lineage.py +775 -0
- cloudsprite/_link_budget.py +99 -0
- cloudsprite/_logging.py +53 -0
- cloudsprite/_mixed_mode.py +49 -0
- cloudsprite/_monte_carlo.py +193 -0
- cloudsprite/_noise_figure.py +44 -0
- cloudsprite/_pagination.py +130 -0
- cloudsprite/_parsers.py +75 -0
- cloudsprite/_publish.py +162 -0
- cloudsprite/_redact.py +179 -0
- cloudsprite/_response.py +63 -0
- cloudsprite/_resultset.py +65 -0
- cloudsprite/_rf_network.py +111 -0
- cloudsprite/_run_config.py +46 -0
- cloudsprite/_script_runner.py +217 -0
- cloudsprite/_script_workspace.py +271 -0
- cloudsprite/_sparameter_metrics.py +75 -0
- cloudsprite/_tdr.py +283 -0
- cloudsprite/_trace.py +112 -0
- cloudsprite/_version.py +23 -0
- cloudsprite/_visualizer.py +380 -0
- cloudsprite/_visualizer_cli.py +412 -0
- cloudsprite/_visualizer_preview.py +864 -0
- cloudsprite/_work_context.py +116 -0
- cloudsprite/_ws.py +577 -0
- cloudsprite/cli.py +300 -0
- cloudsprite/py.typed +0 -0
- cloudsprite/resources/__init__.py +1 -0
- cloudsprite/resources/_base.py +293 -0
- cloudsprite/resources/_models.py +50 -0
- cloudsprite/resources/cloudscripts.py +173 -0
- cloudsprite/resources/datasets.py +431 -0
- cloudsprite/resources/figures.py +282 -0
- cloudsprite/resources/instruments.py +295 -0
- cloudsprite/resources/notebooks.py +183 -0
- cloudsprite/resources/orbs.py +99 -0
- cloudsprite/resources/parameters.py +77 -0
- cloudsprite/resources/projects.py +182 -0
- cloudsprite/resources/related.py +125 -0
- cloudsprite/resources/reports.py +992 -0
- cloudsprite/resources/search.py +245 -0
- cloudsprite/resources/shares.py +229 -0
- cloudsprite/resources/sprites.py +15 -0
- cloudsprite/resources/tags.py +107 -0
- cloudsprite/resources/teams.py +86 -0
- cloudsprite/resources/traces.py +147 -0
- cloudsprite/resources/usage.py +152 -0
- cloudsprite/resources/visualizer_templates.py +466 -0
- cloudsprite/resources/workflows.py +59 -0
- cloudsprite-0.11.0.dist-info/METADATA +358 -0
- cloudsprite-0.11.0.dist-info/RECORD +70 -0
- cloudsprite-0.11.0.dist-info/WHEEL +5 -0
- cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
- cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
- cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Batch/Celery entrypoint: fetch the run manifest and exec the stored script.
|
|
2
|
+
|
|
3
|
+
Invoked as ``cloudsprite-script-runner``. Env contract:
|
|
4
|
+
|
|
5
|
+
- ``CS_RUN_ID``
|
|
6
|
+
- ``CS_RUN_TOKEN``
|
|
7
|
+
- ``CS_RUN_MANIFEST_URL``
|
|
8
|
+
- ``CS_API_BASE_URL``
|
|
9
|
+
- ``CS_RUNTIME_LABEL``
|
|
10
|
+
|
|
11
|
+
The manifest's ``org_slug`` / ``team_slug`` / ``project_slug`` become the script's
|
|
12
|
+
default SDK context via ``CLOUDSPRITE_ORG`` / ``CLOUDSPRITE_TEAM`` /
|
|
13
|
+
``CLOUDSPRITE_PROJECT`` (an explicit ``cs.set_team(...)`` in the script still wins).
|
|
14
|
+
The manifest ids (``org_id`` / ``team_id`` / ``project_id``) go in ``CLOUDSPRITE_*_ID`` so the
|
|
15
|
+
SDK needs no tenant/team/project lookups, which run tokens cannot make.
|
|
16
|
+
|
|
17
|
+
The user script is executed with ``python -I`` so ``import cloudsprite as cs``
|
|
18
|
+
authenticates via ``CS_RUN_TOKEN`` (no personal API key). Never log the token
|
|
19
|
+
or presigned URLs.
|
|
20
|
+
|
|
21
|
+
A run of a repo-managed script also carries a manifest ``workspace`` (the repository at the
|
|
22
|
+
script version's commit). The runner then downloads, verifies and unpacks it into
|
|
23
|
+
``<workdir>/workspace`` and starts the script from there, with the root on ``sys.path``
|
|
24
|
+
(see ``_script_workspace``). Without one, behaviour is as before.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import contextlib
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import subprocess
|
|
33
|
+
import sys
|
|
34
|
+
import tempfile
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import Any, cast
|
|
37
|
+
|
|
38
|
+
import requests as req
|
|
39
|
+
|
|
40
|
+
from cloudsprite._auth import AuthManager
|
|
41
|
+
from cloudsprite._config import Config
|
|
42
|
+
from cloudsprite._exceptions import AuthError, CloudSpriteError
|
|
43
|
+
from cloudsprite._response import parse_json_response
|
|
44
|
+
from cloudsprite._script_workspace import (
|
|
45
|
+
Workspace,
|
|
46
|
+
WorkspaceError,
|
|
47
|
+
bootstrap_command,
|
|
48
|
+
download_archive,
|
|
49
|
+
parse_workspace,
|
|
50
|
+
resolve_inside,
|
|
51
|
+
unpack_archive,
|
|
52
|
+
verify_archive,
|
|
53
|
+
workspace_os_error,
|
|
54
|
+
)
|
|
55
|
+
from cloudsprite._version import sdk_version
|
|
56
|
+
|
|
57
|
+
_MANIFEST_PATH = "/api/script-runner/manifest/"
|
|
58
|
+
_CONTEXT_ENV = {
|
|
59
|
+
"org_slug": "CLOUDSPRITE_ORG",
|
|
60
|
+
"team_slug": "CLOUDSPRITE_TEAM",
|
|
61
|
+
"project_slug": "CLOUDSPRITE_PROJECT",
|
|
62
|
+
# Ids seed the SDK's caches: run tokens can't list tenants/teams/projects.
|
|
63
|
+
# org_id is absent from older manifests; it is skipped when missing.
|
|
64
|
+
"org_id": "CLOUDSPRITE_ORG_ID",
|
|
65
|
+
"team_id": "CLOUDSPRITE_TEAM_ID",
|
|
66
|
+
"project_id": "CLOUDSPRITE_PROJECT_ID",
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _context_env(manifest: dict[str, Any]) -> dict[str, str]:
|
|
71
|
+
"""Map manifest org/team/project slugs and ids to the SDK's default-context env vars."""
|
|
72
|
+
out: dict[str, str] = {}
|
|
73
|
+
for key, env_name in _CONTEXT_ENV.items():
|
|
74
|
+
value = manifest.get(key)
|
|
75
|
+
if isinstance(value, str) and value.strip():
|
|
76
|
+
out[env_name] = value.strip()
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _base_url() -> str:
|
|
81
|
+
explicit = os.environ.get("CS_API_BASE_URL", "").strip()
|
|
82
|
+
if explicit:
|
|
83
|
+
return explicit.rstrip("/")
|
|
84
|
+
manifest = os.environ.get("CS_RUN_MANIFEST_URL", "").strip()
|
|
85
|
+
api_marker = "/api" + "/"
|
|
86
|
+
if api_marker in manifest:
|
|
87
|
+
return manifest.split(api_marker, 1)[0].rstrip("/")
|
|
88
|
+
raise CloudSpriteError("CS_API_BASE_URL is required for cloudsprite-script-runner")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _fetch_manifest(base_url: str, token: str) -> dict[str, Any]:
|
|
92
|
+
insecure = base_url.startswith("http://")
|
|
93
|
+
config = Config(api_key=None, base_url=base_url, allow_insecure=insecure)
|
|
94
|
+
auth = AuthManager(config)
|
|
95
|
+
auth.authenticate_run_token(token)
|
|
96
|
+
url = f"{base_url}{_MANIFEST_PATH}"
|
|
97
|
+
headers = {
|
|
98
|
+
"User-Agent": f"cloudsprite-python/{sdk_version()}",
|
|
99
|
+
"Authorization": f"Bearer {auth.access_token}",
|
|
100
|
+
}
|
|
101
|
+
try:
|
|
102
|
+
resp = req.get(url, headers=headers, timeout=(5.0, 60.0))
|
|
103
|
+
except req.RequestException as exc:
|
|
104
|
+
raise CloudSpriteError(f"Failed to fetch run manifest: {exc}") from exc
|
|
105
|
+
if resp.status_code in (401, 403):
|
|
106
|
+
raise AuthError("Run token was rejected fetching the manifest")
|
|
107
|
+
if resp.status_code >= 400:
|
|
108
|
+
raise CloudSpriteError(f"Manifest fetch failed ({resp.status_code})")
|
|
109
|
+
data = parse_json_response(resp, _MANIFEST_PATH)
|
|
110
|
+
if not isinstance(data, dict):
|
|
111
|
+
raise CloudSpriteError("Manifest response was not an object")
|
|
112
|
+
return cast(dict[str, Any], data)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _download_script(script_url: str, dest: Path) -> None:
|
|
116
|
+
try:
|
|
117
|
+
resp = req.get(script_url, timeout=(5.0, 120.0))
|
|
118
|
+
except req.RequestException as exc:
|
|
119
|
+
raise CloudSpriteError(f"Failed to download script: {exc}") from exc
|
|
120
|
+
if resp.status_code >= 400:
|
|
121
|
+
raise CloudSpriteError(f"Script download failed ({resp.status_code})")
|
|
122
|
+
dest.write_bytes(resp.content)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _prepare_workspace(ws: Workspace, root: Path, workdir: Path) -> Path:
|
|
126
|
+
"""Download, verify and unpack the workspace into ``root``; return where the script goes."""
|
|
127
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
128
|
+
if any(root.iterdir()):
|
|
129
|
+
raise CloudSpriteError(f"Workspace directory is not empty: {root}")
|
|
130
|
+
fd, archive_name = tempfile.mkstemp(dir=workdir, prefix="workspace-", suffix=".tar.gz")
|
|
131
|
+
os.close(fd)
|
|
132
|
+
archive = Path(archive_name)
|
|
133
|
+
try:
|
|
134
|
+
download_archive(ws.url, ws.size_bytes, archive)
|
|
135
|
+
verify_archive(archive, sha256=ws.sha256, size_bytes=ws.size_bytes)
|
|
136
|
+
unpack_archive(archive, root, max_files=ws.max_files, max_extracted_bytes=ws.max_extracted_bytes)
|
|
137
|
+
finally:
|
|
138
|
+
with contextlib.suppress(OSError):
|
|
139
|
+
archive.unlink()
|
|
140
|
+
script = resolve_inside(root, ws.script_path)
|
|
141
|
+
script.parent.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
if script.is_dir():
|
|
143
|
+
raise WorkspaceError("WORKSPACE_UNSAFE_PATH", "workspace contains an unsafe path")
|
|
144
|
+
return script
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _workspace_failed(exc: WorkspaceError) -> int:
|
|
148
|
+
print(f"workspace error {exc.code}: {exc.message}", file=sys.stderr)
|
|
149
|
+
return 1
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _run_with_workspace(manifest: dict[str, Any], script_url: str, workdir: Path, raw_workspace: object) -> int:
|
|
153
|
+
"""H1 contract steps 1 to 7: the repository is the script's working tree."""
|
|
154
|
+
root = workdir / "workspace"
|
|
155
|
+
try:
|
|
156
|
+
ws = parse_workspace(raw_workspace)
|
|
157
|
+
script = _prepare_workspace(ws, root, workdir)
|
|
158
|
+
# The version's content, not the archive's file, is what runs.
|
|
159
|
+
_download_script(script_url, script)
|
|
160
|
+
config = manifest.get("config") or {}
|
|
161
|
+
if config:
|
|
162
|
+
(root / "cs_run_config.json").write_text(json.dumps(config), encoding="utf-8")
|
|
163
|
+
except WorkspaceError as exc:
|
|
164
|
+
return _workspace_failed(exc)
|
|
165
|
+
except OSError as exc:
|
|
166
|
+
# Local I/O (path too long, full disk): a contract code where one fits, else one line.
|
|
167
|
+
err = workspace_os_error(exc)
|
|
168
|
+
if isinstance(err, WorkspaceError):
|
|
169
|
+
return _workspace_failed(err)
|
|
170
|
+
raise err from None
|
|
171
|
+
env = os.environ.copy()
|
|
172
|
+
env.update(_context_env(manifest))
|
|
173
|
+
# ``-I`` ignores PYTHONPATH for the script itself; the bootstrap puts the root on sys.path.
|
|
174
|
+
# Setting it keeps the root importable for interpreters the script starts.
|
|
175
|
+
env["PYTHONPATH"] = os.pathsep.join(p for p in (str(root), env.get("PYTHONPATH", "")) if p)
|
|
176
|
+
result = subprocess.run(bootstrap_command(script, root), cwd=str(root), env=env, check=False)
|
|
177
|
+
return int(result.returncode)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def run(argv: list[str] | None = None) -> int: # noqa: ARG001
|
|
181
|
+
token = os.environ.get("CS_RUN_TOKEN", "").strip()
|
|
182
|
+
if not token:
|
|
183
|
+
print("CS_RUN_TOKEN is required", file=sys.stderr)
|
|
184
|
+
return 2
|
|
185
|
+
try:
|
|
186
|
+
base = _base_url()
|
|
187
|
+
manifest = _fetch_manifest(base, token)
|
|
188
|
+
script_url = manifest.get("script_url")
|
|
189
|
+
if not isinstance(script_url, str) or not script_url:
|
|
190
|
+
raise CloudSpriteError("Manifest missing script_url")
|
|
191
|
+
workdir = Path(os.environ.get("TMPDIR") or os.environ.get("HOME") or ".")
|
|
192
|
+
workdir.mkdir(parents=True, exist_ok=True)
|
|
193
|
+
raw_workspace = manifest.get("workspace")
|
|
194
|
+
if raw_workspace is not None:
|
|
195
|
+
return _run_with_workspace(manifest, script_url, workdir, raw_workspace)
|
|
196
|
+
entry = manifest.get("entrypoint") or "script.py"
|
|
197
|
+
script_path = workdir / Path(str(entry)).name
|
|
198
|
+
_download_script(script_url, script_path)
|
|
199
|
+
config = manifest.get("config") or {}
|
|
200
|
+
if config:
|
|
201
|
+
(workdir / "cs_run_config.json").write_text(json.dumps(config), encoding="utf-8")
|
|
202
|
+
env = os.environ.copy()
|
|
203
|
+
env.update(_context_env(manifest))
|
|
204
|
+
result = subprocess.run(
|
|
205
|
+
[sys.executable, "-I", str(script_path)],
|
|
206
|
+
cwd=str(workdir),
|
|
207
|
+
env=env,
|
|
208
|
+
check=False,
|
|
209
|
+
)
|
|
210
|
+
return int(result.returncode)
|
|
211
|
+
except (AuthError, CloudSpriteError) as exc:
|
|
212
|
+
print(str(exc), file=sys.stderr)
|
|
213
|
+
return 1
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def main() -> None:
|
|
217
|
+
sys.exit(run())
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Repository workspace for the Batch script runner.
|
|
2
|
+
|
|
3
|
+
A server run of a repo-managed script carries a ``workspace`` object in its manifest: a
|
|
4
|
+
presigned URL for a ``tar.gz`` of the repository at the script version's commit. The runner
|
|
5
|
+
downloads it, verifies it, unpacks it traversal-safely into a root directory, and starts the
|
|
6
|
+
script from that root. The archive is untrusted: this module re-enforces every limit.
|
|
7
|
+
|
|
8
|
+
Failures raise :class:`WorkspaceError` carrying a contract code (``WORKSPACE_*``). Messages
|
|
9
|
+
never contain the presigned URL.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import errno
|
|
15
|
+
import gzip
|
|
16
|
+
import hashlib
|
|
17
|
+
import os
|
|
18
|
+
import stat
|
|
19
|
+
import sys
|
|
20
|
+
import tarfile
|
|
21
|
+
import zlib
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import requests as req
|
|
27
|
+
from urllib3.exceptions import HTTPError as Urllib3HTTPError
|
|
28
|
+
|
|
29
|
+
from cloudsprite._exceptions import CloudSpriteError
|
|
30
|
+
|
|
31
|
+
_CHUNK = 64 * 1024
|
|
32
|
+
_MAX_NAME_BYTES = 1024
|
|
33
|
+
# A pax or GNU long-name header holds a path and a few records; tarfile reads it into memory
|
|
34
|
+
# whole, sized by the header itself, so an archive could ask for gigabytes.
|
|
35
|
+
_MAX_HEADER_BYTES = 64 * 1024
|
|
36
|
+
# Errnos that mean the path the archive asked for cannot exist on this filesystem.
|
|
37
|
+
_PATH_ERRNOS = frozenset(
|
|
38
|
+
{errno.ENAMETOOLONG, errno.EILSEQ, errno.EINVAL, errno.ELOOP, errno.EEXIST, errno.ENOTDIR, errno.EISDIR}
|
|
39
|
+
)
|
|
40
|
+
_SPACE_ERRNOS = frozenset(e for e in (errno.ENOSPC, getattr(errno, "EDQUOT", None), errno.EFBIG) if e is not None)
|
|
41
|
+
_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
|
|
42
|
+
|
|
43
|
+
# Exact text from the contract; ``python -I`` ignores PYTHONPATH and the script directory,
|
|
44
|
+
# so the script's directory and the root are put on sys.path here, and the script runs
|
|
45
|
+
# as ``__main__`` with ``__file__`` and ``sys.argv[0]`` set to its path.
|
|
46
|
+
BOOTSTRAP = (
|
|
47
|
+
"import runpy, sys, os; s = sys.argv[1]; r = sys.argv[2]; "
|
|
48
|
+
"sys.path[:0] = [d for d in dict.fromkeys([os.path.dirname(s), r])]; "
|
|
49
|
+
"sys.argv = [s] + sys.argv[3:]; runpy.run_path(s, run_name='__main__')"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class WorkspaceError(Exception):
|
|
54
|
+
"""A workspace failure with its contract error code."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, code: str, message: str) -> None:
|
|
57
|
+
super().__init__(message)
|
|
58
|
+
self.code = code
|
|
59
|
+
self.message = message
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def workspace_os_error(exc: OSError) -> Exception:
|
|
63
|
+
"""Map a local I/O error to the closest contract code, or a one-line ``CloudSpriteError``.
|
|
64
|
+
|
|
65
|
+
A path the filesystem rejects is ``WORKSPACE_UNSAFE_PATH``; a full disk or quota is
|
|
66
|
+
``WORKSPACE_EXTRACTED_TOO_LARGE``. The contract has no code for other I/O failures, so those
|
|
67
|
+
become a plain run error (exit 1, one line) rather than a traceback. The message names the
|
|
68
|
+
errno only: paths and URLs stay out of it.
|
|
69
|
+
"""
|
|
70
|
+
if exc.errno in _PATH_ERRNOS:
|
|
71
|
+
return WorkspaceError("WORKSPACE_UNSAFE_PATH", "workspace contains an unsafe path")
|
|
72
|
+
if exc.errno in _SPACE_ERRNOS:
|
|
73
|
+
return WorkspaceError("WORKSPACE_EXTRACTED_TOO_LARGE", "workspace does not fit on the runner's disk")
|
|
74
|
+
name = errno.errorcode.get(exc.errno or 0, type(exc).__name__)
|
|
75
|
+
return CloudSpriteError(f"Failed to write the workspace ({name})")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class _BoundedTarInfo(tarfile.TarInfo):
|
|
79
|
+
"""``TarInfo`` that refuses oversized pax and GNU long-name headers before reading them."""
|
|
80
|
+
|
|
81
|
+
def _check_header(self) -> None:
|
|
82
|
+
if self.size > _MAX_HEADER_BYTES:
|
|
83
|
+
raise WorkspaceError("WORKSPACE_ARCHIVE_INVALID", "workspace archive is not a valid tar.gz")
|
|
84
|
+
|
|
85
|
+
def _proc_gnulong(self, tarfile: Any) -> Any:
|
|
86
|
+
self._check_header()
|
|
87
|
+
return super()._proc_gnulong(tarfile) # type: ignore[misc]
|
|
88
|
+
|
|
89
|
+
def _proc_pax(self, tarfile: Any) -> Any:
|
|
90
|
+
self._check_header()
|
|
91
|
+
return super()._proc_pax(tarfile) # type: ignore[misc]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class Workspace:
|
|
96
|
+
url: str
|
|
97
|
+
sha256: str
|
|
98
|
+
size_bytes: int
|
|
99
|
+
script_path: str
|
|
100
|
+
max_files: int
|
|
101
|
+
max_extracted_bytes: int
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _manifest_int(raw: dict[str, Any], field: str) -> int:
|
|
105
|
+
value = raw.get(field)
|
|
106
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
107
|
+
raise CloudSpriteError(f"Manifest workspace.{field} must be a non-negative integer")
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _manifest_str(raw: dict[str, Any], field: str, *, allow_empty: bool = False) -> str:
|
|
112
|
+
value = raw.get(field)
|
|
113
|
+
if not isinstance(value, str) or not (value or allow_empty):
|
|
114
|
+
raise CloudSpriteError(f"Manifest workspace.{field} must be a non-empty string")
|
|
115
|
+
return value
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def parse_workspace(raw: object) -> Workspace:
|
|
119
|
+
"""Validate the manifest's ``workspace`` object.
|
|
120
|
+
|
|
121
|
+
A malformed object is a manifest error (``CloudSpriteError``); the contract has no code for
|
|
122
|
+
it. An unknown archive format is ``WORKSPACE_ARCHIVE_INVALID``; an unsafe ``script_path`` is
|
|
123
|
+
``WORKSPACE_UNSAFE_PATH``.
|
|
124
|
+
"""
|
|
125
|
+
if not isinstance(raw, dict):
|
|
126
|
+
raise CloudSpriteError("Manifest workspace was not an object")
|
|
127
|
+
fmt = raw.get("format", "tar.gz")
|
|
128
|
+
if fmt != "tar.gz":
|
|
129
|
+
raise WorkspaceError("WORKSPACE_ARCHIVE_INVALID", f"unsupported workspace format {fmt!r}")
|
|
130
|
+
ws = Workspace(
|
|
131
|
+
url=_manifest_str(raw, "url"),
|
|
132
|
+
sha256=_manifest_str(raw, "sha256").lower(),
|
|
133
|
+
size_bytes=_manifest_int(raw, "size_bytes"),
|
|
134
|
+
script_path=_manifest_str(raw, "script_path", allow_empty=True),
|
|
135
|
+
max_files=_manifest_int(raw, "max_files"),
|
|
136
|
+
max_extracted_bytes=_manifest_int(raw, "max_extracted_bytes"),
|
|
137
|
+
)
|
|
138
|
+
validate_member_name(ws.script_path)
|
|
139
|
+
return ws
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def validate_member_name(name: str) -> None:
|
|
143
|
+
"""Raise ``WORKSPACE_UNSAFE_PATH`` unless ``name`` is a plain repo-relative POSIX path."""
|
|
144
|
+
unsafe = WorkspaceError("WORKSPACE_UNSAFE_PATH", "workspace contains an unsafe path")
|
|
145
|
+
if not name or name.startswith("/") or "\\" in name or "\0" in name:
|
|
146
|
+
raise unsafe
|
|
147
|
+
if len(name.encode("utf-8", "surrogateescape")) > _MAX_NAME_BYTES:
|
|
148
|
+
raise unsafe
|
|
149
|
+
if any(part in ("", ".", "..") for part in name.split("/")):
|
|
150
|
+
raise unsafe
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def resolve_inside(root: Path, name: str) -> Path:
|
|
154
|
+
"""Destination for ``name`` under ``root``; ``WORKSPACE_UNSAFE_PATH`` if it resolves outside."""
|
|
155
|
+
validate_member_name(name)
|
|
156
|
+
root_real = Path(os.path.realpath(root))
|
|
157
|
+
dest = Path(os.path.realpath(root_real / name))
|
|
158
|
+
if root_real != dest and root_real not in dest.parents:
|
|
159
|
+
raise WorkspaceError("WORKSPACE_UNSAFE_PATH", "workspace contains an unsafe path")
|
|
160
|
+
return dest
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def download_archive(url: str, size_bytes: int, dest: Path) -> None:
|
|
164
|
+
"""Stream ``url`` to ``dest``, reading at most ``size_bytes`` + 1 bytes.
|
|
165
|
+
|
|
166
|
+
The extra byte lets :func:`verify_archive` see an oversized body as a length mismatch
|
|
167
|
+
without ever buffering the rest of it.
|
|
168
|
+
"""
|
|
169
|
+
limit = size_bytes + 1
|
|
170
|
+
written = 0
|
|
171
|
+
try:
|
|
172
|
+
with req.get(url, stream=True, timeout=(5.0, 120.0)) as resp:
|
|
173
|
+
if resp.status_code >= 400:
|
|
174
|
+
raise WorkspaceError("WORKSPACE_DOWNLOAD_FAILED", f"download failed (HTTP {resp.status_code})")
|
|
175
|
+
with dest.open("wb") as out:
|
|
176
|
+
# Raw bytes: the checksum is of the object, so a Content-Encoding must not be undone.
|
|
177
|
+
for chunk in resp.raw.stream(_CHUNK, decode_content=False):
|
|
178
|
+
take = chunk[: limit - written]
|
|
179
|
+
out.write(take)
|
|
180
|
+
written += len(take)
|
|
181
|
+
if written >= limit:
|
|
182
|
+
break
|
|
183
|
+
except (req.RequestException, Urllib3HTTPError, OSError) as exc:
|
|
184
|
+
# The exception text carries the presigned URL: name the type only. A failed write of the
|
|
185
|
+
# temp file (full disk) lands here too.
|
|
186
|
+
raise WorkspaceError("WORKSPACE_DOWNLOAD_FAILED", f"download failed ({type(exc).__name__})") from None
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def verify_archive(path: Path, *, sha256: str, size_bytes: int) -> None:
|
|
190
|
+
"""Check the downloaded archive's length and sha256 against the manifest."""
|
|
191
|
+
digest = hashlib.sha256()
|
|
192
|
+
length = 0
|
|
193
|
+
with path.open("rb") as fh:
|
|
194
|
+
for chunk in iter(lambda: fh.read(_CHUNK), b""):
|
|
195
|
+
digest.update(chunk)
|
|
196
|
+
length += len(chunk)
|
|
197
|
+
if length != size_bytes:
|
|
198
|
+
raise WorkspaceError("WORKSPACE_CHECKSUM_MISMATCH", "workspace archive size does not match the manifest")
|
|
199
|
+
if digest.hexdigest() != sha256:
|
|
200
|
+
raise WorkspaceError("WORKSPACE_CHECKSUM_MISMATCH", "workspace archive checksum does not match the manifest")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _has_git_component(name: str) -> bool:
|
|
204
|
+
return ".git" in name.split("/")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _write_member(src: Any, dest: Path, mode: int, budget: int) -> int:
|
|
208
|
+
"""Write ``src`` to a new file at ``dest``; return bytes written, never more than ``budget``."""
|
|
209
|
+
dest.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
|
|
210
|
+
# O_EXCL: a repeated path, or a file where a directory is needed (or the reverse), fails
|
|
211
|
+
# here and is reported as an unsafe path by ``workspace_os_error``.
|
|
212
|
+
fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW, mode)
|
|
213
|
+
written = 0
|
|
214
|
+
with os.fdopen(fd, "wb") as out:
|
|
215
|
+
while True:
|
|
216
|
+
chunk = src.read(min(_CHUNK, budget - written + 1))
|
|
217
|
+
if not chunk:
|
|
218
|
+
break
|
|
219
|
+
if written + len(chunk) > budget:
|
|
220
|
+
raise WorkspaceError("WORKSPACE_EXTRACTED_TOO_LARGE", "workspace is larger than the extraction limit")
|
|
221
|
+
out.write(chunk)
|
|
222
|
+
written += len(chunk)
|
|
223
|
+
os.chmod(dest, mode)
|
|
224
|
+
return written
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def unpack_archive(archive: Path, root: Path, *, max_files: int, max_extracted_bytes: int) -> None:
|
|
228
|
+
"""Unpack the ``tar.gz`` at ``archive`` into ``root`` member by member (no ``extractall``).
|
|
229
|
+
|
|
230
|
+
Only regular files are written; symlinks, hardlinks, devices, fifos, directories and any
|
|
231
|
+
path with a ``.git`` component are skipped. Unsafe names, repeats, and limit overruns fail
|
|
232
|
+
the whole workspace with the contract code.
|
|
233
|
+
"""
|
|
234
|
+
seen: set[str] = set()
|
|
235
|
+
files = 0
|
|
236
|
+
total = 0
|
|
237
|
+
members = 0
|
|
238
|
+
# Skipped members (links, directories, .git) are not files, but each still costs a header:
|
|
239
|
+
# bound them too. A legitimate server archive holds regular files only.
|
|
240
|
+
member_cap = 2 * max_files + 1000
|
|
241
|
+
try:
|
|
242
|
+
with archive.open("rb") as fh, tarfile.open(fileobj=fh, mode="r|gz", tarinfo=_BoundedTarInfo) as tar:
|
|
243
|
+
for member in tar:
|
|
244
|
+
# Streaming mode still keeps every TarInfo in ``tar.members``; this is not random access.
|
|
245
|
+
tar.members.clear() # type: ignore[attr-defined]
|
|
246
|
+
members += 1
|
|
247
|
+
if members > member_cap:
|
|
248
|
+
raise WorkspaceError("WORKSPACE_TOO_MANY_FILES", "workspace has too many files")
|
|
249
|
+
if not member.isreg() or _has_git_component(member.name):
|
|
250
|
+
continue
|
|
251
|
+
dest = resolve_inside(root, member.name)
|
|
252
|
+
if member.name in seen:
|
|
253
|
+
raise WorkspaceError("WORKSPACE_UNSAFE_PATH", "workspace contains an unsafe path")
|
|
254
|
+
seen.add(member.name)
|
|
255
|
+
files += 1
|
|
256
|
+
if files > max_files:
|
|
257
|
+
raise WorkspaceError("WORKSPACE_TOO_MANY_FILES", "workspace has too many files")
|
|
258
|
+
src = tar.extractfile(member)
|
|
259
|
+
if src is None:
|
|
260
|
+
continue
|
|
261
|
+
mode = 0o755 if member.mode & stat.S_IXUSR else 0o644
|
|
262
|
+
total += _write_member(src, dest, mode, max_extracted_bytes - total)
|
|
263
|
+
except (tarfile.TarError, EOFError, zlib.error, gzip.BadGzipFile):
|
|
264
|
+
raise WorkspaceError("WORKSPACE_ARCHIVE_INVALID", "workspace archive is not a valid tar.gz") from None
|
|
265
|
+
except OSError as exc:
|
|
266
|
+
raise workspace_os_error(exc) from None
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def bootstrap_command(script: Path, root: Path) -> list[str]:
|
|
270
|
+
"""Child command for a workspace run: ``python -I`` plus the contract bootstrap."""
|
|
271
|
+
return [sys.executable, "-I", "-c", BOOTSTRAP, str(script), str(root)]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Frequency-resolved S-parameter metrics backed by scikit-rf."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from numpy.typing import NDArray
|
|
9
|
+
|
|
10
|
+
from cloudsprite._rf_network import NetworkInput, _network
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class SParameterMetrics:
|
|
15
|
+
"""S-parameter results, with zero-based port indices and frequency first.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
frequency_hz: Frequency vector, shape (F,).
|
|
19
|
+
vswr: Reflection VSWR, shape (F, P), from the diagonal of s_vswr.
|
|
20
|
+
Reflection magnitude above one follows scikit-rf's algebraic
|
|
21
|
+
result (negative, not a physical passive-line VSWR).
|
|
22
|
+
return_loss_db: Negative reflection s_db, shape (F, P).
|
|
23
|
+
insertion_loss_db: Negative s_db, shape (F, P, P); use [:, 1, 0]
|
|
24
|
+
for forward two-port insertion loss. Diagonal entries are return loss.
|
|
25
|
+
Assumes matched reference terminations, not transducer gain.
|
|
26
|
+
group_delay_s: Group delay in seconds, shape (F, P, P). NaN where
|
|
27
|
+
transmission/reflection is zero or only one frequency is available.
|
|
28
|
+
stability_k: Rollett K, shape (F,), or None unless there are two ports.
|
|
29
|
+
delta: Complex S-matrix determinant, shape (F,), or None unless two-port.
|
|
30
|
+
Unconditional small-signal stability requires K > 1 and abs(delta) < 1.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
frequency_hz: NDArray[np.float64]
|
|
34
|
+
vswr: NDArray[np.float64]
|
|
35
|
+
return_loss_db: NDArray[np.float64]
|
|
36
|
+
insertion_loss_db: NDArray[np.float64]
|
|
37
|
+
group_delay_s: NDArray[np.float64]
|
|
38
|
+
stability_k: NDArray[np.float64] | None
|
|
39
|
+
delta: NDArray[np.complex128] | None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def sparameter_metrics(network: NetworkInput) -> SParameterMetrics:
|
|
43
|
+
"""Compute metrics from a Network or local Touchstone path without mutation.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
network: Full complex scikit-rf Network or local Touchstone file. A
|
|
47
|
+
``Trace.to_network()`` result is accepted, but that conversion creates
|
|
48
|
+
a magnitude-only one-port: it cannot recover phase or two-port K.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
SParameterMetrics with independent numpy arrays. Infinite loss at zero
|
|
52
|
+
magnitude is retained. K uses scikit-rf's stability property. Zero coupling yields +inf
|
|
53
|
+
K, following scikit-rf. Group delay requires adequately sampled phase.
|
|
54
|
+
Requires ``pip install cloudsprite[rf]``.
|
|
55
|
+
"""
|
|
56
|
+
n = _network(network)
|
|
57
|
+
delta = None
|
|
58
|
+
k = None
|
|
59
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
60
|
+
loss = -np.asarray(n.s_db, dtype=np.float64).copy()
|
|
61
|
+
vswr = np.diagonal(n.s_vswr, axis1=1, axis2=2).copy()
|
|
62
|
+
delay = np.asarray(n.group_delay.real, dtype=np.float64).copy() if len(n.f) > 1 else np.full(n.s.shape, np.nan)
|
|
63
|
+
delay[np.abs(n.s) == 0] = np.nan
|
|
64
|
+
if n.nports == 2:
|
|
65
|
+
delta = np.asarray(n.s[:, 0, 0] * n.s[:, 1, 1] - n.s[:, 0, 1] * n.s[:, 1, 0], dtype=np.complex128)
|
|
66
|
+
k = np.asarray(n.stability, dtype=np.float64).copy()
|
|
67
|
+
return SParameterMetrics(
|
|
68
|
+
np.asarray(n.f, dtype=np.float64).copy(),
|
|
69
|
+
vswr,
|
|
70
|
+
np.diagonal(loss, axis1=1, axis2=2).copy(),
|
|
71
|
+
loss,
|
|
72
|
+
delay,
|
|
73
|
+
k,
|
|
74
|
+
delta,
|
|
75
|
+
)
|