leankg 0.19.31

Lightweight Knowledge Graph for AI-Assisted Development
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
use crate::db::models::{Relationship, RelationshipType};
use regex::Regex;
use serde_yaml::Value;
use std::collections::HashMap;
use std::path::Path;
use walkdir::WalkDir;

pub struct MicroserviceExtractor {
    grpc_pattern: Regex,
    _http_pattern: Regex,
    client_dirs: Vec<String>,
}

impl MicroserviceExtractor {
    pub fn new() -> Self {
        Self {
            // Matches: dns:///service-name.default.svc.cluster.local.:10000
            grpc_pattern: Regex::new(r"dns:///([a-z0-9-]+)\.default\.svc\.cluster\.local\.:\d+")
                .unwrap(),
            // Matches http(s)://service-name[:port][/path] — k8s DNS
            // (…default.svc.cluster.local), docker-compose service names,
            // or plain host:port.
            _http_pattern: Regex::new(
                r"https?://([a-z0-9_-]+)(?:\.default\.svc\.cluster\.local\.?)?(?::\d+)?(?:/|$)",
            )
            .unwrap(),
            client_dirs: vec!["internal/external".to_string()],
        }
    }

    pub fn with_config(
        client_dirs: Vec<String>,
        grpc_pattern: String,
        http_pattern: String,
    ) -> Self {
        Self {
            grpc_pattern: Regex::new(&grpc_pattern).unwrap_or_else(|_| {
                Regex::new(r"dns:///[a-z0-9-]+\.default\.svc\.cluster\.local\.\:\d+").unwrap()
            }),
            _http_pattern: Regex::new(&http_pattern).unwrap_or_else(|_| {
                Regex::new(
                    r"https?://([a-z0-9_-]+)(?:\.default\.svc\.cluster\.local\.?)?(?::\d+)?(?:/|$)",
                )
                .unwrap()
            }),
            client_dirs,
        }
    }

    /// Extract microservice relationships from a project directory
    pub fn extract(&self, project_path: &str) -> Vec<Relationship> {
        let mut relationships = Vec::new();
        let service_names = self.discover_services(project_path);
        let project_service = service_names.values().next().cloned();

        // Scan client files for gRPC calls
        for client_dir in &self.client_dirs {
            let full_path = Path::new(project_path).join(client_dir);
            if full_path.exists() {
                let file_relationships = self.scan_client_files(&full_path, &project_service);
                relationships.extend(file_relationships);
            }
        }

        // Scan config files for service addresses
        let config_relationships = self.scan_config_files(project_path, &project_service);
        relationships.extend(config_relationships);

        relationships
    }

    /// Discover service names from go.mod or service discovery
    fn discover_services(&self, project_path: &str) -> HashMap<String, String> {
        let mut services = HashMap::new();

        // Read go.mod to get module name as service prefix
        let go_mod_path = Path::new(project_path).join("go.mod");
        if let Ok(content) = std::fs::read_to_string(&go_mod_path) {
            for line in content.lines() {
                if line.starts_with("module ") {
                    let module = line.trim_start_matches("module ");
                    // Extract service name from module path
                    if let Some(last_segment) = module.rsplit('/').next() {
                        services.insert(last_segment.to_string(), last_segment.to_string());
                    }
                    break;
                }
            }
        }

        services
    }

    /// Scan client files (internal/external/) for gRPC client instantiations
    fn scan_client_files(&self, dir: &Path, project_service: &Option<String>) -> Vec<Relationship> {
        let mut relationships = Vec::new();

        for entry in WalkDir::new(dir)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().map(|ext| ext == "go").unwrap_or(false))
        {
            let file_path = entry.path();
            if let Ok(content) = std::fs::read_to_string(file_path) {
                let file_rels = self.extract_grpc_calls(
                    &content,
                    file_path.to_str().unwrap_or(""),
                    project_service,
                );
                relationships.extend(file_rels);
            }
        }

