Repository navigation
Expand file tree
/
Copy pathgraph_query.py
More file actions
718 lines (610 loc) · 24.1 KB
/
Copy pathgraph_query.py
File metadata and controls
718 lines (610 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
"""Deterministic graph queries for agents and the `cgr graph` commands.
`query_code_graph` turns natural language into Cypher through an LLM, which
is the wrong shape for "go to definition" or "find callers": those must be
exact and repeatable. Everything here is fixed Cypher scoped to one project
plus client-side walks over the fetched rows, with every result list
sorted, so the same graph always yields the same JSON (issue #1523).
`callers` and `callees` return one row per call SITE: the CALLS edges carry
the site location from issue #1522, so an agent can jump to, check, or
rewrite each call. Edges written without a site (libclang macro uses,
Roslyn facts, trace write-back) return `null` positions.
"""
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
from typing import TypedDict
from . import constants as cs
from . import cypher_queries as cq
from .dead_code import (
_is_test_symbol,
_node_props,
_NodeId,
_rust_test_fn_spans,
_rust_test_modules_from_nodes,
)
from .types_defs import PropertyDict, ResultRow
from .utils.source_extraction import extract_source_lines
QueryFn = Callable[[str, PropertyDict | None], list[ResultRow]]
_DEFINITION_LABELS = frozenset(
{
cs.NodeLabel.FUNCTION.value,
cs.NodeLabel.METHOD.value,
cs.NodeLabel.CLASS.value,
cs.NodeLabel.INTERFACE.value,
cs.NodeLabel.ENUM.value,
cs.NodeLabel.TYPE.value,
cs.NodeLabel.UNION.value,
cs.NodeLabel.MODULE.value,
}
)
_REACH_RELS = frozenset(
{
cs.RelationshipType.CALLS.value,
cs.RelationshipType.REFERENCES.value,
cs.RelationshipType.INSTANTIATES.value,
}
)
class SymbolRow(TypedDict):
label: str
qualified_name: str
path: str | None
start_line: int | None
end_line: int | None
class DefinitionRow(SymbolRow):
name: str | None
docstring: str | None
source: str | None
found: bool
class EndpointRow(TypedDict):
endpoint: str
kind: str | None
label: str
handler: str
path: str | None
callers: int
class EndpointCallerRow(TypedDict):
label: str
qualified_name: str
path: str | None
url: str | None
direction: str | None
endpoint: str
handler: str
class RemoteDependencyRow(TypedDict):
label: str
qualified_name: str
path: str | None
url: str | None
direction: str | None
endpoint: str | None
handler: str | None
handler_project: str | None
class CallSiteRow(TypedDict):
label: str
qualified_name: str
path: str | None
line: int | None
col: int | None
end_line: int | None
end_col: int | None
arg_count: int | None
kwarg_names: list[str] | None
resolution: str | None
depth: int
through: str
class RelatedRow(TypedDict):
label: str
qualified_name: str
path: str | None
relationship: str
class ImporterRow(TypedDict):
module: str
path: str | None
line: int | None
col: int | None
end_line: int | None
end_col: int | None
alias: str | None
imported_name: str | None
class TestReachRow(TypedDict):
label: str
qualified_name: str
path: str | None
depth: int
through: str
def _owner_check(fetch_all: QueryFn, project_name: str) -> Callable[[str], bool]:
"""Whether `project_name`, and not a longer-named registered project it
is a dotted prefix of, owns a qualified name (issue #1982).
Every read here is scoped by `STARTS WITH $project_prefix`, and `foo.`
selects `foo.bar`'s rows too. The owner is the LONGEST registered
project name the qn sits under, the way the updater and the gloss
repair decide it; the project list is read once per call, and a failed
read keeps the prefix rule rather than dropping every row.
"""
prefix = _prefix(project_name)
names: set[str] = {project_name}
try:
rows = fetch_all(cq.CYPHER_LIST_PROJECTS, None)
except Exception:
rows = []
for row in rows:
name = row.get(cs.KEY_NAME)
if isinstance(name, str) and name:
names.add(name)
longest_first = sorted(names, key=len, reverse=True)
def owns(qn: str) -> bool:
if qn != project_name and not qn.startswith(prefix):
return False
for name in longest_first:
if qn == name or qn.startswith(f"{name}{cs.SEPARATOR_DOT}"):
return name == project_name
return True
return owns
def _prefix(project_name: str) -> str:
return f"{project_name}{cs.SEPARATOR_DOT}"
def _text_qn(row: ResultRow) -> str:
return str(row.get(cs.KEY_QUALIFIED_NAME, ""))
def _opt_int(value: object) -> int | None:
return value if isinstance(value, int) and not isinstance(value, bool) else None
def _opt_str(value: object) -> str | None:
return value if isinstance(value, str) else None
def _symbol_row(row: ResultRow) -> SymbolRow:
return SymbolRow(
label=str(row.get(cs.KEY_LABEL, "")),
qualified_name=str(row.get(cs.KEY_QUALIFIED_NAME, "")),
path=_opt_str(row.get(cs.KEY_PATH)),
start_line=_opt_int(row.get(cs.KEY_START_LINE)),
end_line=_opt_int(row.get(cs.KEY_END_LINE)),
)
def _symbol_key(row: SymbolRow) -> tuple[str, str]:
return (row["qualified_name"], row["path"] or "")
def parse_location(target: str) -> tuple[str, int] | None:
"""`(path, line)` when `target` is a `path:line` location, else None.
One parser for every tool that accepts a resolve target, so "is this a
location" is answered the same way by `resolve` and by anything that
decides differently for a location (a gloss anchors to the innermost
definition spanning a line, and refuses an ambiguous NAME).
"""
path, sep, line_text = target.rpartition(cs.CHAR_COLON)
if sep and line_text.isdigit() and path:
return path, int(line_text)
return None
# --- resolve ------------------------------------------------------------------
def resolve(fetch_all: QueryFn, project_name: str, target: str) -> list[SymbolRow]:
"""Definitions a name or `path:line` refers to, exact first, then suffix.
`target` is a qualified name, a bare name (`helper`, `Store.get`), or
`path:line` (repo-relative path and 1-based line). Names match on the
node's `name` or as a dotted suffix of its qualified name; a location
returns the innermost definitions spanning that line.
"""
prefix = _prefix(project_name)
owns = _owner_check(fetch_all, project_name)
location = parse_location(target)
if location is not None:
path, line = location
rows = fetch_all(
cq.CYPHER_GRAPH_RESOLVE_LOCATION,
{
cs.KEY_PROJECT_PREFIX: prefix,
cs.KEY_PATH: path,
cs.KEY_LINE: line,
},
)
symbols = [_symbol_row(r) for r in rows if owns(_text_qn(r))]
# Innermost first: the tightest span is what the line "is in".
symbols.sort(
key=lambda s: (
(s["end_line"] or 0) - (s["start_line"] or 0),
s["qualified_name"],
)
)
return symbols
rows = fetch_all(
cq.CYPHER_GRAPH_RESOLVE_NAME,
{
cs.KEY_PROJECT_PREFIX: prefix,
cs.KEY_NAME: target.rsplit(cs.SEPARATOR_DOT, 1)[-1],
cs.KEY_SUFFIX: f"{cs.SEPARATOR_DOT}{target}",
cs.KEY_QN: target,
},
)
symbols = [_symbol_row(r) for r in rows if owns(_text_qn(r))]
exact = [s for s in symbols if s["qualified_name"] == target]
suffix = [
s
for s in symbols
if s["qualified_name"] != target
and s["qualified_name"].endswith(f"{cs.SEPARATOR_DOT}{target}")
]
by_name = [s for s in symbols if s not in exact and s not in suffix]
ordered: list[SymbolRow] = []
for bucket in (exact, suffix, by_name):
ordered.extend(sorted(bucket, key=_symbol_key))
return ordered
# --- definition ---------------------------------------------------------------
def source_root_for(
fetch_all: QueryFn, project_name: str, repo_root: Path
) -> Path | None:
"""`repo_root` when the graph project was indexed from it, else None.
A definition of another project carries a relative path that may also
exist under `repo_root`; reading it there would return the wrong file. A
matching project name is not enough either: the Project node's stored
root path must be this repository.
"""
rows = fetch_all(
cq.CYPHER_PROJECT_ROOT_PATH,
{
cs.KEY_PROJECT_NAME: project_name,
cs.KEY_PROJECT_PREFIX: _prefix(project_name),
},
)
stored = _opt_str(rows[0].get(cs.KEY_ROOT_PATH)) if rows else None
if not stored:
return None
local = repo_root.resolve()
return local if Path(stored).resolve() == local else None
def definition(
fetch_all: QueryFn, project_name: str, qualified_name: str, repo_root: Path | None
) -> DefinitionRow:
"""File, span, docstring and source of one definition.
Source is read from `repo_root` when the node's repo-relative path stays
inside it; a graph indexed elsewhere still answers with the span.
"""
rows = fetch_all(
cq.CYPHER_GRAPH_DEFINITION,
{cs.KEY_PROJECT_PREFIX: _prefix(project_name), cs.KEY_QN: qualified_name},
)
owns = _owner_check(fetch_all, project_name)
rows = [r for r in rows if owns(_text_qn(r))]
if not rows:
return DefinitionRow(
label="",
qualified_name=qualified_name,
path=None,
start_line=None,
end_line=None,
name=None,
docstring=None,
source=None,
found=False,
)
row = rows[0]
symbol = _symbol_row(row)
source: str | None = None
path, start, end = symbol["path"], symbol["start_line"], symbol["end_line"]
if repo_root is not None and path and start and end:
candidate = (repo_root / path).resolve()
if candidate.is_relative_to(repo_root.resolve()) and candidate.is_file():
source = extract_source_lines(candidate, start, end)
return DefinitionRow(
label=symbol["label"],
qualified_name=symbol["qualified_name"],
path=path,
start_line=start,
end_line=end,
name=_opt_str(row.get(cs.KEY_NAME)),
docstring=_opt_str(row.get(cs.KEY_DOCSTRING)),
source=source,
found=True,
)
# --- callers / callees --------------------------------------------------------
def _site_row(row: ResultRow, depth: int, through: str) -> CallSiteRow:
kwargs = row.get(cs.KEY_KWARG_NAMES)
return CallSiteRow(
label=str(row.get(cs.KEY_LABEL, "")),
qualified_name=str(row.get(cs.KEY_QUALIFIED_NAME, "")),
path=_opt_str(row.get(cs.KEY_PATH)),
line=_opt_int(row.get(cs.KEY_LINE)),
col=_opt_int(row.get(cs.KEY_COL)),
end_line=_opt_int(row.get(cs.KEY_END_LINE)),
end_col=_opt_int(row.get(cs.KEY_END_COL)),
arg_count=_opt_int(row.get(cs.KEY_ARG_COUNT)),
kwarg_names=[str(k) for k in kwargs] if isinstance(kwargs, list) else None,
resolution=_opt_str(row.get(cs.KEY_RESOLUTION)),
depth=depth,
through=through,
)
def _site_sort_key(row: CallSiteRow) -> tuple[int, str, str, int, int]:
return (
row["depth"],
row["through"],
row["qualified_name"],
row["line"] if row["line"] is not None else -1,
row["col"] if row["col"] is not None else -1,
)
def _walk_sites(
fetch_all: QueryFn, project_name: str, query: str, start: str, depth: int
) -> list[CallSiteRow]:
# Breadth-first over endpoints, one query per frontier node; a node's
# sites appear at the depth it was first reached and never again, so a
# cycle terminates and the output stays a finite, ordered list.
prefix = _prefix(project_name)
owns = _owner_check(fetch_all, project_name)
seen: set[str] = {start}
frontier: list[str] = [start]
out: list[CallSiteRow] = []
for level in range(1, max(1, depth) + 1):
next_frontier: list[str] = []
for qn in sorted(frontier):
rows = fetch_all(query, {cs.KEY_PROJECT_PREFIX: prefix, cs.KEY_QN: qn})
for site in _owned_sites(rows, owns, level, qn):
out.append(site)
other = site["qualified_name"]
if other not in seen:
seen.add(other)
next_frontier.append(other)
frontier = next_frontier
if not frontier:
break
return sorted(out, key=_site_sort_key)
def _owned_sites(
rows: list[ResultRow], owns: Callable[[str], bool], level: int, through: str
) -> list[CallSiteRow]:
"""The sites among `rows` whose other endpoint this project owns: a
foreign row is neither reported nor a hop the walk continues through."""
return [_site_row(row, level, through) for row in rows if owns(_text_qn(row))]
def callers(
fetch_all: QueryFn, project_name: str, qualified_name: str, depth: int = 1
) -> list[CallSiteRow]:
"""Call sites that reach `qualified_name`, one row per site.
`depth` > 1 follows the callers' callers; `through` names the callee
each row's site invokes, so a transitive row is still one exact site.
"""
return _walk_sites(
fetch_all, project_name, cq.CYPHER_GRAPH_CALLERS, qualified_name, depth
)
def callees(
fetch_all: QueryFn, project_name: str, qualified_name: str, depth: int = 1
) -> list[CallSiteRow]:
"""Call sites inside `qualified_name`, one row per site (`through` = caller)."""
return _walk_sites(
fetch_all, project_name, cq.CYPHER_GRAPH_CALLEES, qualified_name, depth
)
# --- implementors / overrides / importers ---------------------------------------
def _related_rows(
fetch_all: QueryFn, project_name: str, query: str, qn: str
) -> list[RelatedRow]:
rows = fetch_all(
query, {cs.KEY_PROJECT_PREFIX: _prefix(project_name), cs.KEY_QN: qn}
)
owns = _owner_check(fetch_all, project_name)
rows = [r for r in rows if owns(_text_qn(r))]
out = [
RelatedRow(
label=str(r.get(cs.KEY_LABEL, "")),
qualified_name=str(r.get(cs.KEY_QUALIFIED_NAME, "")),
path=_opt_str(r.get(cs.KEY_PATH)),
relationship=str(r.get(cs.KEY_REL_TYPE, "")),
)
for r in rows
]
return sorted(out, key=lambda r: (r["qualified_name"], r["relationship"]))
def implementors(
fetch_all: QueryFn, project_name: str, qualified_name: str
) -> list[RelatedRow]:
"""Types that INHERIT from or IMPLEMENT `qualified_name`."""
return _related_rows(
fetch_all, project_name, cq.CYPHER_GRAPH_IMPLEMENTORS, qualified_name
)
def overrides(
fetch_all: QueryFn, project_name: str, qualified_name: str
) -> list[RelatedRow]:
"""Methods that OVERRIDE `qualified_name`, and the method it overrides."""
return _related_rows(
fetch_all, project_name, cq.CYPHER_GRAPH_OVERRIDES, qualified_name
)
def importers(
fetch_all: QueryFn, project_name: str, module_qn: str
) -> list[ImporterRow]:
"""Modules importing `module_qn`, with each import statement's location."""
rows = fetch_all(
cq.CYPHER_GRAPH_IMPORTERS,
{cs.KEY_PROJECT_PREFIX: _prefix(project_name), cs.KEY_QN: module_qn},
)
owns = _owner_check(fetch_all, project_name)
rows = [r for r in rows if owns(_text_qn(r))]
out = [
ImporterRow(
module=str(r.get(cs.KEY_QUALIFIED_NAME, "")),
path=_opt_str(r.get(cs.KEY_PATH)),
line=_opt_int(r.get(cs.KEY_LINE)),
col=_opt_int(r.get(cs.KEY_COL)),
end_line=_opt_int(r.get(cs.KEY_END_LINE)),
end_col=_opt_int(r.get(cs.KEY_END_COL)),
alias=_opt_str(r.get(cs.KEY_ALIAS)),
imported_name=_opt_str(r.get(cs.KEY_IMPORTED_NAME)),
)
for r in rows
]
return sorted(
out,
key=lambda r: (
r["module"],
r["line"] if r["line"] is not None else -1,
# `or -1` would fold a real column 0 -- the common case, an import
# at the start of a line -- into the same key as a missing column,
# leaving co-located rows in the arbitrary order the graph
# returned them.
r["col"] if r["col"] is not None else -1,
r["alias"] or "",
r["imported_name"] or "",
),
)
# --- tests_reaching ------------------------------------------------------------
class ReachIndex:
"""The project's reverse call graph plus the test classifier's inputs.
Built once from the dead-code fetch (one query each for nodes and edges)
and walked backwards from one symbol; the structural delta (issue #1525)
walks callers per hop instead and does not use it.
"""
def __init__(
self,
nodes: dict[_NodeId, PropertyDict],
reverse: dict[str, set[str]],
test_patterns: tuple[str, ...],
) -> None:
self._by_qn: dict[str, tuple[str, PropertyDict]] = {
str(qn): (label, props) for (label, qn), props in nodes.items()
}
self._reverse = reverse
self._patterns = test_patterns
self._rust_modules = _rust_test_modules_from_nodes(nodes)
self._rust_spans = _rust_test_fn_spans(nodes)
@classmethod
def build(
cls,
fetch_all: QueryFn,
project_name: str,
test_patterns: tuple[str, ...] = cs.TEST_PATH_PATTERNS,
) -> ReachIndex:
params = {cs.KEY_PROJECT_PREFIX: _prefix(project_name)}
nodes: dict[_NodeId, PropertyDict] = {}
owns = _owner_check(fetch_all, project_name)
for row in fetch_all(cq.CYPHER_DEAD_CODE_NODES, params):
qn = str(row.get(cs.KEY_QUALIFIED_NAME) or "")
if not owns(qn):
continue
if qn:
nodes[(str(row.get(cs.KEY_LABEL, "")), qn)] = _node_props(row)
reverse: dict[str, set[str]] = {}
for row in fetch_all(cq.CYPHER_DEAD_CODE_RELS, params):
if str(row.get(cs.KEY_REL_TYPE, "")) not in _REACH_RELS:
continue
src = str(row.get(cs.KEY_FROM_QN) or "")
dst = str(row.get(cs.KEY_TO_QN) or "")
# Both ends owned: a foreign caller must neither be reported
# nor be a hop the walk continues through (issue #1982).
if src and dst and owns(src) and owns(dst):
reverse.setdefault(dst, set()).add(src)
return cls(nodes, reverse, test_patterns)
def _walk(self, qualified_name: str) -> tuple[dict[str, int], dict[str, str]]:
depth_of: dict[str, int] = {qualified_name: 0}
through_of: dict[str, str] = {qualified_name: qualified_name}
frontier = [qualified_name]
while frontier:
next_frontier: list[str] = []
for qn in sorted(frontier):
for caller in sorted(self._reverse.get(qn, ())):
if caller in depth_of:
continue
depth_of[caller] = depth_of[qn] + 1
through_of[caller] = qn
next_frontier.append(caller)
frontier = next_frontier
return depth_of, through_of
def tests_reaching(self, qualified_name: str) -> list[TestReachRow]:
depth_of, through_of = self._walk(qualified_name)
out: list[TestReachRow] = []
for qn, depth in depth_of.items():
if qn == qualified_name:
continue
entry = self._by_qn.get(qn)
if entry is None:
continue
label, props = entry
path = str(props.get(cs.KEY_PATH) or "")
if _is_test_symbol(
props, qn, path, self._patterns, self._rust_modules, self._rust_spans
):
out.append(
TestReachRow(
label=label,
qualified_name=qn,
path=path or None,
depth=depth,
through=through_of[qn],
)
)
return sorted(out, key=lambda r: (r["depth"], r["qualified_name"]))
def tests_reaching(
fetch_all: QueryFn,
project_name: str,
qualified_name: str,
test_patterns: tuple[str, ...] = cs.TEST_PATH_PATTERNS,
) -> list[TestReachRow]:
"""Test symbols from which `qualified_name` is reachable, with distance.
Walks CALLS / REFERENCES / INSTANTIATES backwards over the project's
edges (the dead-code fetch, one query each for nodes and edges) and keeps
the reached definitions the dead-code root classifier calls tests, so
Rust `#[cfg(test)]` modules count exactly as they do there.
"""
return ReachIndex.build(fetch_all, project_name, test_patterns).tests_reaching(
qualified_name
)
# --- cross-service edges (issue #1603) ---------------------------------------
def _endpoint_row(row: ResultRow) -> EndpointRow:
callers = row.get(cs.KEY_CALLERS)
return EndpointRow(
endpoint=str(row.get(cs.KEY_ENDPOINT) or ""),
kind=_opt_str(row.get(cs.KEY_KIND)),
label=str(row.get(cs.KEY_LABEL) or ""),
handler=str(row.get(cs.KEY_HANDLER) or ""),
path=_opt_str(row.get(cs.KEY_PATH)),
callers=callers if isinstance(callers, int) else 0,
)
def _endpoint_caller_row(row: ResultRow) -> EndpointCallerRow:
return EndpointCallerRow(
label=str(row.get(cs.KEY_LABEL) or ""),
qualified_name=str(row.get(cs.KEY_QUALIFIED_NAME) or ""),
path=_opt_str(row.get(cs.KEY_PATH)),
url=_opt_str(row.get(cs.KEY_URL)),
direction=_opt_str(row.get(cs.KEY_DIRECTION)),
endpoint=str(row.get(cs.KEY_ENDPOINT) or ""),
handler=str(row.get(cs.KEY_HANDLER) or ""),
)
def endpoints(fetch_all: QueryFn, project_name: str) -> list[EndpointRow]:
"""The endpoints a project exposes, each with its handler and how many
call sites in the whole graph reach it. Zero callers on a graph that
holds only this project means "none indexed", not "dead"."""
params = {cs.KEY_PROJECT_PREFIX: _prefix(project_name)}
return [_endpoint_row(row) for row in fetch_all(cq.CYPHER_GRAPH_ENDPOINTS, params)]
def endpoint_callers(
fetch_all: QueryFn, project_name: str, target: str
) -> list[EndpointCallerRow]:
"""Call sites, in any project, that reach the endpoint `target` names:
the handler's qualified name or the endpoint identity (`GET /users/{id}`).
Through a NETWORK resource that RESOLVES_TO the endpoint, or directly for
the RPC and dispatch kinds, which join without RESOLVES_TO.
"""
params = {cs.KEY_PROJECT_PREFIX: _prefix(project_name), cs.KEY_QN: target}
rows = [
_endpoint_caller_row(row)
for query in (
cq.CYPHER_GRAPH_ENDPOINT_CALLERS,
cq.CYPHER_GRAPH_ENDPOINT_DIRECT_CALLERS,
)
for row in fetch_all(query, params)
]
# Every field in the key: a caller that both reads and writes one URL is
# two rows, and two handlers can share a caller (bot review on PR #1975).
return sorted(
rows,
key=lambda r: (
r["qualified_name"],
r["url"] or "",
r["path"] or "",
r["direction"] or "",
r["endpoint"],
r["handler"],
),
)
def remote_dependencies(
fetch_all: QueryFn, project_name: str
) -> list[RemoteDependencyRow]:
"""Every network access a project makes, with the handler and project it
resolves to; an unresolved row (no endpoint) is a dependency the graph
cannot place -- a dynamic URL, or a service not indexed."""
params = {cs.KEY_PROJECT_PREFIX: _prefix(project_name)}
return [
RemoteDependencyRow(
label=str(row.get(cs.KEY_LABEL) or ""),
qualified_name=str(row.get(cs.KEY_QUALIFIED_NAME) or ""),
path=_opt_str(row.get(cs.KEY_PATH)),
url=_opt_str(row.get(cs.KEY_URL)),
direction=_opt_str(row.get(cs.KEY_DIRECTION)),
endpoint=_opt_str(row.get(cs.KEY_ENDPOINT)),
handler=_opt_str(row.get(cs.KEY_HANDLER)),
handler_project=_opt_str(row.get(cs.KEY_HANDLER_PROJECT)),
)
for row in fetch_all(cq.CYPHER_GRAPH_REMOTE_DEPENDENCIES, params)
]