codecop 0.1.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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
"""The runtimes a call shape is replayed on: CPython (with the HTTP library the repository names), Node and Go. Each
|
|
2
|
+
harness is a small program of CodeCop's own (`runners/`) run in a child process with a hard timeout; it gets one JSON
|
|
3
|
+
request and answers one JSON line. Nothing of the repository is run.
|
|
4
|
+
|
|
5
|
+
- Python: the interpreter in `[kinds.calls] python`, else CodeCop's own. A library the interpreter lacks (requests, httpx,
|
|
6
|
+
aiohttp, redis) is installed once into a venv in CodeCop's cache when `provision` is on (the default), at the version
|
|
7
|
+
the repository pins when it pins one; otherwise the library is "not available" and its sites are "could not be
|
|
8
|
+
judged: runtime not available".
|
|
9
|
+
- Node: `node` on PATH (built-in modules only).
|
|
10
|
+
- Go: the local toolchain builds `run_go.go` once into the cache (standard library only, offline).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from .standin import cache_dir
|
|
27
|
+
|
|
28
|
+
HERE = Path(__file__).parent / "runners"
|
|
29
|
+
HARNESS_VERSION = "1"
|
|
30
|
+
PY_LIBS = ("requests", "httpx", "aiohttp", "redis", "boto3")
|
|
31
|
+
NODE_PKGS = ("axios", "ioredis")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Unavailable(RuntimeError):
|
|
35
|
+
"""The runtime or library is not on this machine."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def pinned_versions(root: Path) -> dict[str, str]:
|
|
39
|
+
"""The versions the repository pins for the replayed libraries ({name: version}), from requirements files, uv.lock,
|
|
40
|
+
poetry.lock or pyproject.toml. Exact pins only."""
|
|
41
|
+
out: dict[str, str] = {}
|
|
42
|
+
names = "|".join(PY_LIBS)
|
|
43
|
+
root = Path(root)
|
|
44
|
+
cands = [p for pat in ("requirements*.txt", "*/requirements*.txt", "pyproject.toml", "*/pyproject.toml") for p in root.glob(pat)]
|
|
45
|
+
for p in cands[:40]:
|
|
46
|
+
try:
|
|
47
|
+
text = p.read_text(errors="replace")
|
|
48
|
+
except OSError:
|
|
49
|
+
continue
|
|
50
|
+
for m in re.finditer(rf"(?im)^\s*[\"']?({names})(?:\[[^\]]*\])?\s*==\s*([0-9][0-9A-Za-z.\-]*)", text):
|
|
51
|
+
out.setdefault(m.group(1).lower(), m.group(2))
|
|
52
|
+
for lock in ("uv.lock", "poetry.lock"):
|
|
53
|
+
p = root / lock
|
|
54
|
+
try:
|
|
55
|
+
text = p.read_text(errors="replace")
|
|
56
|
+
except OSError:
|
|
57
|
+
continue
|
|
58
|
+
for m in re.finditer(rf'(?m)^name = "({names})"\s*\nversion = "([^"]+)"', text):
|
|
59
|
+
out.setdefault(m.group(1).lower(), m.group(2))
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
RUST_TOML = ('[package]\nname = "codecop-calls-harness"\nversion = "0.1.0"\nedition = "2021"\n\n[dependencies]\n'
|
|
64
|
+
'reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }\n'
|
|
65
|
+
'tokio = { version = "1", features = ["full"] }\nredis = { version = "0.32", default-features = false }\n'
|
|
66
|
+
'serde_json = "1"\n\n[profile.release]\nopt-level = 2\n')
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def node_pins(root: Path) -> dict[str, str]:
|
|
70
|
+
"""The version ranges package.json files name for the replayed Node packages."""
|
|
71
|
+
out: dict[str, str] = {}
|
|
72
|
+
for p in [Path(root) / "package.json"] + list(Path(root).glob("*/package.json"))[:20]:
|
|
73
|
+
try:
|
|
74
|
+
doc = json.loads(p.read_text())
|
|
75
|
+
except (OSError, ValueError):
|
|
76
|
+
continue
|
|
77
|
+
for sec in ("dependencies", "devDependencies"):
|
|
78
|
+
for name in NODE_PKGS:
|
|
79
|
+
v = (doc.get(sec) or {}).get(name)
|
|
80
|
+
if isinstance(v, str) and re.fullmatch(r"[\^~]?\d[\w.\-]*", v):
|
|
81
|
+
out.setdefault(name, v)
|
|
82
|
+
return out
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Runtimes:
|
|
86
|
+
"""Which runtimes and libraries this machine has, and the call into each harness."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, settings: dict | None = None, root: Path | None = None):
|
|
89
|
+
self.settings = dict(settings or {})
|
|
90
|
+
self.root = root
|
|
91
|
+
self._lock = threading.Lock()
|
|
92
|
+
self._py: dict[str, tuple[str | None, str]] = {} # lib -> (interpreter, why not / version)
|
|
93
|
+
self._go: tuple[list[str] | None, str] | None = None
|
|
94
|
+
self._node: tuple[list[str] | None, str] | None = None
|
|
95
|
+
self.pins = pinned_versions(root) if root else {}
|
|
96
|
+
self.node_pins = node_pins(root) if root else {}
|
|
97
|
+
self._rust: tuple[list[str] | None, str] | None = None
|
|
98
|
+
self._java: tuple[list[str] | None, str] | None = None
|
|
99
|
+
self._npm: dict[str, tuple[str | None, str]] = {}
|
|
100
|
+
self.rust_versions: dict[str, str] = {}
|
|
101
|
+
|
|
102
|
+
# --- Python ----------------------------------------------------------------------------------------------------------
|
|
103
|
+
def _base_python(self) -> str:
|
|
104
|
+
exe = self.settings.get("python") or sys.executable
|
|
105
|
+
if not exe or not (Path(exe).exists() or shutil.which(exe)):
|
|
106
|
+
raise Unavailable("no Python interpreter")
|
|
107
|
+
return exe
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def _has(exe: str, lib: str) -> str | None:
|
|
111
|
+
try:
|
|
112
|
+
r = subprocess.run([exe, "-I", "-c", f"import {lib}; print(getattr({lib}, '__version__', '?'))"], capture_output=True,
|
|
113
|
+
text=True, timeout=60)
|
|
114
|
+
except (OSError, subprocess.SubprocessError):
|
|
115
|
+
return None
|
|
116
|
+
return r.stdout.strip() if r.returncode == 0 else None
|
|
117
|
+
|
|
118
|
+
def python_for(self, lib: str) -> tuple[str, str]:
|
|
119
|
+
"""(interpreter, library version) that can replay `lib` ('' for the standard library). Raises Unavailable."""
|
|
120
|
+
with self._lock:
|
|
121
|
+
if lib not in self._py:
|
|
122
|
+
try:
|
|
123
|
+
self._py[lib] = (*self._find_python(lib),)
|
|
124
|
+
except Unavailable as e:
|
|
125
|
+
self._py[lib] = (None, str(e))
|
|
126
|
+
exe, detail = self._py[lib]
|
|
127
|
+
if exe is None:
|
|
128
|
+
raise Unavailable(detail)
|
|
129
|
+
return exe, detail
|
|
130
|
+
|
|
131
|
+
def _find_python(self, lib: str) -> tuple[str, str]:
|
|
132
|
+
base = self._base_python()
|
|
133
|
+
if not lib:
|
|
134
|
+
return base, ""
|
|
135
|
+
want = self.pins.get(lib)
|
|
136
|
+
have = self._has(base, lib)
|
|
137
|
+
if have and (not want or have == want):
|
|
138
|
+
return base, have
|
|
139
|
+
if not self.settings.get("provision", True):
|
|
140
|
+
if have:
|
|
141
|
+
return base, have
|
|
142
|
+
raise Unavailable(f"the Python library `{lib}` is not installed for {base} (setting provision is off)")
|
|
143
|
+
ver = subprocess.run([base, "-I", "-c", "import sys; print('%d.%d' % sys.version_info[:2])"], capture_output=True, text=True,
|
|
144
|
+
timeout=60).stdout.strip() or "py"
|
|
145
|
+
for spec in ([f"{lib}=={want}"] if want else []) + [lib]:
|
|
146
|
+
d = cache_dir() / "python" / f"{ver}-{spec.replace('==', '-')}"
|
|
147
|
+
exe = d / "bin" / "python"
|
|
148
|
+
if not exe.exists():
|
|
149
|
+
try:
|
|
150
|
+
subprocess.run([base, "-m", "venv", str(d)], capture_output=True, timeout=300, check=True)
|
|
151
|
+
r = subprocess.run([str(exe), "-m", "pip", "install", "-q", "--disable-pip-version-check", spec], capture_output=True,
|
|
152
|
+
text=True, timeout=600)
|
|
153
|
+
if r.returncode != 0:
|
|
154
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
155
|
+
continue
|
|
156
|
+
except (OSError, subprocess.SubprocessError):
|
|
157
|
+
shutil.rmtree(d, ignore_errors=True)
|
|
158
|
+
continue
|
|
159
|
+
got = self._has(str(exe), lib)
|
|
160
|
+
if got:
|
|
161
|
+
return str(exe), got
|
|
162
|
+
if have:
|
|
163
|
+
return base, have
|
|
164
|
+
raise Unavailable(f"the Python library `{lib}` is not installed and could not be installed into CodeCop's cache")
|
|
165
|
+
|
|
166
|
+
# --- Node and Go -----------------------------------------------------------------------------------------------------
|
|
167
|
+
def node(self) -> list[str]:
|
|
168
|
+
with self._lock:
|
|
169
|
+
if self._node is None:
|
|
170
|
+
exe = shutil.which(self.settings.get("node") or "node")
|
|
171
|
+
self._node = ([exe, str(HERE / "run_node.js")], "") if exe else (None, "node is not installed")
|
|
172
|
+
cmd, why = self._node
|
|
173
|
+
if cmd is None:
|
|
174
|
+
raise Unavailable(why)
|
|
175
|
+
return cmd
|
|
176
|
+
|
|
177
|
+
def go(self) -> list[str]:
|
|
178
|
+
with self._lock:
|
|
179
|
+
if self._go is None:
|
|
180
|
+
try:
|
|
181
|
+
self._go = (self._build_go(), "")
|
|
182
|
+
except Unavailable as e:
|
|
183
|
+
self._go = (None, str(e))
|
|
184
|
+
except (OSError, subprocess.SubprocessError) as e:
|
|
185
|
+
self._go = (None, f"{type(e).__name__}: {e}"[:200])
|
|
186
|
+
cmd, why = self._go
|
|
187
|
+
if cmd is None:
|
|
188
|
+
raise Unavailable(why)
|
|
189
|
+
return cmd
|
|
190
|
+
|
|
191
|
+
def _build_go(self) -> list[str]:
|
|
192
|
+
go = shutil.which(self.settings.get("go") or "go")
|
|
193
|
+
if not go:
|
|
194
|
+
raise Unavailable("the Go toolchain is not installed")
|
|
195
|
+
v = subprocess.run([go, "version"], capture_output=True, text=True, timeout=60).stdout.strip()
|
|
196
|
+
src = (HERE / "run_go.go").read_text()
|
|
197
|
+
tag = hashlib.sha256((v + HARNESS_VERSION + src).encode()).hexdigest()[:12]
|
|
198
|
+
d = cache_dir() / f"go-{tag}"
|
|
199
|
+
exe = d / "run_go"
|
|
200
|
+
if not exe.exists():
|
|
201
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
202
|
+
(d / "main.go").write_text(src)
|
|
203
|
+
(d / "go.mod").write_text("module codecopcalls\n\ngo 1.21\n")
|
|
204
|
+
env = {**os.environ, "GOFLAGS": "-mod=mod", "GOPROXY": "off", "GOTOOLCHAIN": "local", "CGO_ENABLED": "0"}
|
|
205
|
+
r = subprocess.run([go, "build", "-o", str(exe), "."], cwd=d, capture_output=True, text=True, timeout=600, env=env)
|
|
206
|
+
if r.returncode != 0:
|
|
207
|
+
raise Unavailable(f"the Go harness did not build: {r.stderr.strip()[:200]}")
|
|
208
|
+
return [str(exe)]
|
|
209
|
+
|
|
210
|
+
def node_package(self, pkg: str) -> tuple[str, str]:
|
|
211
|
+
"""(a node_modules directory holding `pkg`, its version): installed once into CodeCop's cache with npm, at the
|
|
212
|
+
version range the repository's package.json names, when `provision` is on. Raises Unavailable."""
|
|
213
|
+
with self._lock:
|
|
214
|
+
if pkg not in self._npm:
|
|
215
|
+
self._npm[pkg] = self._find_npm(pkg)
|
|
216
|
+
d, why = self._npm[pkg]
|
|
217
|
+
if d is None:
|
|
218
|
+
raise Unavailable(why)
|
|
219
|
+
return d, why
|
|
220
|
+
|
|
221
|
+
def _find_npm(self, pkg: str) -> tuple[str | None, str]:
|
|
222
|
+
spec = self.node_pins.get(pkg) or "latest"
|
|
223
|
+
safe = re.sub(r"[^A-Za-z0-9.]+", "_", spec)
|
|
224
|
+
d = cache_dir() / "node" / f"{pkg}-{safe}"
|
|
225
|
+
mod = d / "node_modules" / pkg / "package.json"
|
|
226
|
+
if not mod.exists():
|
|
227
|
+
npm = shutil.which("npm")
|
|
228
|
+
if not npm:
|
|
229
|
+
return None, f"the Node package `{pkg}` is not available (npm is not installed)"
|
|
230
|
+
if not self.settings.get("provision", True):
|
|
231
|
+
return None, f"the Node package `{pkg}` is not installed in CodeCop's cache (setting provision is off)"
|
|
232
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
233
|
+
try:
|
|
234
|
+
r = subprocess.run([npm, "install", "--prefix", str(d), f"{pkg}@{spec}", "--no-audit", "--no-fund", "--silent",
|
|
235
|
+
"--ignore-scripts"], capture_output=True, text=True, timeout=600)
|
|
236
|
+
except (OSError, subprocess.SubprocessError) as e:
|
|
237
|
+
return None, f"the Node package `{pkg}` could not be installed ({type(e).__name__})"
|
|
238
|
+
if r.returncode != 0 or not mod.exists():
|
|
239
|
+
return None, f"the Node package `{pkg}` could not be installed into CodeCop's cache"
|
|
240
|
+
try:
|
|
241
|
+
ver = json.loads(mod.read_text()).get("version", "?")
|
|
242
|
+
except (OSError, ValueError):
|
|
243
|
+
ver = "?"
|
|
244
|
+
return str(d / "node_modules"), ver
|
|
245
|
+
|
|
246
|
+
def rust(self) -> list[str]:
|
|
247
|
+
with self._lock:
|
|
248
|
+
if self._rust is None:
|
|
249
|
+
try:
|
|
250
|
+
self._rust = (self._build_rust(), "")
|
|
251
|
+
except Unavailable as e:
|
|
252
|
+
self._rust = (None, str(e))
|
|
253
|
+
except (OSError, subprocess.SubprocessError) as e:
|
|
254
|
+
self._rust = (None, f"{type(e).__name__}: {e}"[:200])
|
|
255
|
+
cmd, why = self._rust
|
|
256
|
+
if cmd is None:
|
|
257
|
+
raise Unavailable(why)
|
|
258
|
+
return cmd
|
|
259
|
+
|
|
260
|
+
def _build_rust(self) -> list[str]:
|
|
261
|
+
cargo = shutil.which(self.settings.get("cargo") or "cargo")
|
|
262
|
+
if not cargo:
|
|
263
|
+
raise Unavailable("cargo is not installed")
|
|
264
|
+
ver = subprocess.run([cargo, "--version"], capture_output=True, text=True, timeout=60).stdout.strip()
|
|
265
|
+
src = (HERE / "run_rust.rs").read_text()
|
|
266
|
+
tag = hashlib.sha256((ver + HARNESS_VERSION + RUST_TOML + src).encode()).hexdigest()[:12]
|
|
267
|
+
d = cache_dir() / f"rust-{tag}"
|
|
268
|
+
exe = d / "target" / "release" / "codecop-calls-harness"
|
|
269
|
+
if not exe.exists():
|
|
270
|
+
(d / "src").mkdir(parents=True, exist_ok=True)
|
|
271
|
+
(d / "Cargo.toml").write_text(RUST_TOML)
|
|
272
|
+
(d / "src" / "main.rs").write_text(src)
|
|
273
|
+
env = {**os.environ, "CARGO_NET_OFFLINE": "true"}
|
|
274
|
+
r = subprocess.run([cargo, "build", "--release", "--offline", "--quiet"], cwd=d, capture_output=True, text=True,
|
|
275
|
+
timeout=1800, env=env)
|
|
276
|
+
if r.returncode != 0:
|
|
277
|
+
raise Unavailable("the Rust harness did not build offline (reqwest, tokio and redis must be in the local cargo "
|
|
278
|
+
"cache): " + (r.stderr or r.stdout)[-160:])
|
|
279
|
+
try:
|
|
280
|
+
lock = (d / "Cargo.lock").read_text()
|
|
281
|
+
for name in ("reqwest", "tokio", "redis"):
|
|
282
|
+
m = re.search(rf'name = "{name}"\nversion = "([^"]+)"', lock)
|
|
283
|
+
if m:
|
|
284
|
+
self.rust_versions[name] = m.group(1)
|
|
285
|
+
except OSError:
|
|
286
|
+
pass
|
|
287
|
+
return [str(exe)]
|
|
288
|
+
|
|
289
|
+
def java(self) -> list[str]:
|
|
290
|
+
with self._lock:
|
|
291
|
+
if self._java is None:
|
|
292
|
+
try:
|
|
293
|
+
self._java = (self._build_java(), "")
|
|
294
|
+
except Unavailable as e:
|
|
295
|
+
self._java = (None, str(e))
|
|
296
|
+
except (OSError, subprocess.SubprocessError) as e:
|
|
297
|
+
self._java = (None, f"{type(e).__name__}: {e}"[:200])
|
|
298
|
+
cmd, why = self._java
|
|
299
|
+
if cmd is None:
|
|
300
|
+
raise Unavailable(why)
|
|
301
|
+
return cmd
|
|
302
|
+
|
|
303
|
+
def _build_java(self) -> list[str]:
|
|
304
|
+
java, javac = shutil.which(self.settings.get("java") or "java"), shutil.which("javac")
|
|
305
|
+
if not java or not javac:
|
|
306
|
+
raise Unavailable("a JDK (java and javac, 11 or newer) is not installed")
|
|
307
|
+
v = subprocess.run([java, "-version"], capture_output=True, text=True, timeout=60).stderr.splitlines()
|
|
308
|
+
src = (HERE / "RunCalls.java").read_text()
|
|
309
|
+
tag = hashlib.sha256(((v[0] if v else "") + HARNESS_VERSION + src).encode()).hexdigest()[:12]
|
|
310
|
+
d = cache_dir() / f"java-{tag}"
|
|
311
|
+
if not (d / "RunCalls.class").exists():
|
|
312
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
313
|
+
r = subprocess.run([javac, "-d", str(d), str(HERE / "RunCalls.java")], capture_output=True, text=True, timeout=300)
|
|
314
|
+
if r.returncode != 0:
|
|
315
|
+
raise Unavailable("the Java harness did not compile: " + (r.stderr or "")[-160:])
|
|
316
|
+
pool = int(self.settings.get("java_pool") or 4)
|
|
317
|
+
return [java, "-XX:+UseSerialGC", f"-Djava.util.concurrent.ForkJoinPool.common.parallelism={pool}", "-cp", str(d), "RunCalls"]
|
|
318
|
+
|
|
319
|
+
# --- availability ----------------------------------------------------------------------------------------------------
|
|
320
|
+
def command(self, runtime: str, lib: str = "") -> list[str]:
|
|
321
|
+
if runtime == "python":
|
|
322
|
+
exe, _ = self.python_for(lib)
|
|
323
|
+
return [exe, "-I", str(HERE / "run_python.py")]
|
|
324
|
+
if runtime == "node":
|
|
325
|
+
return self.node()
|
|
326
|
+
if runtime == "go":
|
|
327
|
+
return self.go()
|
|
328
|
+
if runtime == "rust":
|
|
329
|
+
return self.rust()
|
|
330
|
+
if runtime == "java":
|
|
331
|
+
return self.java()
|
|
332
|
+
raise Unavailable(f"no harness for {runtime}")
|
|
333
|
+
|
|
334
|
+
def env_for(self, runtime: str, lib: str) -> dict:
|
|
335
|
+
"""Environment of a harness child: a provisioned Node package's directory on NODE_PATH."""
|
|
336
|
+
if runtime == "node" and lib in NODE_PKGS:
|
|
337
|
+
return {"NODE_PATH": self.node_package(lib)[0]}
|
|
338
|
+
return {}
|
|
339
|
+
|
|
340
|
+
def available(self, runtime: str, lib: str = "") -> tuple[bool, str]:
|
|
341
|
+
try:
|
|
342
|
+
self.command(runtime, lib)
|
|
343
|
+
self.env_for(runtime, lib)
|
|
344
|
+
return True, self.version(runtime, lib)
|
|
345
|
+
except Unavailable as e:
|
|
346
|
+
return False, str(e)
|
|
347
|
+
|
|
348
|
+
def version(self, runtime: str, lib: str = "") -> str:
|
|
349
|
+
try:
|
|
350
|
+
got, _, _ = self.call(runtime, {"op": "version"}, lib=lib, timeout_s=60)
|
|
351
|
+
except Unavailable:
|
|
352
|
+
return ""
|
|
353
|
+
if runtime == "python":
|
|
354
|
+
v = f"CPython {got.get('python', '')}"
|
|
355
|
+
if lib:
|
|
356
|
+
v += f", {lib} {(got.get('libs') or {}).get(lib, '?')}"
|
|
357
|
+
return v
|
|
358
|
+
if runtime == "node":
|
|
359
|
+
return f"Node {got.get('node', '')}" + (f", {lib} {self.node_package(lib)[1]}" if lib in NODE_PKGS else "")
|
|
360
|
+
if runtime == "rust":
|
|
361
|
+
return "Rust, " + ", ".join(f"{k} {v}" for k, v in self.rust_versions.items()) if self.rust_versions else "Rust"
|
|
362
|
+
if runtime == "java":
|
|
363
|
+
return f"Java {got.get('java', '')} (java.net.http, common pool {got.get('common_pool', '?')})"
|
|
364
|
+
return str(got.get("go") or "")
|
|
365
|
+
|
|
366
|
+
# --- one call --------------------------------------------------------------------------------------------------------
|
|
367
|
+
def call(self, runtime: str, req: dict, *, lib: str = "", timeout_s: float = 120, env: dict | None = None) -> tuple[dict, float, bool]:
|
|
368
|
+
"""(the harness's answer, seconds the child ran, whether it was stopped at the timeout). A child stopped at the
|
|
369
|
+
timeout answers {} : the caller reads that as "still waiting"."""
|
|
370
|
+
cmd = self.command(runtime, lib)
|
|
371
|
+
env = {**self.env_for(runtime, lib), **(env or {})}
|
|
372
|
+
t = time.perf_counter()
|
|
373
|
+
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
|
374
|
+
env={**os.environ, **(env or {})}, start_new_session=True)
|
|
375
|
+
try:
|
|
376
|
+
so, se = p.communicate(json.dumps(req), timeout=timeout_s)
|
|
377
|
+
killed = False
|
|
378
|
+
except subprocess.TimeoutExpired:
|
|
379
|
+
p.kill()
|
|
380
|
+
so, se = p.communicate()
|
|
381
|
+
killed = True
|
|
382
|
+
secs = time.perf_counter() - t
|
|
383
|
+
lines = [ln for ln in (so or "").splitlines() if ln.strip().startswith("{")]
|
|
384
|
+
try:
|
|
385
|
+
got = json.loads(lines[-1]) if lines else {}
|
|
386
|
+
except ValueError:
|
|
387
|
+
got = {}
|
|
388
|
+
if not killed and not got:
|
|
389
|
+
got = {"error": (se or "").strip()[-300:] or f"exit {p.returncode}"}
|
|
390
|
+
return got, secs, killed
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def doctor(settings: dict | None = None) -> list[tuple[bool, str, str]]:
|
|
394
|
+
"""(available, runtime, version or why not) per runtime, for `codecop doctor`. Python libraries are checked, never
|
|
395
|
+
installed here."""
|
|
396
|
+
r = Runtimes({**(settings or {}), "provision": False})
|
|
397
|
+
out = []
|
|
398
|
+
try:
|
|
399
|
+
base = r._base_python()
|
|
400
|
+
libs = [f"{lib} {v}" for lib in PY_LIBS if (v := Runtimes._has(base, lib))]
|
|
401
|
+
out.append((True, "CPython", (r.version("python") or "CPython") + (f" ({', '.join(libs)})" if libs else
|
|
402
|
+
" (HTTP libraries are installed into CodeCop's cache when first needed)")))
|
|
403
|
+
except Unavailable as e:
|
|
404
|
+
out.append((False, "CPython", str(e)))
|
|
405
|
+
for name, label in (("node", "Node"), ("go", "Go"), ("rust", "Rust (cargo, offline)"), ("java", "Java (JDK)")):
|
|
406
|
+
ok, detail = r.available(name)
|
|
407
|
+
out.append((ok, label, detail))
|
|
408
|
+
return out
|