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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1097 @@
1
+ """Discovery of outbound call shapes, per language (text and syntax only; nothing is imported or run).
2
+
3
+ Three scenarios:
4
+
5
+ - `client_per_call`: a network client (HTTP client or session, connection pool, transport, Redis or database client)
6
+ built inside a function, so every call of that function builds it again; and, in Python, `requests.<verb>()` inside a
7
+ per-item loop (each call is a new session and a new connection).
8
+ - `blocking_in_async`: a blocking call (sleep, synchronous HTTP, a child process, a synchronous key derivation) inside an
9
+ async function, where it stops the event loop for every other task.
10
+ - `no_timeout`: an outbound HTTP call that can wait forever (requests and urllib without `timeout`, Go's default client
11
+ or a client without `Timeout`, Node `fetch` without an abort signal, `http.request` without `timeout`).
12
+
13
+ Each site carries the facts the rules need: the canonical call (`httpx.AsyncClient`), the runtime that replays it, the
14
+ literal keyword arguments (only literals are replayed), and static set-asides found in the code itself (`aside`: built
15
+ on the object or behind a guard, a factory, a start-up function, a retry loop, a timeout set process-wide, ...).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import ast
21
+ import re
22
+ from pathlib import Path
23
+
24
+ from ...discover.base import read_text
25
+ from ..regex.extract import _ancestors, _line, _t, _walk, browser_path, parser, vendored
26
+
27
+ HTTP_VERBS = {"get", "post", "put", "delete", "patch", "head", "options", "request"}
28
+ # Python client constructors: canonical name -> (library, replayable on the stand-in)
29
+ PY_CLIENTS = {
30
+ "httpx.Client": ("httpx", True), "httpx.AsyncClient": ("httpx", True), "aiohttp.ClientSession": ("aiohttp", True),
31
+ "requests.Session": ("requests", True), "requests.session": ("requests", True),
32
+ "redis.Redis": ("redis", True), "redis.StrictRedis": ("redis", True), "redis.from_url": ("redis", True),
33
+ "redis.Redis.from_url": ("redis", True), "redis.asyncio.Redis": ("redis", False), "redis.asyncio.from_url": ("redis", False),
34
+ "urllib3.PoolManager": ("urllib3", False), "boto3.client": ("boto3", False), "boto3.resource": ("boto3", False),
35
+ "pymongo.MongoClient": ("pymongo", False), "motor.motor_asyncio.AsyncIOMotorClient": ("motor", False),
36
+ "psycopg2.connect": ("psycopg2", False), "psycopg.connect": ("psycopg", False), "psycopg.AsyncConnection.connect": ("psycopg", False),
37
+ "sqlalchemy.create_engine": ("sqlalchemy", False), "sqlalchemy.ext.asyncio.create_async_engine": ("sqlalchemy", False),
38
+ "asyncpg.create_pool": ("asyncpg", False), "elasticsearch.Elasticsearch": ("elasticsearch", False),
39
+ "elasticsearch.AsyncElasticsearch": ("elasticsearch", False), "clickhouse_connect.get_client": ("clickhouse_connect", False),
40
+ }
41
+ PY_BLOCKING = {"time.sleep", "urllib.request.urlopen", "subprocess.run", "subprocess.call", "subprocess.check_call",
42
+ "subprocess.check_output", "os.system"} | {f"requests.{v}" for v in HTTP_VERBS} | \
43
+ {f"httpx.{v}" for v in HTTP_VERBS - {"options"}} | {"httpx.stream"}
44
+ STARTUP_NAMES = re.compile(r"^(__init__|__aenter__|__enter__|__post_init__|setup|set_up|setUp|startup|on_startup|start_up|lifespan|"
45
+ r"init|init_app|initialize|initialise|create_app|make_app|build_app|main|run_main|cli|configure|bootstrap|"
46
+ r"app_lifespan|on_event|connect|open|start)$|(^|_)(lifespan|startup)$")
47
+ CACHE_DECORATORS = re.compile(r"(^|\.)(lru_cache|cache|cached|cached_property|cachedmethod|memoize|alru_cache|singleton)$")
48
+ PER_CALL_KW = {"cookies", "auth", "cert", "proxies", "proxy", "proxy_auth", "trust_env", "transport", "connector"}
49
+ RETRY_NAMES = re.compile(r"(?i)retr|attempt|tries|backoff|poll|page|cursor|offset|next_|token")
50
+
51
+
52
+ def _literal(node):
53
+ """A Python literal value (numbers, strings, bools, None, flat lists and dicts of those), else raise ValueError."""
54
+ v = ast.literal_eval(node)
55
+ if isinstance(v, (int, float, str, bool, type(None))):
56
+ return v
57
+ if isinstance(v, (list, tuple, dict)) and len(repr(v)) < 400:
58
+ return v
59
+ raise ValueError("not a short literal")
60
+
61
+
62
+ class _Aliases:
63
+ """Local names of imported modules and objects -> dotted canonical names."""
64
+
65
+ def __init__(self, tree):
66
+ self.names: dict[str, str] = {}
67
+ for n in ast.walk(tree):
68
+ if isinstance(n, ast.Import):
69
+ for a in n.names:
70
+ if a.asname:
71
+ self.names[a.asname] = a.name
72
+ else:
73
+ self.names[a.name.split(".")[0]] = a.name.split(".")[0]
74
+ elif isinstance(n, ast.ImportFrom) and n.module and not n.level:
75
+ for a in n.names:
76
+ self.names[a.asname or a.name] = f"{n.module}.{a.name}"
77
+
78
+ def resolve(self, func) -> str:
79
+ parts = []
80
+ n = func
81
+ while isinstance(n, ast.Attribute):
82
+ parts.append(n.attr)
83
+ n = n.value
84
+ if not isinstance(n, ast.Name):
85
+ return ""
86
+ head = self.names.get(n.id)
87
+ if head is None:
88
+ return ""
89
+ return ".".join([head] + list(reversed(parts)))
90
+
91
+
92
+ def _canon(name: str) -> str:
93
+ """Normalise a resolved import path to the names the tables use (aiohttp.client.ClientSession -> aiohttp.ClientSession)."""
94
+ name = re.sub(r"^redis\.client\.", "redis.", name)
95
+ name = re.sub(r"^aiohttp\.client\.", "aiohttp.", name)
96
+ name = re.sub(r"^httpx\._client\.", "httpx.", name)
97
+ name = re.sub(r"^requests\.(sessions|api)\.", "requests.", name)
98
+ name = re.sub(r"^sqlalchemy\.engine\.", "sqlalchemy.", name)
99
+ return name
100
+
101
+
102
+ def _py_loop_kind(node) -> str:
103
+ """'retry' for a while loop, a loop over range(retries) or one that sleeps or breaks on success; 'each' for a loop
104
+ over a collection; 'comprehension'."""
105
+ if isinstance(node, ast.While):
106
+ return "retry"
107
+ if isinstance(node, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)):
108
+ return "each"
109
+ names = " ".join(n.id for n in ast.walk(node.target) if isinstance(n, ast.Name)) + " " + ast.unparse(node.iter)[:120]
110
+ if RETRY_NAMES.search(names):
111
+ return "retry"
112
+ it = node.iter
113
+ if isinstance(it, ast.Call) and isinstance(it.func, ast.Name) and it.func.id == "range" and it.args and \
114
+ all(isinstance(a, ast.Constant) for a in it.args) and max(int(a.value) for a in it.args if isinstance(a.value, int)) <= 5:
115
+ return "retry"
116
+ for b in ast.walk(node):
117
+ if isinstance(b, ast.Call):
118
+ f = ast.unparse(b.func)
119
+ if f.endswith("sleep"):
120
+ return "retry"
121
+ return "each"
122
+
123
+
124
+ def python_sites(root: Path, files: list[str]) -> list[dict]:
125
+ out: list[dict] = []
126
+ process_timeout = None # socket.setdefaulttimeout anywhere: every requests/urllib call has a deadline
127
+ adapters_with_timeout = None
128
+ parsed = []
129
+ for rel in files:
130
+ src = read_text(root / rel)
131
+ if not src or not any(k in src for k in ("requests", "httpx", "aiohttp", "redis", "urllib", "subprocess", "sleep", "boto3",
132
+ "psycopg", "create_engine", "Mongo", "asyncpg", "Elasticsearch", "os.system",
133
+ "clickhouse")):
134
+ if src and "setdefaulttimeout" in src:
135
+ pass
136
+ else:
137
+ continue
138
+ try:
139
+ tree = ast.parse(src)
140
+ except (SyntaxError, ValueError, RecursionError):
141
+ continue
142
+ if "setdefaulttimeout(" in src and process_timeout is None:
143
+ for n in ast.walk(tree):
144
+ if isinstance(n, ast.Call) and ast.unparse(n.func).endswith("setdefaulttimeout") and n.args and \
145
+ not (isinstance(n.args[0], ast.Constant) and n.args[0].value is None):
146
+ process_timeout = f"{rel}:{n.lineno}"
147
+ break
148
+ if "HTTPAdapter" in src and "timeout" in src and adapters_with_timeout is None:
149
+ for n in ast.walk(tree):
150
+ if isinstance(n, ast.ClassDef) and any("HTTPAdapter" in ast.unparse(b) for b in n.bases) and "timeout" in ast.unparse(n):
151
+ adapters_with_timeout = f"{rel}:{n.lineno}"
152
+ parsed.append((rel, src, tree))
153
+ for rel, src, tree in parsed:
154
+ out.extend(_py_file(rel, src, tree, process_timeout, adapters_with_timeout))
155
+ return out
156
+
157
+
158
+ def _py_file(rel: str, src: str, tree, process_timeout, adapters_with_timeout) -> list[dict]:
159
+ al = _Aliases(tree)
160
+ lines = src.splitlines()
161
+ out: list[dict] = []
162
+ parents: dict = {}
163
+ for p in ast.walk(tree):
164
+ for c in ast.iter_child_nodes(p):
165
+ parents[c] = p
166
+ # module-level names bound to a requests.Session(): their verb calls are session calls
167
+ module_sessions = set()
168
+ for st in tree.body:
169
+ if isinstance(st, ast.Assign) and isinstance(st.value, ast.Call) and _canon(al.resolve(st.value.func)) in ("requests.Session", "requests.session"):
170
+ module_sessions |= {t.id for t in st.targets if isinstance(t, ast.Name)}
171
+
172
+ def chain(n):
173
+ p = parents.get(n)
174
+ while p is not None:
175
+ yield p
176
+ p = parents.get(p)
177
+
178
+ def func_of(n):
179
+ """(innermost def, its qualified name, whether a lambda or nested sync def stands between)."""
180
+ names, fn, through = [], None, False
181
+ for a in chain(n):
182
+ if isinstance(a, ast.Lambda) and fn is None:
183
+ through = True
184
+ if isinstance(a, (ast.FunctionDef, ast.AsyncFunctionDef)):
185
+ if fn is None:
186
+ fn = a
187
+ names.append(a.name)
188
+ elif isinstance(a, ast.ClassDef):
189
+ names.append(a.name)
190
+ return fn, ".".join(reversed(names[:2])), through
191
+
192
+ def text_of(n) -> str:
193
+ ln = getattr(n, "lineno", 0)
194
+ return lines[ln - 1].strip()[:160] if 0 < ln <= len(lines) else ""
195
+
196
+ def loop_of(n, fn):
197
+ for a in chain(n):
198
+ if a is fn:
199
+ return ""
200
+ if isinstance(a, (ast.For, ast.AsyncFor, ast.While, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)):
201
+ return _py_loop_kind(a)
202
+ return ""
203
+
204
+ def site(n, scenario, call, fn, sym, **kw):
205
+ ln = n.lineno
206
+ d = {"file": rel, "line": ln, "end_line": getattr(n, "end_lineno", ln) or ln, "language": "python", "runtime": "python",
207
+ "symbol": sym, "scenario": scenario, "call": call, "text": f"{scenario}:{call}:{text_of(n)}", "code": text_of(n),
208
+ "in_async": isinstance(fn, ast.AsyncFunctionDef), "function": getattr(fn, "name", ""), "in_function": fn is not None}
209
+ d.update(kw)
210
+ out.append(d)
211
+
212
+ sessions_by_fn: dict = {}
213
+ for n in ast.walk(tree):
214
+ if not isinstance(n, ast.Call):
215
+ continue
216
+ name = _canon(al.resolve(n.func))
217
+ fn, sym, through = func_of(n)
218
+ kws = {k.arg for k in n.keywords if k.arg}
219
+ starstar = any(k.arg is None for k in n.keywords)
220
+ # --- a session variable's verb call (s = requests.Session(); s.get(...)) --------------------------------------
221
+ if not name and isinstance(n.func, ast.Attribute) and n.func.attr in HTTP_VERBS and isinstance(n.func.value, ast.Name):
222
+ var = n.func.value.id
223
+ if fn is not None and fn not in sessions_by_fn:
224
+ sess = {}
225
+ for a in ast.walk(fn):
226
+ if isinstance(a, ast.Assign) and isinstance(a.value, ast.Call):
227
+ c = _canon(al.resolve(a.value.func))
228
+ if c in ("requests.Session", "requests.session", "httpx.Client"):
229
+ for t in a.targets:
230
+ if isinstance(t, ast.Name):
231
+ sess[t.id] = c
232
+ if isinstance(a, ast.withitem) and isinstance(a.context_expr, ast.Call) and isinstance(a.optional_vars, ast.Name):
233
+ c = _canon(al.resolve(a.context_expr.func))
234
+ if c in ("requests.Session", "requests.session", "httpx.Client"):
235
+ sess[a.optional_vars.id] = c
236
+ sessions_by_fn[fn] = sess
237
+ kind = (sessions_by_fn.get(fn) or {}).get(var) or ("requests.Session" if var in module_sessions else None)
238
+ if kind:
239
+ verb = n.func.attr
240
+ if kind.startswith("requests") and "timeout" not in kws:
241
+ aside = "keyword arguments passed through (may carry a timeout)" if starstar else \
242
+ f"a process-wide socket timeout is set at {process_timeout}" if process_timeout else \
243
+ f"a session adapter with a timeout is defined at {adapters_with_timeout}" if adapters_with_timeout else ""
244
+ site(n, "no_timeout", f"requests.{verb}", fn, sym, lib="requests", verb=verb, aside=aside, via="session")
245
+ if fn is not None and isinstance(fn, ast.AsyncFunctionDef) and not through:
246
+ site(n, "blocking_in_async", f"{'requests' if kind.startswith('requests') else 'httpx'}.{verb}", fn, sym,
247
+ lib=kind.split(".")[0], verb=verb, aside="", via="session")
248
+ continue
249
+ if not name:
250
+ continue
251
+ # --- client per call -------------------------------------------------------------------------------------------
252
+ if name in PY_CLIENTS and fn is not None:
253
+ lib, replay = PY_CLIENTS[name]
254
+ literal, dynamic = {}, []
255
+ for k in n.keywords:
256
+ if not k.arg:
257
+ dynamic.append("**")
258
+ continue
259
+ try:
260
+ literal[k.arg] = _literal(k.value)
261
+ except (ValueError, SyntaxError, TypeError, RecursionError):
262
+ dynamic.append(k.arg)
263
+ aside = _py_client_aside(n, fn, parents, chain, al)
264
+ if not aside and set(dynamic) & PER_CALL_KW:
265
+ aside = f"built with per-call {', '.join(sorted(set(dynamic) & PER_CALL_KW))}"
266
+ service = n.args[0].value if n.args and isinstance(n.args[0], ast.Constant) and isinstance(n.args[0].value, str) else \
267
+ next((k.value.value for k in n.keywords if k.arg == "service_name" and isinstance(k.value, ast.Constant)), None)
268
+ if name == "boto3.client":
269
+ replay = service == "s3" # the stand-in answers S3 object reads; other services are not stood in for
270
+ site(n, "client_per_call", name, fn, sym, lib=lib, replay=replay, kwargs=literal, dynamic=dynamic, aside=aside,
271
+ loop=loop_of(n, fn), service=service)
272
+ continue
273
+ # --- requests.<verb> in a per-item loop: a new session and connection per item ----------------------------------
274
+ if name.startswith("requests.") and name.split(".")[-1] in HTTP_VERBS and fn is not None:
275
+ loop = loop_of(n, fn)
276
+ if loop:
277
+ site(n, "client_per_call", name, fn, sym, lib="requests", replay=True, kwargs={}, dynamic=[], loop=loop,
278
+ aside="a retry, poll or pagination loop" if loop == "retry" else "", verb=name.split(".")[-1], implicit=True)
279
+ # --- no timeout --------------------------------------------------------------------------------------------------
280
+ if (name.startswith("requests.") and name.split(".")[-1] in HTTP_VERBS) or name == "urllib.request.urlopen":
281
+ has = "timeout" in kws or (name == "urllib.request.urlopen" and len(n.args) >= 3)
282
+ if not has:
283
+ aside = "keyword arguments passed through (may carry a timeout)" if starstar else \
284
+ f"a process-wide socket timeout is set at {process_timeout}" if process_timeout else ""
285
+ site(n, "no_timeout", name, fn, sym, lib="requests" if name.startswith("requests") else "", verb=name.split(".")[-1],
286
+ aside=aside, via="module")
287
+ # --- blocking in async -------------------------------------------------------------------------------------------
288
+ if name in PY_BLOCKING and fn is not None and isinstance(fn, ast.AsyncFunctionDef):
289
+ aside = ""
290
+ if through:
291
+ aside = "inside a lambda (run elsewhere)"
292
+ elif name == "time.sleep" and n.args and isinstance(n.args[0], ast.Constant) and not n.args[0].value:
293
+ aside = "sleep(0)"
294
+ sleep_s = None
295
+ if name == "time.sleep" and n.args:
296
+ try:
297
+ sleep_s = float(_literal(n.args[0]))
298
+ except (ValueError, TypeError, SyntaxError):
299
+ sleep_s = None
300
+ site(n, "blocking_in_async", name, fn, sym, lib=name.split(".")[0] if name.split(".")[0] in ("requests", "httpx") else "",
301
+ verb=name.split(".")[-1], aside=aside, sleep_s=sleep_s)
302
+ return out
303
+
304
+
305
+ def _py_client_aside(n, fn, parents, chain, al) -> str:
306
+ """Why a client built inside a function is still built once (or is not this function's to reuse): kept on the object
307
+ or the module, returned or yielded by a factory, behind a guard, in a start-up or cached function."""
308
+ if STARTUP_NAMES.search(fn.name or ""):
309
+ return f"built in a start-up function ({fn.name})"
310
+ for d in fn.decorator_list:
311
+ if CACHE_DECORATORS.search(ast.unparse(d).split("(")[0]):
312
+ return "built in a cached function"
313
+ p = parents.get(n)
314
+ while isinstance(p, (ast.Await, ast.Tuple, ast.List, ast.Starred, ast.IfExp)):
315
+ p = parents.get(p)
316
+ target = None
317
+ if isinstance(p, (ast.Assign, ast.AnnAssign)):
318
+ tgts = p.targets if isinstance(p, ast.Assign) else [p.target]
319
+ for t in tgts:
320
+ if isinstance(t, ast.Attribute):
321
+ return "kept on the object (built once per object)"
322
+ if isinstance(t, ast.Subscript):
323
+ return "kept in a table (built once per key)"
324
+ if isinstance(t, ast.Name):
325
+ target = t.id
326
+ if target and any(isinstance(g, ast.Global) and target in g.names for g in ast.walk(fn)):
327
+ return "kept in a module global"
328
+ if isinstance(p, (ast.Return, ast.Yield, ast.YieldFrom)):
329
+ return "a factory: its callers decide how often it is built"
330
+ if isinstance(p, ast.withitem):
331
+ w = parents.get(p)
332
+ if w is not None and any(isinstance(b, (ast.Yield, ast.YieldFrom)) for b in ast.walk(w)):
333
+ return "a factory: its callers decide how often it is built"
334
+ if target:
335
+ # `return client` later in the function: a factory
336
+ for a in ast.walk(fn):
337
+ if isinstance(a, (ast.Return, ast.Yield)) and isinstance(a.value, ast.Name) and a.value.id == target:
338
+ return "a factory: its callers decide how often it is built"
339
+ for st in fn.body: # `if cached: return cached` before the client: it is built only on a cache miss
340
+ if getattr(st, "lineno", 10 ** 9) >= n.lineno:
341
+ break
342
+ if isinstance(st, ast.If) and re.search(r"(?i)cache", ast.unparse(st.test)) and any(isinstance(b, ast.Return) for b in st.body):
343
+ return "built only on a cache miss"
344
+ for a in chain(n):
345
+ if a is fn:
346
+ break
347
+ if isinstance(a, ast.If):
348
+ test = ast.unparse(a.test)
349
+ if re.search(r"\bis None\b|\bnot\s+[\w.]+$|^not\s|_client|_session|_pool|_conn", test):
350
+ return "built once behind a guard"
351
+ return ""
352
+
353
+
354
+ # --- TypeScript / JavaScript ------------------------------------------------------------------------------------------------
355
+
356
+ TS_CLIENTS = { # (module, exported name) -> (canonical, replayable on the stand-in)
357
+ ("https", "Agent"): ("https.Agent", True), ("http", "Agent"): ("http.Agent", True),
358
+ ("node:https", "Agent"): ("https.Agent", True), ("node:http", "Agent"): ("http.Agent", True),
359
+ ("undici", "Agent"): ("undici.Agent", False), ("undici", "Pool"): ("undici.Pool", False),
360
+ ("@prisma/client", "PrismaClient"): ("PrismaClient", False), ("ioredis", "default"): ("ioredis", True),
361
+ ("ioredis", "Redis"): ("ioredis", True), ("redis", "createClient"): ("redis.createClient", False),
362
+ ("pg", "Pool"): ("pg.Pool", False), ("pg", "Client"): ("pg.Client", False), ("mongodb", "MongoClient"): ("MongoClient", False),
363
+ ("axios", "create"): ("axios.create", True),
364
+ }
365
+ # a front-end tree (its `api/` folder is the browser's client of the server, not the server), unless a server file
366
+ BROWSER_TREE = re.compile(r"(^|/)(frontend|front-end|web-ui|webui|webapp|client|ui|dashboard|extension|chrome-extension|renderer|templates|static|public|assets|apis)/|(^|/)src/lib/", re.I)
367
+ SERVER_FILE = re.compile(r"(^|/)(pages/api|app/api|server|backend|workers?)/|(^|/)route\.[jt]s$|\.server\.[jt]sx?$|"
368
+ r"(^|/)(middleware|server)\.[jt]s$", re.I)
369
+ TS_BLOCKING = {("child_process", "execSync"), ("child_process", "execFileSync"), ("child_process", "spawnSync"),
370
+ ("crypto", "pbkdf2Sync"), ("crypto", "scryptSync")}
371
+
372
+
373
+ def _ts_imports(tree) -> dict[str, tuple[str, str]]:
374
+ """Local name -> (module, exported name; 'default' / '*' for a default or namespace import)."""
375
+ out: dict[str, tuple[str, str]] = {}
376
+ for n in _walk(tree.root_node):
377
+ if n.type == "import_statement":
378
+ src = n.child_by_field_name("source")
379
+ mod = _t(src).strip("'\"`") if src is not None else ""
380
+ for c in _walk(n):
381
+ if c.type == "import_specifier":
382
+ nm, al = c.child_by_field_name("name"), c.child_by_field_name("alias")
383
+ out[_t(al or nm)] = (mod, _t(nm))
384
+ elif c.type == "namespace_import":
385
+ ids = [x for x in c.named_children if x.type == "identifier"]
386
+ if ids:
387
+ out[_t(ids[-1])] = (mod, "*")
388
+ elif c.type == "import_clause":
389
+ for x in c.named_children:
390
+ if x.type == "identifier":
391
+ out[_t(x)] = (mod, "default")
392
+ elif n.type == "variable_declarator":
393
+ v = n.child_by_field_name("value")
394
+ if v is not None and v.type == "call_expression" and _t(v.child_by_field_name("function")) == "require":
395
+ args = v.child_by_field_name("arguments")
396
+ mod = _t(args.named_children[0]).strip("'\"`") if args is not None and args.named_children else ""
397
+ nm = n.child_by_field_name("name")
398
+ if nm is not None and nm.type == "identifier":
399
+ out[_t(nm)] = (mod, "*")
400
+ elif nm is not None and nm.type == "object_pattern":
401
+ for c in nm.named_children:
402
+ if c.type == "shorthand_property_identifier_pattern":
403
+ out[_t(c)] = (mod, _t(c))
404
+ elif c.type == "pair_pattern":
405
+ out[_t(c.child_by_field_name("value"))] = (mod, _t(c.child_by_field_name("key")))
406
+ return out
407
+
408
+
409
+ def _ts_resolve(node, imports) -> tuple[str, str] | None:
410
+ """(module, name) a callee or constructor expression refers to: `Agent` imported from https, `https.Agent`,
411
+ `cp.execSync` with cp = require('child_process')."""
412
+ if node is None:
413
+ return None
414
+ if node.type == "identifier":
415
+ return imports.get(_t(node))
416
+ if node.type == "member_expression":
417
+ obj, prop = node.child_by_field_name("object"), node.child_by_field_name("property")
418
+ if obj is not None and obj.type == "identifier":
419
+ got = imports.get(_t(obj))
420
+ if got and got[1] in ("*", "default"):
421
+ return got[0], _t(prop)
422
+ if _t(obj) in ("http", "https", "crypto", "child_process") and not got:
423
+ return _t(obj), _t(prop)
424
+ return None
425
+
426
+
427
+ def _ts_fn(n):
428
+ names, fn = [], None
429
+ for a in _ancestors(n):
430
+ if a.type in ("function_declaration", "method_definition", "function_expression", "arrow_function", "function",
431
+ "generator_function_declaration"):
432
+ if fn is None:
433
+ fn = a
434
+ nm = a.child_by_field_name("name")
435
+ if nm is not None:
436
+ names.append(_t(nm))
437
+ elif a.parent is not None and a.parent.type == "variable_declarator":
438
+ names.append(_t(a.parent.child_by_field_name("name")))
439
+ if a.type in ("class_declaration", "class"):
440
+ nm = a.child_by_field_name("name")
441
+ if nm is not None:
442
+ names.append(_t(nm))
443
+ return fn, ".".join(reversed(names[:2]))
444
+
445
+
446
+ def _ts_async(fn) -> bool:
447
+ return fn is not None and any(c.type == "async" for c in fn.children)
448
+
449
+
450
+ def _ts_name(fn) -> str:
451
+ if fn is None:
452
+ return ""
453
+ nm = fn.child_by_field_name("name")
454
+ if nm is not None:
455
+ return _t(nm)
456
+ if fn.parent is not None and fn.parent.type == "variable_declarator":
457
+ return _t(fn.parent.child_by_field_name("name"))
458
+ return ""
459
+
460
+
461
+ def _ts_client_aside(n, fn) -> str:
462
+ name = _ts_name(fn)
463
+ if name == "constructor" or STARTUP_NAMES.search(name):
464
+ return f"built in a start-up function ({name})"
465
+ p = n.parent
466
+ while p is not None and p.type in ("await_expression", "parenthesized_expression", "as_expression", "non_null_expression"):
467
+ p = p.parent
468
+ if p is not None and p.type == "assignment_expression":
469
+ left = p.child_by_field_name("left")
470
+ if left is not None and left.type in ("member_expression", "subscript_expression"):
471
+ return "kept on the object (built once per object)"
472
+ if left is not None and left.type == "identifier":
473
+ return "kept in a module variable (built once)"
474
+ if p is not None and p.type in ("return_statement", "arrow_function"):
475
+ return "a factory: its callers decide how often it is built"
476
+ if p is not None and p.type == "variable_declarator":
477
+ var = _t(p.child_by_field_name("name"))
478
+ body = fn.child_by_field_name("body") if fn is not None else None
479
+ if body is not None and re.search(rf"\breturn\s+{re.escape(var)}\b", _t(body)):
480
+ return "a factory: its callers decide how often it is built"
481
+ for a in _ancestors(n):
482
+ if a == fn:
483
+ break
484
+ if a.type == "if_statement":
485
+ cond = _t(a.child_by_field_name("condition"))
486
+ if re.search(r"!\s*[\w.]+|=== ?(null|undefined)|== ?null", cond):
487
+ return "built once behind a guard"
488
+ return ""
489
+
490
+
491
+ def ts_sites(root: Path, files: list[str]) -> list[dict]:
492
+ out: list[dict] = []
493
+ for rel in files:
494
+ if rel.endswith(".d.ts") or ".min." in rel:
495
+ continue
496
+ src = read_text(root / rel)
497
+ if not src or not re.search(r"Agent|PrismaClient|Redis|createClient|Pool|MongoClient|axios|fetch\(|Sync\(|\.request\(|\.get\(", src):
498
+ continue
499
+ if vendored(rel, src):
500
+ continue
501
+ tree = parser("tsx" if rel.endswith((".tsx", ".jsx", ".js", ".mjs", ".cjs")) else "ts").parse(src.encode())
502
+ imports = _ts_imports(tree)
503
+ browser = (browser_path(rel) or bool(re.match(r"\s*['\"]use client['\"]", src)) or bool(BROWSER_TREE.search(rel))) \
504
+ and not SERVER_FILE.search(rel)
505
+ lines = src.splitlines()
506
+
507
+ def site(n, scenario, call, fn, sym, **kw):
508
+ ln = _line(n)
509
+ code = lines[ln - 1].strip()[:160] if 0 < ln <= len(lines) else ""
510
+ d = {"file": rel, "line": ln, "end_line": n.end_point[0] + 1, "language": "typescript", "runtime": "node", "symbol": sym,
511
+ "scenario": scenario, "call": call, "text": f"{scenario}:{call}:{code}", "code": code, "in_async": _ts_async(fn),
512
+ "function": _ts_name(fn) or (sym or "an inline handler" if fn is not None else ""), "browser": browser,
513
+ "in_function": fn is not None}
514
+ d.update(kw)
515
+ out.append(d)
516
+
517
+ for n in _walk(tree.root_node):
518
+ if n.type not in ("new_expression", "call_expression"):
519
+ continue
520
+ callee = n.child_by_field_name("constructor") or n.child_by_field_name("function")
521
+ ref = _ts_resolve(callee, imports)
522
+ fn, sym = _ts_fn(n)
523
+ args = n.child_by_field_name("arguments")
524
+ a = args.named_children if args is not None else []
525
+ if ref is not None and fn is not None:
526
+ mod = ref[0].replace("node:", "")
527
+ key = (ref[0], ref[1]) if (ref[0], ref[1]) in TS_CLIENTS else (mod, ref[1])
528
+ if ref[0] in ("ioredis",) and ref[1] in ("*", "default"):
529
+ key = ("ioredis", "default")
530
+ if key in TS_CLIENTS and (n.type == "new_expression" or ref[1] in ("create", "createClient")):
531
+ canon, replay = TS_CLIENTS[key]
532
+ opts = {}
533
+ if a and a[0].type == "object":
534
+ for pr in a[0].named_children:
535
+ if pr.type == "pair":
536
+ v = pr.child_by_field_name("value")
537
+ if v is not None and v.type in ("number", "true", "false"):
538
+ opts[_t(pr.child_by_field_name("key"))] = float(_t(v)) if v.type == "number" else v.type == "true"
539
+ deliberate = opts.get("keepAlive") is False or opts.get("maxCachedSessions") == 0
540
+ site(n, "client_per_call", canon, fn, sym, lib=canon.split(".")[0], replay=replay, kwargs=opts, dynamic=[],
541
+ aside="built not to reuse connections, on purpose (keepAlive false or maxCachedSessions 0)" if deliberate
542
+ else _ts_client_aside(n, fn), loop="")
543
+ continue
544
+ if (mod, ref[1]) in TS_BLOCKING and _ts_async(fn):
545
+ extra = {}
546
+ if ref[1] == "pbkdf2Sync" and len(a) >= 4:
547
+ try:
548
+ extra = {"iterations": int(_t(a[2]).replace("_", "")), "keylen": int(_t(a[3]).replace("_", ""))}
549
+ if len(a) >= 5 and a[4].type == "string":
550
+ extra["digest"] = _t(a[4]).strip("'\"")
551
+ except ValueError:
552
+ extra = {}
553
+ site(n, "blocking_in_async", ref[1], fn, sym, lib="", aside="", **extra)
554
+ continue
555
+ if mod == "axios" and ref[1] in HTTP_VERBS:
556
+ pos = {"get": 1, "delete": 1, "head": 1, "options": 1, "request": 0}.get(ref[1], 2)
557
+ cfg = a[pos] if len(a) > pos else None
558
+ has = cfg is not None and cfg.type == "object" and any(
559
+ pr.type == "pair" and _t(pr.child_by_field_name("key")) in ("timeout", "signal") for pr in cfg.named_children)
560
+ opaque = cfg is not None and (cfg.type != "object" or any(pr.type == "spread_element" for pr in cfg.named_children))
561
+ if not has:
562
+ site(n, "no_timeout", "axios", fn, sym, lib="axios",
563
+ aside="a default timeout is set in this file" if "defaults.timeout" in src
564
+ else "options built elsewhere" if opaque else "")
565
+ continue
566
+ if mod in ("http", "https") and ref[1] in ("get", "request"):
567
+ has = any(pr.type == "pair" and _t(pr.child_by_field_name("key")) in ("timeout", "signal")
568
+ for x in a if x.type == "object" for pr in x.named_children)
569
+ opaque = any(x.type in ("identifier", "member_expression", "spread_element") for x in a[1:2]) and not \
570
+ any(x.type == "arrow_function" for x in a[1:2])
571
+ if not has:
572
+ site(n, "no_timeout", f"{mod}.{ref[1]}", fn, sym, lib="", aside="options built elsewhere" if opaque else "")
573
+ continue
574
+ if n.type == "call_expression" and callee is not None and callee.type == "identifier" and _t(callee) == "fetch" \
575
+ and "fetch" not in imports:
576
+ has = any(pr.type in ("pair", "shorthand_property_identifier") and
577
+ (_t(pr.child_by_field_name("key")) if pr.type == "pair" else _t(pr)) == "signal"
578
+ for x in a[1:2] if x.type == "object" for pr in x.named_children)
579
+ opaque = len(a) > 1 and (a[1].type != "object" or any(pr.type == "spread_element" for pr in a[1].named_children))
580
+ if not has:
581
+ site(n, "no_timeout", "fetch", fn, sym, lib="", aside="options built elsewhere" if opaque else "")
582
+ return out
583
+
584
+
585
+ # --- Go ---------------------------------------------------------------------------------------------------------------------
586
+
587
+ GO_DEFAULT_CLIENT = {"http.Get", "http.Post", "http.Head", "http.PostForm", "http.DefaultClient.Do", "http.DefaultClient.Get",
588
+ "http.DefaultClient.Post", "http.DefaultClient.Head", "http.DefaultClient.PostForm"}
589
+ GO_OTHER_CLIENTS = {"redis.NewClient": "go-redis", "redis.NewClusterClient": "go-redis", "sql.Open": "database/sql",
590
+ "pgxpool.New": "pgx", "pgxpool.Connect": "pgx", "pgx.Connect": "pgx", "mongo.Connect": "mongo-driver",
591
+ "grpc.Dial": "grpc", "grpc.NewClient": "grpc", "grpc.DialContext": "grpc"}
592
+
593
+
594
+ def _go_fn(n):
595
+ for a in _ancestors(n):
596
+ if a.type in ("function_declaration", "method_declaration"):
597
+ nm = a.child_by_field_name("name")
598
+ return a, _t(nm)
599
+ if a.type == "func_literal":
600
+ continue
601
+ return None, ""
602
+
603
+
604
+ def _go_aside_client(n, fn, name) -> str:
605
+ if name in ("init", "main") or re.match(r"^(New|new|Make|make|Setup|setup|Init|init|Open|open|Connect|connect|Start|start)", name):
606
+ return f"built in a constructor or start-up function ({name})"
607
+ p = n.parent
608
+ while p is not None and p.type in ("unary_expression", "parenthesized_expression", "expression_list", "literal_element",
609
+ "keyed_element", "literal_value", "composite_literal"):
610
+ if p.type == "composite_literal" and p != n and _t(p.child_by_field_name("type")) != "http.Client":
611
+ return "part of a larger value (its owner decides)"
612
+ p = p.parent
613
+ if p is not None and p.type == "return_statement":
614
+ return "a factory: its callers decide how often it is built"
615
+ if p is not None and p.type == "assignment_statement":
616
+ left = p.child_by_field_name("left")
617
+ if left is not None and "." in _t(left):
618
+ return "kept on a struct (built once per value)"
619
+ for a in _ancestors(n):
620
+ if a == fn:
621
+ break
622
+ if a.type == "if_statement" and re.search(r"==\s*nil", _t(a.child_by_field_name("condition"))):
623
+ return "built once behind a guard"
624
+ if a.type == "call_expression" and re.search(r"\.Do$|once\.Do", _t(a.child_by_field_name("function"))):
625
+ return "built once (sync.Once)"
626
+ return ""
627
+
628
+
629
+ def go_sites(root: Path, files: list[str]) -> list[dict]:
630
+ out: list[dict] = []
631
+ for rel in files:
632
+ src = read_text(root / rel)
633
+ if not src or "net/http" not in src and not re.search(r"redis\.NewClient|sql\.Open|pgx|mongo\.Connect|grpc\.", src):
634
+ continue
635
+ tree = parser("go").parse(src.encode())
636
+ lines = src.splitlines()
637
+ deadline_in_file = bool(re.search(r"context\.With(Timeout|Deadline)|NewRequestWithContext|\.WithContext\(", src))
638
+
639
+ def site(n, scenario, call, fn, sym, **kw):
640
+ ln = _line(n)
641
+ code = lines[ln - 1].strip()[:160] if 0 < ln <= len(lines) else ""
642
+ d = {"file": rel, "line": ln, "end_line": n.end_point[0] + 1, "language": "go", "runtime": "go", "symbol": sym,
643
+ "scenario": scenario, "call": call, "text": f"{scenario}:{call}:{code}", "code": code, "in_async": False, "function": sym,
644
+ "in_function": fn is not None}
645
+ d.update(kw)
646
+ out.append(d)
647
+
648
+ for n in _walk(tree.root_node):
649
+ if n.type == "composite_literal":
650
+ ty = _t(n.child_by_field_name("type"))
651
+ body = n.child_by_field_name("body")
652
+ fields = {}
653
+ if body is not None:
654
+ for el in body.named_children:
655
+ if el.type == "keyed_element" and el.named_children:
656
+ fields[_t(el.named_children[0])] = el.named_children[-1]
657
+ fn, name = _go_fn(n)
658
+ if ty == "http.Transport" and fn is not None:
659
+ site(n, "client_per_call", "http.Transport", fn, name, lib="net/http", replay=True, kwargs={},
660
+ dynamic=sorted(fields), aside=_go_aside_client(n, fn, name), loop="")
661
+ elif ty == "http.Client":
662
+ tr = fields.get("Transport")
663
+ has_timeout = "Timeout" in fields
664
+ rh = tr is not None and "ResponseHeaderTimeout" in _t(tr)
665
+ if not has_timeout:
666
+ aside = "its transport has a response header timeout" if rh else \
667
+ "a request context may carry a deadline (context.WithTimeout or NewRequestWithContext in this file)" if deadline_in_file else ""
668
+ site(n, "no_timeout", "http.Client{}", fn, name, lib="net/http", aside=aside)
669
+ elif n.type == "call_expression":
670
+ f = _t(n.child_by_field_name("function"))
671
+ fn, name = _go_fn(n)
672
+ if f in GO_DEFAULT_CLIENT:
673
+ site(n, "no_timeout", f, fn, name, lib="net/http", aside="")
674
+ elif f.endswith("DefaultTransport.(*http.Transport).Clone") and fn is not None:
675
+ site(n, "client_per_call", "http.Transport", fn, name, lib="net/http", replay=True, kwargs={}, dynamic=["Clone"],
676
+ aside=_go_aside_client(n, fn, name), loop="")
677
+ elif f in GO_OTHER_CLIENTS and fn is not None:
678
+ site(n, "client_per_call", f, fn, name, lib=GO_OTHER_CLIENTS[f], replay=False, kwargs={}, dynamic=[],
679
+ aside=_go_aside_client(n, fn, name), loop="")
680
+ return out
681
+
682
+
683
+ # --- Rust -------------------------------------------------------------------------------------------------------------------
684
+
685
+ RUST_START = re.compile(r"^(new|default|main|init|setup|build|builder|create|open|connect|start|from_\w+|with_\w+|try_new|new_\w+|"
686
+ r"make_\w+|init_\w+|setup_\w+|build_\w+|create_\w+)$")
687
+ RUST_ONCE_CALL = re.compile(r"(get_or_init|get_or_try_init|call_once|get_or_insert_with|or_insert_with)$")
688
+
689
+
690
+ def _rust_uses(src: str) -> dict[str, str]:
691
+ """Imported last segments -> full paths (`use reqwest::{Client, ClientBuilder}`; `use redis::Client as R`)."""
692
+ out: dict[str, str] = {}
693
+ for m in re.finditer(r"(?m)^\s*(?:pub\s+)?use\s+([\w:]+)::\{([^}]*)\}\s*;", src):
694
+ for part in m.group(2).split(","):
695
+ bits = part.strip().split(" as ")
696
+ if bits[0].strip() and re.fullmatch(r"[\w:]+", bits[0].strip()):
697
+ out[(bits[-1] if len(bits) > 1 else bits[0].split("::")[-1]).strip()] = f"{m.group(1)}::{bits[0].strip()}"
698
+ for m in re.finditer(r"(?m)^\s*(?:pub\s+)?use\s+([\w:]+?)(?:\s+as\s+(\w+))?\s*;", src):
699
+ out[m.group(2) or m.group(1).split("::")[-1]] = m.group(1)
700
+ return out
701
+
702
+
703
+ def _rust_path(text: str, uses: dict) -> str:
704
+ """`Client::new` with `use reqwest::Client` -> `reqwest::Client::new`."""
705
+ head = text.split("::")[0]
706
+ if head in uses and not text.startswith(uses[head]):
707
+ return uses[head] + text[len(head):]
708
+ return text
709
+
710
+
711
+ def _rust_fn(n):
712
+ """(innermost fn item, its name, whether an async fn or async block holds the node (before any closure), whether a
713
+ closure handed to spawn_blocking / block_in_place stands between)."""
714
+ fn, name, is_async, offloaded, seen_closure = None, "", False, False, False
715
+ for a in _ancestors(n):
716
+ if a.type == "closure_expression" and fn is None:
717
+ p = a.parent.parent if a.parent is not None and a.parent.type == "arguments" else None
718
+ if p is not None and p.type == "call_expression" and re.search(r"(spawn_blocking|block_in_place|thread::spawn|spawn)$",
719
+ _t(p.child_by_field_name("function"))):
720
+ offloaded = True
721
+ seen_closure = True
722
+ if a.type == "async_block" and fn is None:
723
+ is_async = True
724
+ if a.type == "function_item":
725
+ fn = a
726
+ name = _t(a.child_by_field_name("name"))
727
+ mods = next((c for c in a.children if c.type == "function_modifiers"), None)
728
+ if mods is not None and "async" in _t(mods):
729
+ is_async = True
730
+ break
731
+ return fn, name, is_async, offloaded
732
+
733
+
734
+ def _rust_chain_top(n):
735
+ """The outermost call of a method chain starting at `n` (Client::builder().timeout(..).build())."""
736
+ top = n
737
+ while top.parent is not None and top.parent.type == "field_expression" and top.parent.parent is not None \
738
+ and top.parent.parent.type == "call_expression":
739
+ top = top.parent.parent
740
+ return top
741
+
742
+
743
+ def _rust_client_aside(top, fn, name) -> str:
744
+ if RUST_START.match(name or ""):
745
+ return f"built in a constructor or start-up function ({name})"
746
+ for a in _ancestors(top):
747
+ if a == fn:
748
+ break
749
+ if a.type == "call_expression" and RUST_ONCE_CALL.search(_t(a.child_by_field_name("function"))):
750
+ return "built once (OnceCell, OnceLock or a map entry)"
751
+ if a.type == "field_initializer" or a.type == "shorthand_field_initializer":
752
+ return "kept on a struct (built once per value)"
753
+ if a.type == "assignment_expression" and _t(a.child_by_field_name("left")).startswith("self."):
754
+ return "kept on a struct (built once per value)"
755
+ if a.type == "return_expression":
756
+ return "a factory: its callers decide how often it is built"
757
+ body = fn.child_by_field_name("body") if fn is not None else None
758
+ if body is not None and body.named_children:
759
+ last = body.named_children[-1]
760
+ if last.type not in ("expression_statement", "let_declaration") and any(x == last for x in _ancestors(top)) or last == top:
761
+ return "a factory: its callers decide how often it is built"
762
+ return ""
763
+
764
+
765
+ def _rust_loop(n, fn) -> str:
766
+ for a in _ancestors(n):
767
+ if a == fn:
768
+ return ""
769
+ if a.type in ("while_expression", "loop_expression"):
770
+ return "retry"
771
+ if a.type == "for_expression":
772
+ return "retry" if RETRY_NAMES.search(_t(a.child_by_field_name("pattern")) + " " + _t(a.child_by_field_name("value"))[:80]) \
773
+ else "each"
774
+ return ""
775
+
776
+
777
+ def _crate_of(root: Path, rel: str) -> str:
778
+ p = Path(rel).parent
779
+ while str(p) not in ("", "."):
780
+ if (Path(root) / p / "Cargo.toml").exists():
781
+ return str(p)
782
+ p = p.parent
783
+ return ""
784
+
785
+
786
+ def rust_sites(root: Path, files: list[str]) -> list[dict]:
787
+ out: list[dict] = []
788
+ # a crate whose requests set `.timeout(...)` anywhere: a client built without one may be used only with per-request
789
+ # deadlines (the client is handed to code in other files), so its "no timeout" is set aside, not claimed
790
+ timed_crates = set()
791
+ for rel in files:
792
+ txt = read_text(root / rel) or ""
793
+ if re.search(r"\.timeout\(|tokio::time::timeout|time::timeout\(", txt):
794
+ timed_crates.add(_crate_of(root, rel))
795
+ for rel in files:
796
+ src = read_text(root / rel)
797
+ if not src or not re.search(r"reqwest|redis|hyper|ureq|thread::sleep|Command|sleep\(", src):
798
+ continue
799
+ tree = parser("rust").parse(src.encode())
800
+ uses = _rust_uses(src)
801
+ lines = src.splitlines()
802
+ request_timeout = bool(re.search(r"\.timeout\(|tokio::time::timeout|time::timeout\(|\btimeout\(Duration", src)) or \
803
+ bool(timed_crates)
804
+ std_command = "std::process::Command" in src and "tokio::process::Command" not in src
805
+
806
+ def site(n, scenario, call, fn, name, **kw):
807
+ ln = _line(n)
808
+ code = lines[ln - 1].strip()[:160] if 0 < ln <= len(lines) else ""
809
+ d = {"file": rel, "line": ln, "end_line": n.end_point[0] + 1, "language": "rust", "runtime": "rust", "symbol": name,
810
+ "scenario": scenario, "call": call, "text": f"{scenario}:{call}:{code}", "code": code, "function": name,
811
+ "in_function": fn is not None}
812
+ d.update(kw)
813
+ out.append(d)
814
+
815
+ for n in _walk(tree.root_node):
816
+ if n.type != "call_expression":
817
+ continue
818
+ f = n.child_by_field_name("function")
819
+ ftext = _t(f)
820
+ path = _rust_path(ftext, uses) if f is not None and f.type in ("scoped_identifier", "identifier") else ""
821
+ fn, name, is_async, offloaded = _rust_fn(n)
822
+ if path in ("reqwest::Client::new", "reqwest::Client::builder", "reqwest::ClientBuilder::new"):
823
+ top = _rust_chain_top(n)
824
+ chain = _t(top)
825
+ if fn is not None:
826
+ site(n, "client_per_call", "reqwest::Client", fn, name, lib="reqwest", replay=True, kwargs={}, dynamic=[],
827
+ aside=_rust_client_aside(top, fn, name), loop=_rust_loop(n, fn))
828
+ if not re.search(r"\.(timeout|read_timeout)\(", chain):
829
+ site(n, "no_timeout", "reqwest::Client", fn, name, lib="reqwest",
830
+ aside="requests in this repository set timeouts per call (the client may be used only with them)" if request_timeout else "")
831
+ elif path == "reqwest::get":
832
+ if fn is not None and _rust_loop(n, fn):
833
+ loop = _rust_loop(n, fn)
834
+ site(n, "client_per_call", "reqwest::get", fn, name, lib="reqwest", replay=True, kwargs={}, dynamic=[], loop=loop,
835
+ implicit=True, aside="a retry, poll or pagination loop" if loop == "retry" else "")
836
+ site(n, "no_timeout", "reqwest::get", fn, name, lib="reqwest",
837
+ aside="a wrapper in this file sets a timeout" if re.search(r"tokio::time::timeout|time::timeout\(", src) else "")
838
+ elif path in ("redis::Client::open",) and fn is not None:
839
+ site(n, "client_per_call", "redis::Client", fn, name, lib="redis", replay=True, kwargs={}, dynamic=[],
840
+ aside=_rust_client_aside(_rust_chain_top(n), fn, name), loop=_rust_loop(n, fn))
841
+ elif re.match(r"^(hyper::Client::(new|builder)|hyper_util::client::legacy::Client::builder|ureq::(agent|AgentBuilder::new))$", path) \
842
+ and fn is not None:
843
+ site(n, "client_per_call", path.rsplit("::", 1)[0], fn, name, lib=path.split("::")[0], replay=False, kwargs={},
844
+ dynamic=[], aside=_rust_client_aside(_rust_chain_top(n), fn, name), loop=_rust_loop(n, fn))
845
+ # --- blocking inside async code -----------------------------------------------------------------------------
846
+ elif is_async and fn is not None:
847
+ call = ""
848
+ if path in ("std::thread::sleep", "thread::sleep") or (ftext == "sleep" and uses.get("sleep") == "std::thread::sleep"):
849
+ call = "std::thread::sleep"
850
+ elif f is not None and f.type == "field_expression" and _t(f.child_by_field_name("field")) in ("output", "status") \
851
+ and "Command::new" in _t(f.child_by_field_name("value")) and std_command:
852
+ call = "std::process::Command.output"
853
+ if call:
854
+ site(n, "blocking_in_async", call, fn, name, lib="",
855
+ aside="inside spawn_blocking or block_in_place" if offloaded else "")
856
+ return out
857
+
858
+
859
+ # --- Java and Kotlin ------------------------------------------------------------------------------------------------------------
860
+
861
+ JAVA_CLIENT = { # creation text -> (canonical, replayable)
862
+ "HttpClient.newHttpClient": ("java.net.http.HttpClient", True), "HttpClient.newBuilder": ("java.net.http.HttpClient", True),
863
+ "new OkHttpClient": ("OkHttpClient", False), "new OkHttpClient.Builder": ("OkHttpClient", False),
864
+ "HttpClients.createDefault": ("Apache HttpClient", False), "HttpClients.custom": ("Apache HttpClient", False),
865
+ "HttpClientBuilder.create": ("Apache HttpClient", False), "new RestTemplate": ("RestTemplate", False),
866
+ "WebClient.create": ("WebClient", False), "WebClient.builder": ("WebClient", False),
867
+ }
868
+ JAVA_START = re.compile(r"^(main|init|setup|setUp|create\w*|build\w*|new\w*|make\w*|configure\w*|get\w*Client|\w*[Cc]lient|"
869
+ r"\w*Template|\w*Factory|initialize\w*|start\w*|open\w*)$")
870
+ JAVA_BEAN = re.compile(r"@(Bean|PostConstruct|Produces|Provides|Singleton|ApplicationScoped|Startup)\b")
871
+ JAVA_BLOCKING = re.compile(r"\bThread\.sleep\(|\.openConnection\(|\.getInputStream\(|\brestTemplate\.\w+\(|\.send\(|\.execute\(\)|"
872
+ r"\.block\(\)|\.executeQuery\(|TimeUnit\.\w+\.sleep\(")
873
+
874
+
875
+ def _java_creation(n) -> str:
876
+ if n.type == "object_creation_expression":
877
+ return "new " + _t(n.child_by_field_name("type"))
878
+ if n.type == "method_invocation":
879
+ obj, nm = n.child_by_field_name("object"), n.child_by_field_name("name")
880
+ return f"{_t(obj)}.{_t(nm)}" if obj is not None else _t(nm)
881
+ return ""
882
+
883
+
884
+ def _java_method(n):
885
+ for a in _ancestors(n):
886
+ if a.type in ("method_declaration", "constructor_declaration", "field_declaration", "static_initializer",
887
+ "class_body", "enum_body"):
888
+ return a
889
+ return None
890
+
891
+
892
+ def _java_chain_top(n):
893
+ top = n
894
+ while top.parent is not None and top.parent.type == "method_invocation" and top.parent.child_by_field_name("object") == top:
895
+ top = top.parent
896
+ return top
897
+
898
+
899
+ def _java_client_aside(top, m) -> str:
900
+ if m is None or m.type != "method_declaration":
901
+ return "built once (a field, a constructor or a static block)"
902
+ head = _t(m)[: max(0, _t(m).find("{"))] if "{" in _t(m) else _t(m)
903
+ if JAVA_BEAN.search(head):
904
+ return "built once (a bean or start-up method)"
905
+ name = _t(m.child_by_field_name("name"))
906
+ if JAVA_START.match(name):
907
+ return f"built in a constructor, factory or start-up method ({name})"
908
+ for a in _ancestors(top):
909
+ if a == m:
910
+ break
911
+ if a.type == "return_statement":
912
+ return "a factory: its callers decide how often it is built"
913
+ if a.type == "assignment_expression" and (_t(a.child_by_field_name("left")).startswith("this.") or
914
+ "." not in _t(a.child_by_field_name("left"))):
915
+ left = _t(a.child_by_field_name("left"))
916
+ if left.startswith("this.") or re.search(rf"\b(private|protected|public)?\s*[\w<>.,\s]+\s+{re.escape(left)}\s*[;=]",
917
+ _t(m.parent) if m.parent is not None else ""):
918
+ return "kept on the object (built once per object)"
919
+ if a.type == "if_statement" and re.search(r"==\s*null", _t(a.child_by_field_name("condition"))):
920
+ return "built once behind a guard"
921
+ return ""
922
+
923
+
924
+ def _java_loop(n, m) -> str:
925
+ for a in _ancestors(n):
926
+ if a == m:
927
+ return ""
928
+ if a.type in ("while_statement", "do_statement"):
929
+ return "retry"
930
+ if a.type in ("for_statement", "enhanced_for_statement"):
931
+ return "retry" if RETRY_NAMES.search(_t(a)[:120]) else "each"
932
+ return ""
933
+
934
+
935
+ def java_sites(root: Path, files: list[str]) -> list[dict]:
936
+ out: list[dict] = []
937
+ for rel in files:
938
+ src = read_text(root / rel)
939
+ if not src or not re.search(r"HttpClient|OkHttp|RestTemplate|WebClient|openConnection|CompletableFuture|Mono|Flux", src):
940
+ continue
941
+ tree = parser("java").parse(src.encode())
942
+ lines = src.splitlines()
943
+ virtual = bool(re.search(r"newVirtualThreadPerTaskExecutor|Thread\.ofVirtual|virtual\.enabled", src))
944
+ reactor = "reactor.core.publisher" in src
945
+
946
+ def site(n, scenario, call, m, **kw):
947
+ ln = _line(n)
948
+ code = lines[ln - 1].strip()[:160] if 0 < ln <= len(lines) else ""
949
+ name = _t(m.child_by_field_name("name")) if m is not None and m.type in ("method_declaration", "constructor_declaration") else ""
950
+ cls = next((_t(a.child_by_field_name("name")) for a in _ancestors(n) if a.type in ("class_declaration", "record_declaration",
951
+ "enum_declaration")), "")
952
+ d = {"file": rel, "line": ln, "end_line": n.end_point[0] + 1, "language": "java", "runtime": "java",
953
+ "symbol": f"{cls}.{name}".strip("."), "scenario": scenario, "call": call, "text": f"{scenario}:{call}:{code}",
954
+ "code": code, "function": name, "in_function": m is not None and m.type == "method_declaration"}
955
+ d.update(kw)
956
+ out.append(d)
957
+
958
+ for n in _walk(tree.root_node):
959
+ if n.type not in ("object_creation_expression", "method_invocation"):
960
+ continue
961
+ created = _java_creation(n)
962
+ m = _java_method(n)
963
+ if created in JAVA_CLIENT:
964
+ canon, replay = JAVA_CLIENT[created]
965
+ top = _java_chain_top(n)
966
+ chain = _t(top)
967
+ site(n, "client_per_call", canon, m, lib=canon, replay=replay, kwargs={}, dynamic=[], aside=_java_client_aside(top, m),
968
+ loop=_java_loop(n, m))
969
+ if canon == "RestTemplate" and not n.child_by_field_name("arguments").named_children \
970
+ and not re.search(r"setReadTimeout|RequestFactory|RestTemplateBuilder|setConnectTimeout", src):
971
+ site(n, "no_timeout", "RestTemplate", m, lib="RestTemplate", aside="")
972
+ elif canon == "Apache HttpClient" and not re.search(r"RequestConfig|setResponseTimeout|setSocketTimeout|ConnectionConfig", src):
973
+ site(n, "no_timeout", "Apache HttpClient", m, lib="Apache HttpClient", aside="")
974
+ elif canon == "WebClient" and not re.search(r"responseTimeout|\.timeout\(|ReadTimeoutHandler", src):
975
+ site(n, "no_timeout", "WebClient", m, lib="WebClient", aside="")
976
+ continue
977
+ if created == "HttpRequest.newBuilder" and m is not None:
978
+ chain = _t(_java_chain_top(n))
979
+ if ".timeout(" not in chain:
980
+ site(n, "no_timeout", "HttpRequest.newBuilder", m, lib="java.net.http",
981
+ aside="the response is awaited with a deadline in this file" if re.search(r"orTimeout\(|\.get\(\s*\d+\s*,\s*TimeUnit", src)
982
+ else "")
983
+ continue
984
+ if n.type == "method_invocation" and _t(n.child_by_field_name("name")) == "openConnection" and m is not None:
985
+ if "setReadTimeout" not in _t(m):
986
+ site(n, "no_timeout", "HttpURLConnection", m, lib="java.net",
987
+ aside="a process-wide default read timeout is set" if "sun.net.client.defaultReadTimeout" in src else "")
988
+ continue
989
+ # --- blocking work on the common pool or in a reactive chain ------------------------------------------------------
990
+ nm = _t(n.child_by_field_name("name"))
991
+ if nm in ("supplyAsync", "runAsync") and "CompletableFuture" in _t(n.child_by_field_name("object")):
992
+ args = n.child_by_field_name("arguments")
993
+ if args is not None and len(args.named_children) == 1:
994
+ body = _t(args.named_children[0])
995
+ hit = JAVA_BLOCKING.search(body)
996
+ if hit:
997
+ call = "Thread.sleep" if "sleep" in hit.group(0) else "blocking I/O (" + hit.group(0).strip(".(") + ")"
998
+ site(n, "blocking_in_async", call, m, lib="", pool="common",
999
+ aside="runs on virtual threads" if virtual else "")
1000
+ elif reactor and nm in ("map", "flatMap", "doOnNext", "filter", "handle", "concatMap") and m is not None:
1001
+ args = n.child_by_field_name("arguments")
1002
+ body = _t(args) if args is not None else ""
1003
+ hit = JAVA_BLOCKING.search(body)
1004
+ if hit and "publishOn" not in _t(_java_chain_top(n)) and "subscribeOn" not in _t(_java_chain_top(n)):
1005
+ site(n, "blocking_in_async", "reactor: " + hit.group(0).strip(".("), m, lib="reactor", aside="")
1006
+ return out
1007
+
1008
+
1009
+ KT_FUN = re.compile(r"(?m)^\s*(?:(?:private|public|internal|protected|override|open|inline)\s+)*(suspend\s+)?fun\s+(?:<[^>]*>\s*)?(?:[\w.]+\.)?(\w+)\s*\(")
1010
+
1011
+
1012
+ def kotlin_sites(root: Path, files: list[str]) -> list[dict]:
1013
+ """Kotlin by text (no Kotlin grammar is installed): a client built inside a `fun`, java.net.http requests without a
1014
+ timeout, and blocking calls in a `suspend fun` outside `withContext(Dispatchers.IO)`. Brace-counted function bodies."""
1015
+ out: list[dict] = []
1016
+ for rel in files:
1017
+ src = read_text(root / rel)
1018
+ if not src or not re.search(r"HttpClient|OkHttpClient|RestTemplate|WebClient|Thread\.sleep|\.execute\(\)", src):
1019
+ continue
1020
+ lines = src.splitlines()
1021
+ for fm in KT_FUN.finditer(src):
1022
+ start = src.find("{", fm.end())
1023
+ eq = src.find("=", fm.end())
1024
+ if start < 0 or (0 <= eq < start and src[fm.end():eq].count("(") <= src[fm.end():eq].count(")")):
1025
+ continue
1026
+ depth, i = 0, start
1027
+ while i < len(src):
1028
+ depth += {"{": 1, "}": -1}.get(src[i], 0)
1029
+ if depth == 0:
1030
+ break
1031
+ i += 1
1032
+ body = src[start:i]
1033
+ name, suspend = fm.group(2), bool(fm.group(1))
1034
+
1035
+ def at(off):
1036
+ return src.count("\n", 0, start + off) + 1
1037
+
1038
+ def site(off, scenario, call, **kw):
1039
+ ln = at(off)
1040
+ code = lines[ln - 1].strip()[:160] if 0 < ln <= len(lines) else ""
1041
+ d = {"file": rel, "line": ln, "end_line": ln, "language": "kotlin", "runtime": "java", "symbol": name, "scenario": scenario,
1042
+ "call": call, "text": f"{scenario}:{call}:{code}", "code": code, "function": name, "in_function": True}
1043
+ d.update(kw)
1044
+ out.append(d)
1045
+ for cm in re.finditer(r"HttpClient\.newHttpClient\(\)|HttpClient\.newBuilder\(\)|\bOkHttpClient\(\)|OkHttpClient\.Builder\(\)|"
1046
+ r"\bRestTemplate\(\)|WebClient\.(create|builder)\(", body):
1047
+ text = cm.group(0)
1048
+ canon = "java.net.http.HttpClient" if "newHttpClient" in text or "newBuilder" in text else \
1049
+ "OkHttpClient" if "OkHttp" in text else "RestTemplate" if "RestTemplate" in text else "WebClient"
1050
+ before = body[max(0, cm.start() - 80):cm.start()]
1051
+ aside = f"built in a factory or start-up function ({name})" if JAVA_START.match(name) else \
1052
+ "kept on the object (built once per object)" if re.search(r"this\.\w+\s*=\s*$|by lazy", before) else \
1053
+ "a factory: its callers decide how often it is built" if re.search(r"return\s*$", before) else ""
1054
+ site(cm.start(), "client_per_call", canon, lib=canon, replay=canon == "java.net.http.HttpClient", kwargs={}, dynamic=[],
1055
+ aside=aside, loop="")
1056
+ for cm in re.finditer(r"HttpRequest\.newBuilder\(", body):
1057
+ stmt = body[cm.start():body.find("build()", cm.start()) + 7] if "build()" in body[cm.start():] else body[cm.start():cm.start() + 300]
1058
+ if ".timeout(" not in stmt:
1059
+ site(cm.start(), "no_timeout", "HttpRequest.newBuilder", lib="java.net.http", aside="")
1060
+ if suspend:
1061
+ for cm in re.finditer(r"\bThread\.sleep\(|\.execute\(\)", body):
1062
+ pre = body[:cm.start()]
1063
+ wrapped = pre.count("withContext(Dispatchers.IO") > 0 and pre.rfind("withContext(Dispatchers.IO") > pre.rfind("}")
1064
+ site(cm.start(), "blocking_in_async", "suspend: " + cm.group(0).strip(".("), lib="coroutines",
1065
+ aside="inside withContext(Dispatchers.IO)" if wrapped else "")
1066
+ return out
1067
+
1068
+
1069
+ EXTRACTORS = {"python": python_sites, "typescript": ts_sites, "go": go_sites, "rust": rust_sites, "java": java_sites}
1070
+
1071
+
1072
+ def sites(root: Path, by_lang: dict, log=None) -> list[dict]:
1073
+ out: list[dict] = []
1074
+ for lang, files in sorted((by_lang or {}).items()):
1075
+ fx = EXTRACTORS.get(lang)
1076
+ if fx is None:
1077
+ continue
1078
+ try:
1079
+ out.extend(fx(Path(root), list(files)))
1080
+ except Exception as e: # noqa: BLE001 -- one language must not lose the others
1081
+ if log:
1082
+ log(f"calls: {lang} extraction stopped ({type(e).__name__}: {e})")
1083
+ # Kotlin is not one of discovery's languages: its tracked .kt files are read here (sources only, never .env files)
1084
+ kt = list((by_lang or {}).get("kotlin") or [])
1085
+ if not kt:
1086
+ try:
1087
+ from ...discover import list_files
1088
+ kt = [f for f in list_files(Path(root)) if f.endswith(".kt")]
1089
+ except Exception: # noqa: BLE001
1090
+ kt = []
1091
+ if kt:
1092
+ try:
1093
+ out.extend(kotlin_sites(Path(root), kt))
1094
+ except Exception as e: # noqa: BLE001
1095
+ if log:
1096
+ log(f"calls: kotlin extraction stopped ({type(e).__name__}: {e})")
1097
+ return out