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,167 @@
|
|
|
1
|
+
// CodeCop's call harness for the JVM (JDK only: java.net.http and HttpURLConnection; compiled once with javac into CodeCop's
|
|
2
|
+
// cache, no Maven). One JSON request on stdin (flat keys), one JSON line out. The call shape is replayed against CodeCop's
|
|
3
|
+
// stand-in server; nothing of the repository is compiled or run.
|
|
4
|
+
//
|
|
5
|
+
// ops:
|
|
6
|
+
// version
|
|
7
|
+
// client {base, calls, mode: per_call|shared, cafile} java.net.http.HttpClient built per call or once
|
|
8
|
+
// block {call: thread_sleep|url_connection, base, call_ms, handlers, heartbeat_ms, mode: before|after}
|
|
9
|
+
// `handlers` CompletableFuture.supplyAsync tasks on the common pool (before) or on their own executor (after);
|
|
10
|
+
// a heartbeat submits a no-op to the common pool every heartbeat_ms and records how late it starts
|
|
11
|
+
// hang {call: http_client|url_connection, url, timeout_ms}
|
|
12
|
+
import java.io.*;
|
|
13
|
+
import java.net.*;
|
|
14
|
+
import java.net.http.*;
|
|
15
|
+
import java.security.KeyStore;
|
|
16
|
+
import java.security.cert.*;
|
|
17
|
+
import java.time.Duration;
|
|
18
|
+
import java.util.*;
|
|
19
|
+
import java.util.concurrent.*;
|
|
20
|
+
import java.util.regex.*;
|
|
21
|
+
import javax.net.ssl.*;
|
|
22
|
+
|
|
23
|
+
public class RunCalls {
|
|
24
|
+
static Map<String, String> parse(String s) {
|
|
25
|
+
Map<String, String> m = new HashMap<>();
|
|
26
|
+
Matcher x = Pattern.compile("\"([a-z_]+)\"\\s*:\\s*(\"((?:[^\"\\\\]|\\\\.)*)\"|[-0-9.eE]+|true|false|null)").matcher(s);
|
|
27
|
+
while (x.find()) m.put(x.group(1), x.group(3) != null ? x.group(3).replace("\\/", "/").replace("\\\\", "\\") : x.group(2));
|
|
28
|
+
return m;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
static double num(Map<String, String> r, String k, double d) {
|
|
32
|
+
try { return Double.parseDouble(r.get(k)); } catch (Exception e) { return d; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
static String q(String s) { return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; }
|
|
36
|
+
|
|
37
|
+
static SSLContext ssl(String cafile) throws Exception {
|
|
38
|
+
if (cafile == null || cafile.isEmpty()) return SSLContext.getDefault();
|
|
39
|
+
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
|
|
40
|
+
ks.load(null, null);
|
|
41
|
+
try (InputStream in = new FileInputStream(cafile)) {
|
|
42
|
+
ks.setCertificateEntry("standin", CertificateFactory.getInstance("X.509").generateCertificate(in));
|
|
43
|
+
}
|
|
44
|
+
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
|
45
|
+
tmf.init(ks);
|
|
46
|
+
SSLContext c = SSLContext.getInstance("TLS");
|
|
47
|
+
c.init(null, tmf.getTrustManagers(), null);
|
|
48
|
+
return c;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
static long fnv(long h, byte[] b) { for (byte x : b) h = (h ^ (x & 0xff)) * 1099511628211L; return h; }
|
|
52
|
+
|
|
53
|
+
static String client(Map<String, String> r) throws Exception {
|
|
54
|
+
int n = (int) num(r, "calls", 10);
|
|
55
|
+
boolean shared = "shared".equals(r.get("mode"));
|
|
56
|
+
SSLContext ctx = ssl(r.get("cafile"));
|
|
57
|
+
HttpClient one = shared ? HttpClient.newBuilder().sslContext(ctx).build() : null;
|
|
58
|
+
long h = 1469598103934665603L;
|
|
59
|
+
StringBuilder per = new StringBuilder();
|
|
60
|
+
long t0 = System.nanoTime();
|
|
61
|
+
for (int i = 0; i < n; i++) {
|
|
62
|
+
long t = System.nanoTime();
|
|
63
|
+
HttpClient c = one != null ? one : HttpClient.newBuilder().sslContext(ctx).build();
|
|
64
|
+
HttpResponse<byte[]> resp = c.send(HttpRequest.newBuilder(URI.create(r.get("base") + "/k" + i)).build(), HttpResponse.BodyHandlers.ofByteArray());
|
|
65
|
+
h = fnv(h, resp.body());
|
|
66
|
+
per.append(i == 0 ? "" : ",").append((System.nanoTime() - t) / 1e6);
|
|
67
|
+
}
|
|
68
|
+
double total = (System.nanoTime() - t0) / 1e6;
|
|
69
|
+
return "{\"ms_per_call\":" + (total / n) + ",\"per_call_ms\":[" + per + "],\"hash\":" + q(Long.toHexString(h)) + "}";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
static String blockingCall(String call, String base, double callMs, int i) throws Exception {
|
|
73
|
+
if ("url_connection".equals(call)) {
|
|
74
|
+
HttpURLConnection c = (HttpURLConnection) URI.create(base + "/h" + i).toURL().openConnection();
|
|
75
|
+
try (InputStream in = c.getInputStream()) { return Long.toHexString(fnv(1469598103934665603L, in.readAllBytes())); }
|
|
76
|
+
}
|
|
77
|
+
Thread.sleep((long) callMs);
|
|
78
|
+
return "slept" + i;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
static String block(Map<String, String> r) throws Exception {
|
|
82
|
+
String call = r.get("call"), base = r.get("base");
|
|
83
|
+
double callMs = num(r, "call_ms", 50), beat = num(r, "heartbeat_ms", 5);
|
|
84
|
+
int handlers = (int) num(r, "handlers", 20);
|
|
85
|
+
boolean before = "before".equals(r.get("mode"));
|
|
86
|
+
ExecutorService own = Executors.newFixedThreadPool(handlers);
|
|
87
|
+
List<double[]> late = Collections.synchronizedList(new ArrayList<>());
|
|
88
|
+
long t0 = System.nanoTime();
|
|
89
|
+
ScheduledExecutorService sched = Executors.newSingleThreadScheduledExecutor();
|
|
90
|
+
sched.scheduleAtFixedRate(() -> {
|
|
91
|
+
long sub = System.nanoTime();
|
|
92
|
+
CompletableFuture.runAsync(() -> late.add(new double[]{(sub - t0) / 1e6, (System.nanoTime() - sub) / 1e6}));
|
|
93
|
+
}, 0, (long) (beat * 1000), TimeUnit.MICROSECONDS);
|
|
94
|
+
Thread.sleep((long) Math.max(20, 4 * beat));
|
|
95
|
+
long ts = System.nanoTime();
|
|
96
|
+
List<CompletableFuture<String>> fs = new ArrayList<>();
|
|
97
|
+
double[][] spans = new double[handlers][3];
|
|
98
|
+
for (int i = 0; i < handlers; i++) {
|
|
99
|
+
final int k = i;
|
|
100
|
+
java.util.function.Supplier<String> task = () -> {
|
|
101
|
+
long s = System.nanoTime();
|
|
102
|
+
try {
|
|
103
|
+
String o = blockingCall(call, base, callMs, k);
|
|
104
|
+
spans[k] = new double[]{k, (s - t0) / 1e6, (System.nanoTime() - t0) / 1e6};
|
|
105
|
+
return o;
|
|
106
|
+
} catch (Exception e) { return "error"; }
|
|
107
|
+
};
|
|
108
|
+
fs.add(before ? CompletableFuture.supplyAsync(task) : CompletableFuture.supplyAsync(task, own));
|
|
109
|
+
}
|
|
110
|
+
StringBuilder outs = new StringBuilder();
|
|
111
|
+
for (CompletableFuture<String> f : fs) outs.append(f.get()).append('|');
|
|
112
|
+
double wall = (System.nanoTime() - ts) / 1e6;
|
|
113
|
+
Thread.sleep((long) Math.max(20, 4 * beat));
|
|
114
|
+
sched.shutdownNow();
|
|
115
|
+
own.shutdownNow();
|
|
116
|
+
double stall = 0;
|
|
117
|
+
StringBuilder st = new StringBuilder();
|
|
118
|
+
int ns = 0;
|
|
119
|
+
synchronized (late) {
|
|
120
|
+
for (double[] x : late) {
|
|
121
|
+
stall = Math.max(stall, x[1]);
|
|
122
|
+
if (x[1] > 2 * beat && ns < 64) { st.append(ns++ == 0 ? "" : ",").append("[").append(x[0]).append(",").append(x[1]).append("]"); }
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
StringBuilder sp = new StringBuilder();
|
|
126
|
+
for (int i = 0; i < Math.min(handlers, 64); i++)
|
|
127
|
+
sp.append(i == 0 ? "" : ",").append("[").append((int) spans[i][0]).append(",").append(spans[i][1]).append(",").append(spans[i][2]).append("]");
|
|
128
|
+
return "{\"wall_ms\":" + wall + ",\"stall_ms\":" + stall + ",\"beats\":" + late.size() + ",\"start_ms\":" + (ts - t0) / 1e6
|
|
129
|
+
+ ",\"stalls\":[" + st + "],\"spans\":[" + sp + "],\"hash\":" + q(Long.toHexString(fnv(1469598103934665603L, outs.toString().getBytes()))) + "}";
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
static String hang(Map<String, String> r) {
|
|
133
|
+
double to = num(r, "timeout_ms", 0);
|
|
134
|
+
long t = System.nanoTime();
|
|
135
|
+
String err = "returned";
|
|
136
|
+
try {
|
|
137
|
+
if ("url_connection".equals(r.get("call"))) {
|
|
138
|
+
HttpURLConnection c = (HttpURLConnection) URI.create(r.get("url")).toURL().openConnection();
|
|
139
|
+
if (to > 0) { c.setConnectTimeout((int) to); c.setReadTimeout((int) to); }
|
|
140
|
+
c.getInputStream().close();
|
|
141
|
+
} else {
|
|
142
|
+
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(r.get("url")));
|
|
143
|
+
if (to > 0) b = b.timeout(Duration.ofMillis((long) to));
|
|
144
|
+
HttpClient.newHttpClient().send(b.build(), HttpResponse.BodyHandlers.discarding());
|
|
145
|
+
}
|
|
146
|
+
} catch (Exception e) { err = e.getClass().getSimpleName(); }
|
|
147
|
+
return "{\"returned\":true,\"seconds\":" + (System.nanoTime() - t) / 1e9 + ",\"error\":" + q(err) + "}";
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
public static void main(String[] a) throws Exception {
|
|
151
|
+
Map<String, String> r = parse(new String(System.in.readAllBytes()));
|
|
152
|
+
String op = r.getOrDefault("op", "");
|
|
153
|
+
String out;
|
|
154
|
+
try {
|
|
155
|
+
switch (op) {
|
|
156
|
+
case "version": out = "{\"java\":" + q(System.getProperty("java.version")) + ",\"common_pool\":" + ForkJoinPool.getCommonPoolParallelism() + "}"; break;
|
|
157
|
+
case "client": out = client(r); break;
|
|
158
|
+
case "block": out = block(r); break;
|
|
159
|
+
case "hang": out = hang(r); break;
|
|
160
|
+
default: out = "{\"error\":\"unknown op\"}";
|
|
161
|
+
}
|
|
162
|
+
} catch (Exception e) { out = "{\"error\":" + q(String.valueOf(e)) + "}"; }
|
|
163
|
+
System.out.println(out);
|
|
164
|
+
System.out.flush();
|
|
165
|
+
System.exit(0);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// CodeCop's call harness for Go (built once into CodeCop's cache with the local toolchain, standard library only). One JSON
|
|
2
|
+
// request on stdin, one JSON line out. The call shape is replayed against CodeCop's stand-in server; nothing of the
|
|
3
|
+
// repository is compiled or run.
|
|
4
|
+
//
|
|
5
|
+
// ops:
|
|
6
|
+
// version
|
|
7
|
+
// client {base, calls, mode: transport_per_call|client_per_call|shared, cafile}
|
|
8
|
+
// transport_per_call: a new http.Transport (and client) per call, as written; client_per_call: a new
|
|
9
|
+
// http.Client{} per call on the default transport; shared: one client and transport (the fix)
|
|
10
|
+
// hang {url, timeout_ms, mode: default_client|client} one call against a listener that never answers
|
|
11
|
+
package main
|
|
12
|
+
|
|
13
|
+
import (
|
|
14
|
+
"crypto/sha256"
|
|
15
|
+
"crypto/tls"
|
|
16
|
+
"crypto/x509"
|
|
17
|
+
"encoding/hex"
|
|
18
|
+
"encoding/json"
|
|
19
|
+
"fmt"
|
|
20
|
+
"io"
|
|
21
|
+
"net/http"
|
|
22
|
+
"os"
|
|
23
|
+
"runtime"
|
|
24
|
+
"time"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
type Req struct {
|
|
28
|
+
Op string `json:"op"`
|
|
29
|
+
Base string `json:"base"`
|
|
30
|
+
Calls int `json:"calls"`
|
|
31
|
+
Mode string `json:"mode"`
|
|
32
|
+
Cafile string `json:"cafile"`
|
|
33
|
+
URL string `json:"url"`
|
|
34
|
+
TimeoutMs float64 `json:"timeout_ms"`
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
func out(v interface{}) {
|
|
38
|
+
b, _ := json.Marshal(v)
|
|
39
|
+
fmt.Println(string(b))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
func tlsConf(cafile string) *tls.Config {
|
|
43
|
+
if cafile == "" {
|
|
44
|
+
return nil
|
|
45
|
+
}
|
|
46
|
+
pem, err := os.ReadFile(cafile)
|
|
47
|
+
if err != nil {
|
|
48
|
+
return nil
|
|
49
|
+
}
|
|
50
|
+
pool := x509.NewCertPool()
|
|
51
|
+
pool.AppendCertsFromPEM(pem)
|
|
52
|
+
return &tls.Config{RootCAs: pool}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
func client(r Req) {
|
|
56
|
+
conf := tlsConf(r.Cafile)
|
|
57
|
+
if conf != nil {
|
|
58
|
+
// the default transport must trust the stand-in too, for the shape that uses it
|
|
59
|
+
http.DefaultTransport.(*http.Transport).TLSClientConfig = conf
|
|
60
|
+
}
|
|
61
|
+
h := sha256.New()
|
|
62
|
+
per := []float64{}
|
|
63
|
+
var shared *http.Client
|
|
64
|
+
if r.Mode == "shared" {
|
|
65
|
+
shared = &http.Client{Transport: &http.Transport{TLSClientConfig: conf}}
|
|
66
|
+
}
|
|
67
|
+
t0 := time.Now()
|
|
68
|
+
for i := 0; i < r.Calls; i++ {
|
|
69
|
+
t := time.Now()
|
|
70
|
+
c := shared
|
|
71
|
+
var tr *http.Transport
|
|
72
|
+
if c == nil {
|
|
73
|
+
if r.Mode == "transport_per_call" {
|
|
74
|
+
tr = &http.Transport{TLSClientConfig: conf}
|
|
75
|
+
c = &http.Client{Transport: tr}
|
|
76
|
+
} else {
|
|
77
|
+
c = &http.Client{}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
resp, err := c.Get(fmt.Sprintf("%s/k%d", r.Base, i))
|
|
81
|
+
if err != nil {
|
|
82
|
+
out(map[string]string{"error": err.Error()})
|
|
83
|
+
return
|
|
84
|
+
}
|
|
85
|
+
b, _ := io.ReadAll(resp.Body)
|
|
86
|
+
resp.Body.Close()
|
|
87
|
+
h.Write(b)
|
|
88
|
+
if tr != nil {
|
|
89
|
+
tr.CloseIdleConnections()
|
|
90
|
+
}
|
|
91
|
+
per = append(per, float64(time.Since(t).Microseconds())/1000)
|
|
92
|
+
}
|
|
93
|
+
total := float64(time.Since(t0).Microseconds()) / 1000
|
|
94
|
+
out(map[string]interface{}{"ms_per_call": total / float64(r.Calls), "per_call_ms": per, "hash": hex.EncodeToString(h.Sum(nil))})
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
func hang(r Req) {
|
|
98
|
+
t := time.Now()
|
|
99
|
+
var err error
|
|
100
|
+
if r.Mode == "default_client" && r.TimeoutMs == 0 {
|
|
101
|
+
var resp *http.Response
|
|
102
|
+
resp, err = http.Get(r.URL)
|
|
103
|
+
if err == nil {
|
|
104
|
+
resp.Body.Close()
|
|
105
|
+
}
|
|
106
|
+
} else {
|
|
107
|
+
c := &http.Client{}
|
|
108
|
+
if r.TimeoutMs > 0 {
|
|
109
|
+
c.Timeout = time.Duration(r.TimeoutMs) * time.Millisecond
|
|
110
|
+
}
|
|
111
|
+
var resp *http.Response
|
|
112
|
+
resp, err = c.Get(r.URL)
|
|
113
|
+
if err == nil {
|
|
114
|
+
resp.Body.Close()
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
e := "returned"
|
|
118
|
+
if err != nil {
|
|
119
|
+
e = "error"
|
|
120
|
+
}
|
|
121
|
+
out(map[string]interface{}{"returned": true, "seconds": time.Since(t).Seconds(), "error": e})
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
func main() {
|
|
125
|
+
var r Req
|
|
126
|
+
b, _ := io.ReadAll(os.Stdin)
|
|
127
|
+
if err := json.Unmarshal(b, &r); err != nil {
|
|
128
|
+
out(map[string]string{"error": err.Error()})
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
switch r.Op {
|
|
132
|
+
case "version":
|
|
133
|
+
out(map[string]string{"go": runtime.Version()})
|
|
134
|
+
case "client":
|
|
135
|
+
client(r)
|
|
136
|
+
case "hang":
|
|
137
|
+
hang(r)
|
|
138
|
+
default:
|
|
139
|
+
out(map[string]string{"error": "unknown op " + r.Op})
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// CodeCop's call harness for Node (run in a child, one JSON request on stdin, one JSON line out). Only Node's own modules
|
|
2
|
+
// are used: the call shape is replayed against CodeCop's stand-in server; nothing of the repository is loaded or run.
|
|
3
|
+
//
|
|
4
|
+
// ops:
|
|
5
|
+
// version
|
|
6
|
+
// client {base, calls, mode: per_call|shared, cafile, verb} a new http(s).Agent per call (as written) or one agent
|
|
7
|
+
// block {call, call_ms, handlers, heartbeat_ms, mode, iterations, keylen, digest}
|
|
8
|
+
// `handlers` concurrent async handlers doing the blocking call on the event loop (before) or its async form (after)
|
|
9
|
+
// hang {call: fetch|http.request, url, timeout_ms} one call against a listener that never answers
|
|
10
|
+
'use strict';
|
|
11
|
+
const http = require('http');
|
|
12
|
+
const https = require('https');
|
|
13
|
+
const crypto = require('crypto');
|
|
14
|
+
const cp = require('child_process');
|
|
15
|
+
const fs = require('fs');
|
|
16
|
+
const { promisify } = require('util');
|
|
17
|
+
|
|
18
|
+
function out(o) { process.stdout.write(JSON.stringify(o) + '\n'); }
|
|
19
|
+
function now() { return Number(process.hrtime.bigint()) / 1e6; }
|
|
20
|
+
|
|
21
|
+
function request(url, agent, ca, verb) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const mod = url.startsWith('https') ? https : http;
|
|
24
|
+
const body = verb === 'post' ? JSON.stringify({ q: 1 }) : null;
|
|
25
|
+
const req = mod.request(url, { method: (verb || 'get').toUpperCase(), agent, ca, headers: body ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) } : {} }, (res) => {
|
|
26
|
+
const chunks = [];
|
|
27
|
+
res.on('data', (c) => chunks.push(c));
|
|
28
|
+
res.on('end', () => resolve(Buffer.concat(chunks)));
|
|
29
|
+
});
|
|
30
|
+
req.on('error', reject);
|
|
31
|
+
if (body) req.write(body);
|
|
32
|
+
req.end();
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// axios (installed into CodeCop's cache, on NODE_PATH): axios.create() per call as written, one instance as the fix; the
|
|
37
|
+
// instance gets the options the call site passed as literals, never an agent of CodeCop's own
|
|
38
|
+
async function axiosClient(r) {
|
|
39
|
+
const axios = require('axios');
|
|
40
|
+
const ca = r.cafile ? fs.readFileSync(r.cafile) : undefined;
|
|
41
|
+
const opts = Object.assign({}, r.agent_options || {});
|
|
42
|
+
if (ca) opts.httpsAgent = undefined;
|
|
43
|
+
if (ca) https.globalAgent.options.ca = ca;
|
|
44
|
+
const h = crypto.createHash('sha256');
|
|
45
|
+
const per = [];
|
|
46
|
+
const t0 = now();
|
|
47
|
+
const shared = r.mode === 'shared' ? axios.create(opts) : null;
|
|
48
|
+
for (let i = 0; i < r.calls; i++) {
|
|
49
|
+
const t = now();
|
|
50
|
+
const c = shared || axios.create(opts);
|
|
51
|
+
const res = await c.get(`${r.base}/k${i}`, { responseType: 'arraybuffer' });
|
|
52
|
+
h.update(Buffer.from(res.data));
|
|
53
|
+
per.push(now() - t);
|
|
54
|
+
}
|
|
55
|
+
out({ ms_per_call: (now() - t0) / r.calls, per_call_ms: per, hash: h.digest('hex') });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ioredis (installed into CodeCop's cache): a new connection object per call as written, one as the fix
|
|
59
|
+
async function ioredisClient(r) {
|
|
60
|
+
const Redis = require('ioredis');
|
|
61
|
+
const [host, port] = r.redis;
|
|
62
|
+
const h = crypto.createHash('sha256');
|
|
63
|
+
const per = [];
|
|
64
|
+
const t0 = now();
|
|
65
|
+
const shared = r.mode === 'shared' ? new Redis({ host, port, enableReadyCheck: false, maxRetriesPerRequest: 1 }) : null;
|
|
66
|
+
for (let i = 0; i < r.calls; i++) {
|
|
67
|
+
const t = now();
|
|
68
|
+
const c = shared || new Redis({ host, port, enableReadyCheck: false, maxRetriesPerRequest: 1 });
|
|
69
|
+
const v = await c.get(`k${i}`);
|
|
70
|
+
h.update(String(v));
|
|
71
|
+
if (!shared) c.disconnect();
|
|
72
|
+
per.push(now() - t);
|
|
73
|
+
}
|
|
74
|
+
if (shared) shared.disconnect();
|
|
75
|
+
out({ ms_per_call: (now() - t0) / r.calls, per_call_ms: per, hash: h.digest('hex') });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function client(r) {
|
|
79
|
+
if (r.lib === 'axios') return axiosClient(r);
|
|
80
|
+
if (r.lib === 'ioredis') return ioredisClient(r);
|
|
81
|
+
const ca = r.cafile ? fs.readFileSync(r.cafile) : undefined;
|
|
82
|
+
const tls = r.base.startsWith('https');
|
|
83
|
+
const Agent = tls ? https.Agent : http.Agent;
|
|
84
|
+
const opts = Object.assign({ keepAlive: true }, r.agent_options || {}, ca ? { ca } : {});
|
|
85
|
+
const h = crypto.createHash('sha256');
|
|
86
|
+
const per = [];
|
|
87
|
+
const t0 = now();
|
|
88
|
+
let shared = r.mode === 'shared' ? new Agent(opts) : null;
|
|
89
|
+
for (let i = 0; i < r.calls; i++) {
|
|
90
|
+
const t = now();
|
|
91
|
+
const agent = shared || new Agent(opts);
|
|
92
|
+
h.update(await request(`${r.base}/k${i}`, agent, ca, r.verb));
|
|
93
|
+
if (!shared) agent.destroy();
|
|
94
|
+
per.push(now() - t);
|
|
95
|
+
}
|
|
96
|
+
if (shared) shared.destroy();
|
|
97
|
+
out({ ms_per_call: (now() - t0) / r.calls, per_call_ms: per.map((x) => Math.round(x * 1000) / 1000), hash: h.digest('hex') });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function blockingFns(r) {
|
|
101
|
+
const ms = Number(r.call_ms);
|
|
102
|
+
const code = `setTimeout(()=>process.stdout.write('done'), ${ms})`;
|
|
103
|
+
const execFile = promisify(cp.execFile);
|
|
104
|
+
if (['execSync', 'spawnSync', 'execFileSync'].includes(r.call)) {
|
|
105
|
+
// a stand-in child that takes call_ms: the repository's own command is never run
|
|
106
|
+
return [
|
|
107
|
+
(i) => cp.execFileSync(process.execPath, ['-e', code]).toString() + i,
|
|
108
|
+
async (i) => (await execFile(process.execPath, ['-e', code])).stdout + i,
|
|
109
|
+
];
|
|
110
|
+
}
|
|
111
|
+
if (r.call === 'pbkdf2Sync') {
|
|
112
|
+
const it = Number(r.iterations || 100000), kl = Number(r.keylen || 64), dg = r.digest || 'sha512';
|
|
113
|
+
const p = promisify(crypto.pbkdf2);
|
|
114
|
+
return [(i) => crypto.pbkdf2Sync('pw' + i, 'salt', it, kl, dg).toString('hex'), async (i) => (await p('pw' + i, 'salt', it, kl, dg)).toString('hex')];
|
|
115
|
+
}
|
|
116
|
+
if (r.call === 'scryptSync') {
|
|
117
|
+
const kl = Number(r.keylen || 64);
|
|
118
|
+
const p = promisify(crypto.scrypt);
|
|
119
|
+
return [(i) => crypto.scryptSync('pw' + i, 'salt', kl).toString('hex'), async (i) => (await p('pw' + i, 'salt', kl)).toString('hex')];
|
|
120
|
+
}
|
|
121
|
+
throw new Error('no replay for ' + r.call);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function block(r) {
|
|
125
|
+
const [syncFn, asyncFn] = blockingFns(r);
|
|
126
|
+
const beat = Number(r.heartbeat_ms);
|
|
127
|
+
const late = [];
|
|
128
|
+
const spans = [];
|
|
129
|
+
const t0 = now();
|
|
130
|
+
let last = now();
|
|
131
|
+
const timer = setInterval(() => { const t = now(); late.push([t - t0, t - last - beat]); last = t; }, beat);
|
|
132
|
+
await new Promise((res) => setTimeout(res, Math.max(20, 4 * beat)));
|
|
133
|
+
const ts = now();
|
|
134
|
+
const handler = async (i) => {
|
|
135
|
+
await null;
|
|
136
|
+
const s = now();
|
|
137
|
+
const v = r.mode === 'before' ? syncFn(i) : await asyncFn(i);
|
|
138
|
+
spans.push([i, Math.round((s - t0) * 100) / 100, Math.round((now() - t0) * 100) / 100]);
|
|
139
|
+
return v;
|
|
140
|
+
};
|
|
141
|
+
const outs = await Promise.all(Array.from({ length: r.handlers }, (_, i) => handler(i)));
|
|
142
|
+
const wall = now() - ts;
|
|
143
|
+
await new Promise((res) => setTimeout(res, Math.max(20, 4 * beat)));
|
|
144
|
+
clearInterval(timer);
|
|
145
|
+
const stall = late.reduce((m, x) => Math.max(m, x[1]), 0);
|
|
146
|
+
out({ wall_ms: wall, stall_ms: stall, beats: late.length, start_ms: Math.round((ts - t0) * 100) / 100,
|
|
147
|
+
stalls: late.filter((x) => x[1] > 2 * beat).slice(0, 64).map((x) => [Math.round((x[0] - x[1]) * 10) / 10, Math.round(x[1] * 10) / 10]),
|
|
148
|
+
spans: spans.sort((a, b) => a[0] - b[0]).slice(0, 64),
|
|
149
|
+
hash: crypto.createHash('sha256').update(JSON.stringify(outs)).digest('hex') });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function hang(r) {
|
|
153
|
+
const t = now();
|
|
154
|
+
let err = 'returned';
|
|
155
|
+
try {
|
|
156
|
+
if (r.call === 'axios') {
|
|
157
|
+
const axios = require('axios');
|
|
158
|
+
await axios.get(r.url, r.timeout_ms ? { timeout: r.timeout_ms } : {});
|
|
159
|
+
} else if (r.call === 'fetch') {
|
|
160
|
+
const opts = r.timeout_ms ? { signal: AbortSignal.timeout(r.timeout_ms) } : {};
|
|
161
|
+
const res = await fetch(r.url, opts);
|
|
162
|
+
await res.text();
|
|
163
|
+
} else {
|
|
164
|
+
await new Promise((resolve, reject) => {
|
|
165
|
+
const req = http.request(r.url, r.timeout_ms ? { timeout: r.timeout_ms } : {}, (res) => { res.resume(); res.on('end', resolve); });
|
|
166
|
+
req.on('timeout', () => req.destroy(Object.assign(new Error('timeout'), { name: 'TimeoutError' })));
|
|
167
|
+
req.on('error', reject);
|
|
168
|
+
req.end();
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
} catch (e) { err = (e && (e.name || e.code)) || 'Error'; }
|
|
172
|
+
out({ returned: true, seconds: (now() - t) / 1000, error: err });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
let input = '';
|
|
176
|
+
process.stdin.on('data', (d) => { input += d; });
|
|
177
|
+
process.stdin.on('end', async () => {
|
|
178
|
+
const r = JSON.parse(input || '{}');
|
|
179
|
+
try {
|
|
180
|
+
if (r.op === 'version') out({ node: process.versions.node, v8: process.versions.v8, undici: process.versions.undici || '' });
|
|
181
|
+
else if (r.op === 'client') await client(r);
|
|
182
|
+
else if (r.op === 'block') await block(r);
|
|
183
|
+
else if (r.op === 'hang') await hang(r);
|
|
184
|
+
else out({ error: 'unknown op ' + r.op });
|
|
185
|
+
} catch (e) { out({ error: String(e && e.message || e) }); }
|
|
186
|
+
});
|