        relationships
    }

    /// Extract gRPC/HTTP/Docker service calls from file content.
    ///
    /// FR-B13: beyond `grpc.NewClient("dns:///…")`, also detects
    /// `http.NewRequest` / `client.Get("http://service:port/…")` /
    /// `fmt.Sprintf("http://service:8080/…")` style calls so
    /// `service_calls` edges are produced for docker-compose and plain
    /// http(s) service addresses, not just k8s DNS.
    fn extract_grpc_calls(
        &self,
        content: &str,
        file_path: &str,
        project_service: &Option<String>,
    ) -> Vec<Relationship> {
        let mut relationships = Vec::new();

        // Pattern: grpc.NewClient("dns:///service-name.default.svc.cluster.local.:10000", ...)
        let grpc_client_re = Regex::new(r#"(?m)grpc\.NewClient\s*\(\s*"([^"]+)"[,\s]"#).unwrap();
        // Pattern: http(s) client calls with an inline URL string argument.
        // Covers `http.Get("url")`, `client.Get("url")`, and
        // `http.NewRequest("GET", "url", body)` (URL as 2nd arg).
        let http_call_re = Regex::new(
            r#"(?m)(?:http\.(?:Get|Post|Do)|client\.(?:Get|Post|Do|Request))\s*\(\s*"([^"]+)""#,
        )
        .unwrap();
        let http_new_request_re =
            Regex::new(r#"(?m)http\.NewRequest\s*\(\s*"[^"]+"\s*,\s*"([^"]+)""#).unwrap();
        // Pattern: bare docker-compose service refs `service-name:port`
        // inside quotes (no dots — those are URLs or DNS names, handled
        // above). Requires an explicit :port so plain quoted words are
        // not treated as services.
        let docker_addr_re = Regex::new(r#"["']([a-z][a-z0-9_-]+):(\d+)["']"#).unwrap();

        let add =
            |address: &str, protocol: &str, cap_start: usize, rels: &mut Vec<Relationship>| {
                if let Some(service_name) = self.extract_service_name(address, protocol) {
                    let line_number = content[..cap_start].lines().count() as u32;
                    rels.push(self.create_relationship(
                        service_name,
                        protocol.to_string(),
                        address.to_string(),
                        "unknown".to_string(),
                        file_path.to_string(),
                        line_number,
                        project_service,
                    ));
                }
            };

        for cap in grpc_client_re.captures_iter(content) {
            let address = &cap[1];
            add(
                address,
                "grpc",
                cap.get(0).map(|m| m.end()).unwrap_or(0),
                &mut relationships,
            );
        }

        for cap in http_call_re
            .captures_iter(content)
            .chain(http_new_request_re.captures_iter(content))
        {
            let address = &cap[1];
            if address.starts_with("http://") || address.starts_with("https://") {
                let protocol = if address.starts_with("https://") {
                    "https"
                } else {
                    "http"
                };
                add(
                    address,
                    protocol,
                    cap.get(0).map(|m| m.end()).unwrap_or(0),
                    &mut relationships,
                );
            }
        }

        // Bare docker-compose service refs `service-name:port` inside quotes
        // (no dots — URLs/DNS handled above).
        for cap in docker_addr_re.captures_iter(content) {
            let name = &cap[1];
            let port = &cap[2];
            if name.contains('.') {
                continue;
            }
            let address = format!("{}:{}", name, port);
            if let Some(service_name) = self.extract_service_name(&address, "docker") {
                if service_name == *project_service.as_deref().unwrap_or("") {
                    continue;
                }
                let line_number = content[..cap.get(0).map(|m| m.end()).unwrap_or(0)]
                    .lines()
                    .count() as u32;
                relationships.push(self.create_relationship(
                    service_name,
                    "docker".to_string(),
                    address.to_string(),
                    "unknown".to_string(),
                    file_path.to_string(),
                    line_number,
                    project_service,
                ));
            }
        }

        relationships
    }

    /// Extract service name from a service address.
    ///
    /// FR-B13: beyond the k8s DNS regex, also handle:
    /// - `http(s)://service-name[.domain][:port][/path]` (incl. docker-compose
    ///   service names like `http://api-gateway:8080/`),
    /// - bare docker-compose service names (`api-gateway:8080`, `db:5432`).
    fn extract_service_name(&self, address: &str, protocol: &str) -> Option<String> {
        match protocol {
            "grpc" => {
                // dns:///service-name.default.svc.cluster.local.:10000
                if let Some(caps) = self.grpc_pattern.captures(address) {
                    return Some(
                        caps.get(1)
                            .map(|m| m.as_str().to_string())
                            .unwrap_or_default(),
                    );
                }
            }
            "http" | "https" => {
                // http://service-name[.namespace][:port][/path]
                if let Some(caps) = self._http_pattern.captures(address) {
                    return Some(
                        caps.get(1)
                            .map(|m| m.as_str().to_string())
                            .unwrap_or_default(),
                    );
                }
            }
            "docker" => {
                // docker-compose service names: `service-name:8080` or plain `service-name`
                let docker_re = Regex::new(r"^([a-z][a-z0-9_-]*)(?::\d+)?(?:/.*)?$").unwrap();
                if let Some(caps) = docker_re.captures(address) {
                    return Some(
                        caps.get(1)
                            .map(|m| m.as_str().to_string())
                            .unwrap_or_default(),
                    );
                }
            }
            _ => {}
        }
        None
    }

    /// Scan config files for service address configurations
    fn scan_config_files(
        &self,
        project_path: &str,
        project_service: &Option<String>,
    ) -> Vec<Relationship> {
        let mut relationships = Vec::new();

        // Scan config/config.go for YAML configs
        let config_go = Path::new(project_path).join("config/config.go");
        if config_go.exists() {
            if let Ok(content) = std::fs::read_to_string(&config_go) {
                // Look for YAML content in config files
                let yaml_re = Regex::new(r#"be_(\w+)_address\s*[=:]\s*["']([^"']+)["']"#).unwrap();
                for cap in yaml_re.captures_iter(&content) {
                    let _service_key = &cap[1];
                    let address = &cap[2];

                    if address.starts_with("dns:///") {
                        if let Some(service_name) = self.extract_service_name(address, "grpc") {
                            relationships.push(self.create_relationship(
                                service_name,
                                "grpc".to_string(),
                                address.to_string(),
                                format!("config:{}", &cap[1]),
                                config_go.to_str().unwrap_or("").to_string(),
                                0,
                                project_service,
                            ));
                        }
                    }
                }
            }
        }

        // Scan YAML config files
        for entry in WalkDir::new(Path::new(project_path).join("config"))
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| {
                let path = e.path();
                path.extension()
                    .map(|ext| ext == "yaml" || ext == "yml")
                    .unwrap_or(false)
            })
        {
            if let Ok(content) = std::fs::read_to_string(entry.path()) {
                if let Ok(yaml) = serde_yaml::from_str::<Value>(&content) {
                    let file_rels = self.extract_from_yaml(
                        &yaml,
                        entry.path().to_str().unwrap_or(""),
                        project_service,
                    );
                    relationships.extend(file_rels);
                }
            }
        }

        relationships
    }

    /// Extract service addresses from YAML content
    fn extract_from_yaml(
        &self,
        yaml: &Value,
        file_path: &str,
        project_service: &Option<String>,
    ) -> Vec<Relationship> {
        let mut relationships = Vec::new();

        if let Some(obj) = yaml.as_mapping() {
            for (key, val) in obj {
                let key_str = key.as_str().unwrap_or("");
                if key_str.ends_with("_address") {
                    if let Some(address) = val.as_str() {
                        if let Some(rel) = self.yaml_address_relationship(
                            address,
                            key_str,
                            file_path,
                            project_service,
                        ) {
                            relationships.push(rel);
                        }
                    }
                }
                // Recurse into nested mappings
                if let Some(nested) = val.as_mapping() {
                    let nested_rels =
                        self.extract_from_yaml_internal(nested, file_path, project_service);
                    relationships.extend(nested_rels);
                }
            }
        }

        relationships
    }

    /// Build a service_calls relationship from a YAML `*_address` string,
    /// handling dns:///, http(s)://, and bare docker `name:port` forms.
    fn yaml_address_relationship(
        &self,
        address: &str,
        key_str: &str,
        file_path: &str,
        project_service: &Option<String>,
    ) -> Option<Relationship> {
        if address.starts_with("dns:///") {
            if let Some(service_name) = self.extract_service_name(address, "grpc") {
                return Some(self.create_relationship(
                    service_name,
                    "grpc".to_string(),
                    address.to_string(),
                    key_str.to_string(),
                    file_path.to_string(),
                    0,
                    project_service,
                ));
            }
        } else if address.starts_with("http://") || address.starts_with("https://") {
            let protocol = if address.starts_with("https://") {
                "https"
            } else {
                "http"
            };
            if let Some(service_name) = self.extract_service_name(address, protocol) {
                return Some(self.create_relationship(
                    service_name,
                    protocol.to_string(),
                    address.to_string(),
                    key_str.to_string(),
                    file_path.to_string(),
                    0,
                    project_service,
                ));
            }
        } else if !address.contains('.') && !address.contains('/') {
            // docker-compose style: `service-name:8080` (bare name w/o dots).
            if let Some(service_name) = self.extract_service_name(address, "docker") {
                return Some(self.create_relationship(
                    service_name,
                    "docker".to_string(),
                    address.to_string(),
                    key_str.to_string(),
                    file_path.to_string(),
                    0,
                    project_service,
                ));
            }
        }
        None
    }

    fn extract_from_yaml_internal(
        &self,
        yaml: &serde_yaml::Mapping,
        file_path: &str,
        project_service: &Option<String>,
    ) -> Vec<Relationship> {
        let mut relationships = Vec::new();

        for (key, val) in yaml {
            let key_str = key.as_str().unwrap_or("");
            if key_str.ends_with("_address") {
                if let Some(address) = val.as_str() {
                    if let Some(rel) =
                        self.yaml_address_relationship(address, key_str, file_path, project_service)
                    {
                        relationships.push(rel);
                    }
                }
            }
            if let Some(nested) = val.as_mapping() {
                let nested_rels =
                    self.extract_from_yaml_internal(nested, file_path, project_service);
                relationships.extend(nested_rels);
            }
        }

        relationships
    }

    /// Create a Relationship with service_calls type
    #[allow(clippy::too_many_arguments)]
    fn create_relationship(
        &self,
        target_service: String,
        protocol: String,
        address: String,
        api_path: String,
        source_file: String,
        line_number: u32,
        project_service: &Option<String>,
    ) -> Relationship {
        Relationship {
            id: None,
            source_qualified: project_service
                .clone()
                .unwrap_or_else(|| self.infer_source_service(&source_file)),
            target_qualified: target_service,
            rel_type: RelationshipType::ServiceCalls.as_str().to_string(),
            confidence: 1.0,
            metadata: serde_json::json!({
                "protocol": protocol,
                "address": address,
                "api_path": api_path,
                "source_file": source_file,
                "line_number": line_number,
            }),
            ..Default::default()
        }
    }

    /// Infer the source service name from the file path
    /// Pattern: .../service-name/internal/external/...
    fn infer_source_service(&self, file_path: &str) -> String {
        let path = Path::new(file_path);
        let components: Vec<_> = path.components().collect();

        // Look for the service name in the path
        // Pattern: .../service-name/internal/external/...
        // The service name is the parent of "internal"
        for i in 0..components.len() {
            if components[i].as_os_str() == "internal" && i > 0 {
                return components[i - 1].as_os_str().to_string_lossy().to_string();
            }
        }

        // Fallback: use the directory containing internal/external
        for i in 0..components.len() {
            if components[i].as_os_str() == "external" && i >= 2 {
                // Return the grandparent (parent of "external"'s parent)
                return components[i - 2].as_os_str().to_string_lossy().to_string();
            }
        }

        "unknown-service".to_string()
    }
}

impl Default for MicroserviceExtractor {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_service_name_from_grpc_address() {
        let extractor = MicroserviceExtractor::new();
        let address = "dns:///service-a.default.svc.cluster.local.:10000";
        let service = extractor.extract_service_name(address, "grpc");
        assert_eq!(service, Some("service-a".to_string()));
    }

    #[test]
    fn test_grpc_pattern_matching() {
        let content = r#"
grpc.NewClient("dns:///service-a.default.svc.cluster.local.:10000",
    grpc.WithTransportCredentials(insecure.NewCredentials()),
)
"#;
        let extractor = MicroserviceExtractor::new();
        let relationships = extractor.extract_grpc_calls(content, "test.go", &None);
        assert!(!relationships.is_empty());
        assert_eq!(relationships[0].target_qualified, "service-a");
    }

    #[test]
    fn test_infer_source_service() {
        let extractor = MicroserviceExtractor::new();
        // Path: .../service-gateway/internal/external/client.go
        // Service is "service-gateway" (parent of "internal")
        let path = "/path/to/service-gateway/internal/external/client.go";
        let service = extractor.infer_source_service(path);
        assert_eq!(service, "service-gateway");
    }

    #[test]
    fn test_infer_source_service_nested() {
        let extractor = MicroserviceExtractor::new();
        // Path: .../my-service/internal/external/client.go
        let path = "/workspace/my-service/internal/external/client.go";
        let service = extractor.infer_source_service(path);
        assert_eq!(service, "my-service");
    }

    // FR-B13: service_calls beyond k8s DNS regex.

    #[test]
    fn test_http_address_matches_docker_service_name() {
        let extractor = MicroserviceExtractor::new();
        // docker-compose service address without .svc.cluster.local suffix
        let address = "http://api-gateway:8080/v1/users";
        let service = extractor.extract_service_name(address, "http");
        assert_eq!(service, Some("api-gateway".to_string()));
    }

    #[test]
    fn test_http_address_matches_k8s_dns() {
        let extractor = MicroserviceExtractor::new();
        let address = "http://user-service.default.svc.cluster.local/health";
        let service = extractor.extract_service_name(address, "http");
        assert_eq!(service, Some("user-service".to_string()));
    }

    #[test]
    fn test_https_address_matches() {
        let extractor = MicroserviceExtractor::new();
        let address = "https://billing-api:8443";
        let service = extractor.extract_service_name(address, "https");
        assert_eq!(service, Some("billing-api".to_string()));
    }

    #[test]
    fn test_docker_service_name_with_port() {
        let extractor = MicroserviceExtractor::new();
        let service = extractor.extract_service_name("redis-cache:6379", "docker");
        assert_eq!(service, Some("redis-cache".to_string()));
    }

    #[test]
    fn test_grpc_client_http_address_emits_service_call() {
        let extractor = MicroserviceExtractor::new();
        let content = r#"
http.NewRequest("GET", "http://order-service:8080/orders", nil)
client.Get("https://payment-api:8443/pay")
"#;
        let rels = extractor.extract_grpc_calls(content, "client.go", &None);
        let protocols: Vec<&str> = rels
            .iter()
            .map(|r| r.metadata["protocol"].as_str().unwrap())
            .collect();
        assert!(protocols.contains(&"http"));
        assert!(protocols.contains(&"https"));
        let targets: Vec<&str> = rels.iter().map(|r| r.target_qualified.as_str()).collect();
        assert!(targets.contains(&"order-service"));
        assert!(targets.contains(&"payment-api"));
    }

    #[test]
    fn test_docker_bare_addr_in_yaml() {
        let extractor = MicroserviceExtractor::new();
        let yaml: serde_yaml::Value = serde_yaml::from_str(
            r#"
redis_address: "redis-cache:6379"
grpc_address: "dns:///cart-service.default.svc.cluster.local.:9000"
http_address: "http://web-front:3000"
"#,
        )
        .unwrap();
        let rels = extractor.extract_from_yaml(&yaml, "config.yaml", &None);
        assert_eq!(rels.len(), 3);
        let protocols: Vec<&str> = rels
            .iter()
            .map(|r| r.metadata["protocol"].as_str().unwrap())
            .collect();
        assert!(protocols.contains(&"docker"));
        assert!(protocols.contains(&"grpc"));
        assert!(protocols.contains(&"http"));
        let targets: Vec<&str> = rels.iter().map(|r| r.target_qualified.as_str()).collect();
        assert!(targets.contains(&"redis-cache"));
        assert!(targets.contains(&"cart-service"));
        assert!(targets.contains(&"web-front"));
    }
}