-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats.go
More file actions
562 lines (523 loc) · 15.3 KB
/
stats.go
File metadata and controls
562 lines (523 loc) · 15.3 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
// Package query implements the codeiq Go port's query-side services. It
// wraps internal/graph.Store with task-level helpers and renders the JSON-
// ready shapes the Java side's QueryService / StatsService / TopologyService
// expose. These services are read-only; mutation paths live in analyzer/.
//
// The package centres on three services:
//
// - StatsService — pure functions over (nodes, edges) slices. Used when the
// enrich pipeline has the full graph in heap; the serve side uses
// graph.Store aggregations instead. Mirrors StatsService.java.
// - Service — high-level read service backed by a graph.Store. Mirrors
// QueryService.java (consumers / producers / callers / cycles / dead).
// - Topology — service-topology analyses. Mirrors TopologyService.java.
package query
import (
"bytes"
"encoding/json"
"sort"
"strings"
"github.com/randomcodespace/codeiq/internal/model"
)
// StatsService computes rich categorized statistics from in-memory node /
// edge slices. Stateless — the zero value is usable.
type StatsService struct{}
// StoreStatsService is a thin store-backed wrapper around StatsService. It
// lazy-loads the full node + edge lists on the first call and reuses them
// for subsequent ComputeStats / ComputeCategory invocations. Use this when
// the caller has a graph.Store handle (e.g. the CLI / MCP) rather than
// pre-materialised slices.
//
// The wrapper is a bridge for the read path while the targeted-Cypher
// rewrite is in flight — same `getCachedData()` snapshot pattern the Java
// side uses for the same reason (see the CLAUDE.md gotcha entry).
type StoreStatsService struct {
loader func() ([]*model.CodeNode, []*model.CodeEdge, error)
once bool
nodes []*model.CodeNode
edges []*model.CodeEdge
err error
base StatsService
}
// NewStatsServiceFromStore returns a StoreStatsService bound to the loader
// callback. The CLI passes `func() (...) { return store.LoadAllNodes(), ... }`.
// Decoupling from graph.Store avoids a query→graph import cycle (graph already
// imports model, but tests want to feed in arbitrary slices).
func NewStatsServiceFromStore(loader func() ([]*model.CodeNode, []*model.CodeEdge, error)) *StoreStatsService {
return &StoreStatsService{loader: loader}
}
func (s *StoreStatsService) load() error {
if s.once {
return s.err
}
s.once = true
s.nodes, s.edges, s.err = s.loader()
return s.err
}
// ComputeStats lazy-loads and forwards to StatsService.ComputeStats. Returns
// an empty *OrderedMap (not nil) on loader failure so the JSON output is
// always well-formed; callers that care about the underlying error must use
// LoadErr() after the call.
func (s *StoreStatsService) ComputeStats() *OrderedMap {
if err := s.load(); err != nil {
return newOrdered()
}
return s.base.ComputeStats(s.nodes, s.edges)
}
// ComputeCategory lazy-loads and forwards to StatsService.ComputeCategory.
// Returns nil for unknown categories (matches the in-memory API).
func (s *StoreStatsService) ComputeCategory(category string) *OrderedMap {
if err := s.load(); err != nil {
return newOrdered()
}
return s.base.ComputeCategory(s.nodes, s.edges, category)
}
// LoadErr returns the loader error, if any, captured during the first call
// to ComputeStats / ComputeCategory.
func (s *StoreStatsService) LoadErr() error { return s.err }
// OrderedMap preserves insertion order — equivalent to Java's
// LinkedHashMap. Stats JSON output relies on a deterministic top-level key
// order matching the Java side for parity diffing.
type OrderedMap struct {
Keys []string
Values map[string]any
}
func newOrdered() *OrderedMap { return &OrderedMap{Values: map[string]any{}} }
// Put records key in insertion order; an overwrite keeps the original
// position so that re-assignment is non-disruptive.
func (m *OrderedMap) Put(k string, v any) {
if _, ok := m.Values[k]; !ok {
m.Keys = append(m.Keys, k)
}
m.Values[k] = v
}
// MarshalJSON emits keys in insertion order — the whole point of OrderedMap.
// Empty/zero maps emit `{}`. Nested OrderedMaps recurse correctly through
// json.Encoder's reflective path because MarshalJSON is declared on the
// pointer receiver and the package always passes *OrderedMap values around.
func (m *OrderedMap) MarshalJSON() ([]byte, error) {
if m == nil {
return []byte("null"), nil
}
var buf bytes.Buffer
buf.WriteByte('{')
for i, k := range m.Keys {
if i > 0 {
buf.WriteByte(',')
}
kb, err := json.Marshal(k)
if err != nil {
return nil, err
}
buf.Write(kb)
buf.WriteByte(':')
vb, err := json.Marshal(m.Values[k])
if err != nil {
return nil, err
}
buf.Write(vb)
}
buf.WriteByte('}')
return buf.Bytes(), nil
}
// ComputeStats returns the seven-category breakdown:
// graph, languages, frameworks, infra, connections, auth, architecture.
// Order matches Java StatsService.computeStats line-for-line for parity.
func (s *StatsService) ComputeStats(nodes []*model.CodeNode, edges []*model.CodeEdge) *OrderedMap {
out := newOrdered()
out.Put("graph", s.computeGraph(nodes, edges))
out.Put("languages", s.computeLanguages(nodes))
out.Put("frameworks", s.computeFrameworks(nodes))
out.Put("infra", s.computeInfra(nodes))
out.Put("connections", s.computeConnections(nodes, edges))
out.Put("auth", s.computeAuth(nodes))
out.Put("architecture", s.computeArchitecture(nodes))
return out
}
// ComputeCategory returns just one category. Names are matched
// case-insensitively. Returns nil for unknown categories — matches Java
// behaviour rather than returning an error envelope (the controller layer
// surfaces that as "Unknown category").
func (s *StatsService) ComputeCategory(nodes []*model.CodeNode, edges []*model.CodeEdge, category string) *OrderedMap {
switch strings.ToLower(category) {
case "graph":
return s.computeGraph(nodes, edges)
case "languages":
return s.computeLanguages(nodes)
case "frameworks":
return s.computeFrameworks(nodes)
case "infra":
return s.computeInfra(nodes)
case "connections":
return s.computeConnections(nodes, edges)
case "auth":
return s.computeAuth(nodes)
case "architecture":
return s.computeArchitecture(nodes)
default:
return nil
}
}
// --- Category implementations (ported from StatsService.java) ---
func (s *StatsService) computeGraph(nodes []*model.CodeNode, edges []*model.CodeEdge) *OrderedMap {
files := map[string]struct{}{}
for _, n := range nodes {
if strings.TrimSpace(n.FilePath) != "" {
files[n.FilePath] = struct{}{}
}
}
counts := map[string]int{}
for _, e := range edges {
counts[e.Kind.String()]++
}
g := newOrdered()
g.Put("nodes", len(nodes))
g.Put("edges", len(edges))
g.Put("files", len(files))
g.Put("edges_by_kind", sortByValueDesc(counts))
return g
}
func (s *StatsService) computeLanguages(nodes []*model.CodeNode) *OrderedMap {
counts := map[string]int{}
for _, n := range nodes {
lang := extractLanguage(n)
if strings.TrimSpace(lang) != "" {
counts[lang]++
}
}
return sortByValueDesc(counts)
}
func (s *StatsService) computeFrameworks(nodes []*model.CodeNode) *OrderedMap {
counts := map[string]int{}
for _, n := range nodes {
fw, _ := n.Properties["framework"].(string)
fw = strings.TrimSpace(fw)
if fw != "" {
counts[fw]++
}
}
return sortByValueDesc(counts)
}
// dbTypeNormalize mirrors Java's DB_TYPE_NORMALIZE Map.ofEntries — display
// strings for known JDBC subprotocols and NoSQL drivers.
var dbTypeNormalize = map[string]string{
"mysql": "MySQL",
"postgresql": "PostgreSQL",
"postgres": "PostgreSQL",
"sqlserver": "SQL Server",
"mssql": "SQL Server",
"oracle": "Oracle",
"db2": "DB2",
"h2": "H2",
"sqlite": "SQLite",
"mariadb": "MariaDB",
"derby": "Derby",
"hsqldb": "HSQLDB",
"mongo": "MongoDB",
"mongodb": "MongoDB",
"redis": "Redis",
"cassandra": "Cassandra",
"dynamodb": "DynamoDB",
"couchbase": "Couchbase",
"neo4j": "Neo4j",
"cockroachdb": "CockroachDB",
}
func (s *StatsService) computeInfra(nodes []*model.CodeNode) *OrderedMap {
databases := map[string]int{}
messaging := map[string]int{}
cloud := map[string]int{}
for _, n := range nodes {
switch n.Kind {
case model.NodeDatabaseConnection:
if dbType := resolveDbType(n); dbType != "" {
databases[dbType]++
}
case model.NodeTopic, model.NodeQueue, model.NodeMessageQueue:
messaging[propOrLabel(n, "protocol")]++
case model.NodeAzureResource, model.NodeInfraResource:
cloud[propOrLabel(n, "resource_type")]++
}
}
infra := newOrdered()
infra.Put("databases", sortByValueDesc(databases))
infra.Put("messaging", sortByValueDesc(messaging))
infra.Put("cloud", sortByValueDesc(cloud))
return infra
}
func (s *StatsService) computeConnections(nodes []*model.CodeNode, edges []*model.CodeEdge) *OrderedMap {
restByMethod := map[string]int{}
var grpcCount, wsCount int64
for _, n := range nodes {
switch n.Kind {
case model.NodeEndpoint:
protocol, _ := n.Properties["protocol"].(string)
if strings.EqualFold(protocol, "grpc") {
grpcCount++
continue
}
method, _ := n.Properties["http_method"].(string)
if method == "" {
method = "UNKNOWN"
}
restByMethod[strings.ToUpper(method)]++
case model.NodeWebSocketEndpoint:
wsCount++
}
}
var restTotal int64
for _, v := range restByMethod {
restTotal += int64(v)
}
rest := newOrdered()
rest.Put("total", restTotal)
rest.Put("by_method", sortByValueDesc(restByMethod))
var producers, consumers int64
for _, e := range edges {
switch e.Kind {
case model.EdgeProduces, model.EdgePublishes:
producers++
case model.EdgeConsumes, model.EdgeListens:
consumers++
}
}
conn := newOrdered()
conn.Put("rest", rest)
conn.Put("grpc", grpcCount)
conn.Put("websocket", wsCount)
conn.Put("producers", producers)
conn.Put("consumers", consumers)
return conn
}
func (s *StatsService) computeAuth(nodes []*model.CodeNode) *OrderedMap {
counts := map[string]int{}
for _, n := range nodes {
if n.Kind == model.NodeGuard {
authType, _ := n.Properties["auth_type"].(string)
if authType == "" {
authType = "unknown"
}
counts[authType]++
continue
}
fw, _ := n.Properties["framework"].(string)
fw = strings.TrimSpace(fw)
if strings.HasPrefix(fw, "auth:") {
authType := strings.TrimSpace(fw[len("auth:"):])
if authType != "" {
counts[authType]++
}
}
}
return sortByValueDesc(counts)
}
func (s *StatsService) computeArchitecture(nodes []*model.CodeNode) *OrderedMap {
var classes, interfaces, abstracts, enums, annotations, modules, methods int
for _, n := range nodes {
switch n.Kind {
case model.NodeClass:
classes++
case model.NodeInterface:
interfaces++
case model.NodeAbstractClass:
abstracts++
case model.NodeEnum:
enums++
case model.NodeAnnotationType:
annotations++
case model.NodeModule:
modules++
case model.NodeMethod:
methods++
}
}
arch := newOrdered()
if classes > 0 {
arch.Put("classes", classes)
}
if interfaces > 0 {
arch.Put("interfaces", interfaces)
}
if abstracts > 0 {
arch.Put("abstract_classes", abstracts)
}
if enums > 0 {
arch.Put("enums", enums)
}
if annotations > 0 {
arch.Put("annotation_types", annotations)
}
if modules > 0 {
arch.Put("modules", modules)
}
if methods > 0 {
arch.Put("methods", methods)
}
return arch
}
// --- Helpers ---
// extractLanguage prefers properties.language, falling back to the file
// extension lookup table. Returns "" when neither is available.
func extractLanguage(n *model.CodeNode) string {
if lang, _ := n.Properties["language"].(string); strings.TrimSpace(lang) != "" {
return strings.ToLower(lang)
}
if dot := strings.LastIndex(n.FilePath, "."); dot >= 0 {
ext := strings.ToLower(n.FilePath[dot+1:])
return extByLang(ext)
}
return ""
}
// extByLang mirrors the Java switch in StatsService.extractLanguage. The
// fallthrough returns the bare extension so unknown formats still
// contribute a non-empty bucket.
func extByLang(ext string) string {
switch ext {
case "java":
return "java"
case "kt", "kts":
return "kotlin"
case "py":
return "python"
case "js", "mjs", "cjs":
return "javascript"
case "ts", "tsx":
return "typescript"
case "go":
return "go"
case "rs":
return "rust"
case "cs":
return "csharp"
case "rb":
return "ruby"
case "scala":
return "scala"
case "cpp", "cc", "cxx":
return "cpp"
case "c", "h":
return "c"
case "proto":
return "protobuf"
case "yml", "yaml":
return "yaml"
case "json":
return "json"
case "xml":
return "xml"
case "toml":
return "toml"
case "ini", "cfg":
return "ini"
case "properties":
return "properties"
case "gradle":
return "gradle"
case "tf":
return "terraform"
case "bicep":
return "bicep"
case "sql":
return "sql"
case "md":
return "markdown"
case "html", "htm":
return "html"
case "css", "scss", "sass":
return "css"
case "vue":
return "vue"
case "svelte":
return "svelte"
case "jsx":
return "jsx"
case "sh", "bash":
return "shell"
}
return ext
}
// resolveDbType returns the display-friendly DB type for a
// DATABASE_CONNECTION node. Order:
// 1. db_type property (canonicalised via dbTypeNormalize)
// 2. extract jdbc: prefix from connection_url / value / url
// 3. fall back to label, ignoring config-key labels (contain '.' or '=')
//
// Returns "" when the node looks like a false-positive config key.
func resolveDbType(n *model.CodeNode) string {
if dbType, _ := n.Properties["db_type"].(string); strings.TrimSpace(dbType) != "" {
return normalizeDbType(dbType)
}
for _, key := range []string{"connection_url", "value", "url"} {
if v, ok := n.Properties[key].(string); ok && strings.Contains(v, "jdbc:") {
if t := extractDbTypeFromURL(v); t != "" {
return t
}
}
}
label := n.Label
if label != "" && !strings.Contains(label, ".") && !strings.Contains(label, "=") {
return normalizeDbType(label)
}
return ""
}
func normalizeDbType(raw string) string {
lower := strings.TrimSpace(strings.ToLower(raw))
// Strip "type@host" suffix from JdbcDetector ("mysql@localhost" → "mysql").
if i := strings.IndexByte(lower, '@'); i >= 0 {
lower = lower[:i]
}
if v, ok := dbTypeNormalize[lower]; ok {
return v
}
return strings.TrimSpace(raw)
}
// extractDbTypeFromURL parses "jdbc:TYPE:..." into the canonicalised TYPE.
func extractDbTypeFromURL(url string) string {
idx := strings.Index(url, "jdbc:")
if idx < 0 {
return ""
}
after := url[idx+5:]
colon := strings.IndexByte(after, ':')
if colon <= 0 {
return ""
}
t := strings.ToLower(after[:colon])
if v, ok := dbTypeNormalize[t]; ok {
return v
}
return t
}
// propOrLabel returns properties[key] when non-blank, else node.Label, else
// "unknown". Mirrors Java's propOrLabel helper.
func propOrLabel(n *model.CodeNode, key string) string {
if v, ok := n.Properties[key].(string); ok && strings.TrimSpace(v) != "" {
return v
}
if n.Label != "" {
return n.Label
}
return "unknown"
}
// sortByValueDesc projects counts into an OrderedMap sorted by value desc,
// then by key asc — deterministic regardless of map iteration order.
func sortByValueDesc(m map[string]int) *OrderedMap {
type kv struct {
k string
v int
}
rows := make([]kv, 0, len(m))
for k, v := range m {
rows = append(rows, kv{k, v})
}
sort.Slice(rows, func(i, j int) bool {
if rows[i].v != rows[j].v {
return rows[i].v > rows[j].v
}
return rows[i].k < rows[j].k
})
out := newOrdered()
for _, r := range rows {
out.Put(r.k, r.v)
}
return out
}