Skip to main content

code_system_graph_core/
router_mounts.rs

1//! Repository-level composition of router prefixes declared across source files.
2//!
3//! Extractors record the router each provider route is registered on and every mount of one
4//! router under a prefix on another. Composition resolves those references per repository, through
5//! file-local names, relative and package imports, and function paths, then rewrites each route
6//! path with every prefix chain that reaches it.
7
8use std::collections::{BTreeMap, BTreeSet};
9
10use crate::repository_symbols::{
11    RepositorySourceFile, RepositorySymbols, SymbolFile, SymbolKey, files_by_repository
12};
13use crate::{
14    SourceEpistemicStatus, SourceLanguage, SourceObservation, SourceRole, SymbolRef, normalize_source_http_path
15};
16
17/// Longest mount chain followed from a route to the application root.
18const MAX_MOUNT_DEPTH: usize = 8;
19/// Most composed paths retained for one router.
20const MAX_COMPOSED_PREFIXES: usize = 16;
21
22/// Rewrites provider paths with the router prefixes mounted above them.
23///
24/// The result has one observation list per input file, in input order. Mount observations are
25/// consumed, a route on a router mounted at several places is repeated once per composed path,
26/// and routes whose router is not mounted anywhere keep their path.
27#[must_use]
28pub fn compose_router_mounts(files: &[RepositorySourceFile<'_>]) -> Vec<Vec<SourceObservation>> {
29    let by_repository = files_by_repository(files);
30    let mut output = files
31        .iter()
32        .map(|file| file.observations.to_vec())
33        .collect::<Vec<_>>();
34    for members in by_repository.into_values() {
35        let repository = RepositoryRouters::new(files, &members);
36        if repository.mounts.is_empty() {
37            for &index in &members {
38                output[index].retain(|observation| observation.role != SourceRole::Mount);
39            }
40            continue;
41        }
42        let mut cache = BTreeMap::new();
43        for (local, &index) in members.iter().enumerate() {
44            output[index] = repository.rewrite(local, &mut cache);
45        }
46    }
47    output
48}
49
50struct RepositoryRouters<'a> {
51    symbols: RepositorySymbols<'a>,
52    mounts: BTreeMap<SymbolKey, Vec<(Option<SymbolKey>, String)>>,
53}
54
55impl<'a> RepositoryRouters<'a> {
56    fn new(files: &'a [RepositorySourceFile<'a>], members: &[usize]) -> Self {
57        let mut symbols = RepositorySymbols::new(
58            members
59                .iter()
60                .map(|&index| SymbolFile {
61                    path: files[index].path,
62                    observations: files[index].observations,
63                })
64                .collect(),
65        );
66        for local in 0..members.len() {
67            for observation in symbols.files()[local].observations {
68                for reference in [&observation.router, &observation.mount_parent]
69                    .into_iter()
70                    .flatten()
71                {
72                    if let SymbolRef::Function(name) = reference {
73                        symbols.declare_function(local, name);
74                    }
75                }
76            }
77        }
78        let mut mounts = BTreeMap::<SymbolKey, Vec<(Option<SymbolKey>, String)>>::new();
79        for local in 0..members.len() {
80            for observation in symbols.files()[local]
81                .observations
82                .iter()
83                .filter(|observation| observation.role == SourceRole::Mount)
84            {
85                let Some(child) = observation
86                    .router
87                    .as_ref()
88                    .and_then(|reference| symbols.resolve(local, reference))
89                else {
90                    continue;
91                };
92                let parent = observation
93                    .mount_parent
94                    .as_ref()
95                    .and_then(|reference| symbols.resolve(local, reference));
96                if parent.as_ref() == Some(&child) {
97                    continue;
98                }
99                let prefix = observation
100                    .path
101                    .as_deref()
102                    .map(prefix_text)
103                    .unwrap_or_default();
104                mounts.entry(child).or_default().push((parent, prefix));
105            }
106        }
107        for edges in mounts.values_mut() {
108            edges.sort();
109            edges.dedup();
110        }
111        Self { symbols, mounts }
112    }
113
114    fn rewrite(
115        &self,
116        local: usize,
117        cache: &mut BTreeMap<SymbolKey, Vec<String>>,
118    ) -> Vec<SourceObservation> {
119        let observations = self.symbols.files()[local].observations;
120        let mut output = Vec::with_capacity(observations.len());
121        for observation in observations {
122            match observation.role {
123                SourceRole::Mount => {}
124                SourceRole::Provider => {
125                    let prefixes = observation
126                        .router
127                        .as_ref()
128                        .and_then(|reference| self.symbols.resolve(local, reference))
129                        .map(|key| self.prefixes(&key, cache))
130                        .unwrap_or_default();
131                    match (&observation.path, prefixes.as_slice()) {
132                        (Some(path), [_, ..]) if prefixes != [""] => {
133                            output.extend(prefixes.iter().map(|prefix| {
134                                let mut composed = observation.clone();
135                                composed.path =
136                                    Some(normalize_source_http_path(&format!("{prefix}{path}")));
137                                composed
138                            }));
139                        }
140                        _ => output.push(observation.clone()),
141                    }
142                }
143                SourceRole::Consumer
144                | SourceRole::Test
145                | SourceRole::Factory
146                | SourceRole::Call
147                | SourceRole::Client => {
148                    output.push(observation.clone());
149                }
150            }
151        }
152        output
153    }
154
155    /// Returns every prefix chain from `key` to a root, outermost prefix first.
156    fn prefixes(
157        &self,
158        key: &SymbolKey,
159        cache: &mut BTreeMap<SymbolKey, Vec<String>>,
160    ) -> Vec<String> {
161        if let Some(cached) = cache.get(key) {
162            return cached.clone();
163        }
164        let mut visiting = Vec::new();
165        let mut prefixes = self.walk(key, &mut visiting);
166        if prefixes.is_empty() {
167            prefixes.push(String::new());
168        }
169        cache.insert(key.clone(), prefixes.clone());
170        prefixes
171    }
172
173    /// Chains through a cycle or deeper than [`MAX_MOUNT_DEPTH`] are dropped.
174    fn walk(&self, key: &SymbolKey, visiting: &mut Vec<SymbolKey>) -> Vec<String> {
175        let Some(edges) = self.mounts.get(key) else {
176            return vec![String::new()];
177        };
178        if visiting.len() >= MAX_MOUNT_DEPTH || visiting.contains(key) {
179            return Vec::new();
180        }
181        visiting.push(key.clone());
182        let mut prefixes = BTreeSet::new();
183        for (parent, prefix) in edges {
184            let outer = parent
185                .as_ref()
186                .map_or_else(|| vec![String::new()], |parent| self.walk(parent, visiting));
187            prefixes.extend(outer.into_iter().map(|outer| format!("{outer}{prefix}")));
188        }
189        visiting.pop();
190        prefixes.into_iter().take(MAX_COMPOSED_PREFIXES).collect()
191    }
192}
193
194/// Normalized prefix text without a trailing slash; the root prefix is empty.
195fn prefix_text(path: &str) -> String {
196    let normalized = normalize_source_http_path(path);
197    if normalized == "/" {
198        String::new()
199    } else {
200        normalized
201    }
202}
203
204/// Builds a mount observation recorded by a source extractor.
205#[must_use]
206pub(crate) fn mount_observation(
207    language: SourceLanguage,
208    framework: crate::SourceFramework,
209    child: SymbolRef,
210    parent: Option<SymbolRef>,
211    prefix: Option<&str>,
212    lines: crate::SourceLineRange,
213) -> SourceObservation {
214    SourceObservation {
215        language,
216        framework,
217        role: SourceRole::Mount,
218        method: None,
219        path: Some(normalize_source_http_path(prefix.unwrap_or("/"))),
220        symbol_name: None,
221        related_symbol: None,
222        related_path: None,
223        authority: None,
224        router: Some(child),
225        mount_parent: parent,
226        url: None,
227        call: None,
228        lines,
229        status: SourceEpistemicStatus::Confirmed,
230        confidence: 1.0,
231        warnings: Vec::new(),
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use code_system_graph_model::RepoId;
238
239    use super::{compose_router_mounts, mount_observation};
240    use crate::{
241        RepositorySourceFile, SourceEpistemicStatus, SourceFramework, SourceLanguage, SourceLineRange, SourceObservation, SourceRole, SymbolRef
242    };
243
244    const LINES: SourceLineRange = SourceLineRange { start: 1, end: 1 };
245
246    fn route(language: SourceLanguage, path: &str, router: SymbolRef) -> SourceObservation {
247        SourceObservation {
248            language,
249            framework: SourceFramework::Express,
250            role: SourceRole::Provider,
251            method: Some("GET".to_owned()),
252            path: Some(path.to_owned()),
253            symbol_name: Some("handler".to_owned()),
254            related_symbol: None,
255            related_path: None,
256            authority: None,
257            router: Some(router),
258            mount_parent: None,
259            url: None,
260            call: None,
261            lines: LINES,
262            status: SourceEpistemicStatus::Confirmed,
263            confidence: 1.0,
264            warnings: Vec::new(),
265        }
266    }
267
268    fn mount(
269        language: SourceLanguage,
270        child: SymbolRef,
271        parent: Option<SymbolRef>,
272        prefix: &str,
273    ) -> SourceObservation {
274        mount_observation(
275            language,
276            SourceFramework::Express,
277            child,
278            parent,
279            Some(prefix),
280            LINES,
281        )
282    }
283
284    fn composed_paths(files: &[(&str, Vec<SourceObservation>)]) -> Vec<String> {
285        let repo = RepoId::new("repo:api");
286        let inputs = files
287            .iter()
288            .map(|(path, observations)| RepositorySourceFile {
289                repo_id: &repo,
290                path,
291                observations,
292            })
293            .collect::<Vec<_>>();
294        let mut paths = compose_router_mounts(&inputs)
295            .into_iter()
296            .flatten()
297            .filter_map(|observation| observation.path)
298            .collect::<Vec<_>>();
299        paths.sort();
300        paths
301    }
302
303    fn local(name: &str) -> SymbolRef {
304        SymbolRef::Local(name.to_owned())
305    }
306
307    #[test]
308    fn script_imports_and_default_exports_should_compose_nested_prefixes() {
309        let js = SourceLanguage::TypeScript;
310        let files = [
311            (
312                "src/routes/orders.ts",
313                vec![
314                    route(js, "/:id", local("router")),
315                    mount(js, local("router"), Some(local("default")), "/"),
316                ],
317            ),
318            (
319                "src/routes/index.ts",
320                vec![mount(
321                    js,
322                    SymbolRef::Import {
323                        module: "./orders.js".to_owned(),
324                        name: "default".to_owned(),
325                    },
326                    Some(local("api")),
327                    "/orders",
328                )],
329            ),
330            (
331                "src/app.ts",
332                vec![
333                    mount(
334                        js,
335                        SymbolRef::Import {
336                            module: "./routes".to_owned(),
337                            name: "api".to_owned(),
338                        },
339                        Some(local("app")),
340                        "/v1",
341                    ),
342                    mount(
343                        js,
344                        SymbolRef::Import {
345                            module: "./routes/index".to_owned(),
346                            name: "api".to_owned(),
347                        },
348                        Some(local("app")),
349                        "/v2/",
350                    ),
351                ],
352            ),
353        ];
354
355        assert_eq!(
356            composed_paths(&files),
357            ["/v1/orders/:id".to_owned(), "/v2/orders/:id".to_owned()]
358        );
359    }
360
361    #[test]
362    fn python_modules_should_resolve_absolute_and_relative_imports() {
363        let py = SourceLanguage::Python;
364        let files = [
365            (
366                "src/app/api/users.py",
367                vec![route(py, "/users/{id}", local("router"))],
368            ),
369            (
370                "src/app/api/__init__.py",
371                vec![mount(
372                    py,
373                    SymbolRef::Import {
374                        module: ".users".to_owned(),
375                        name: "router".to_owned(),
376                    },
377                    Some(local("api")),
378                    "/internal",
379                )],
380            ),
381            (
382                "src/app/main.py",
383                vec![mount(
384                    py,
385                    SymbolRef::Import {
386                        module: "app".to_owned(),
387                        name: "api.api".to_owned(),
388                    },
389                    Some(local("app")),
390                    "/v1",
391                )],
392            ),
393        ];
394
395        assert_eq!(
396            composed_paths(&files),
397            ["/v1/internal/users/{id}".to_owned()]
398        );
399    }
400
401    #[test]
402    fn function_routers_should_resolve_by_module_path() {
403        let rust = SourceLanguage::Rust;
404        let files = [
405            (
406                "crates/api/src/orders/mod.rs",
407                vec![route(
408                    rust,
409                    "/{id}",
410                    SymbolRef::Function("routes".to_owned()),
411                )],
412            ),
413            (
414                "crates/api/src/users.rs",
415                vec![route(
416                    rust,
417                    "/{id}",
418                    SymbolRef::Function("routes".to_owned()),
419                )],
420            ),
421            (
422                "crates/api/src/main.rs",
423                vec![
424                    mount(
425                        rust,
426                        SymbolRef::Call("crate::orders::routes".to_owned()),
427                        Some(SymbolRef::Function("app".to_owned())),
428                        "/orders",
429                    ),
430                    mount(
431                        rust,
432                        SymbolRef::Call("routes".to_owned()),
433                        Some(SymbolRef::Function("app".to_owned())),
434                        "/ambiguous",
435                    ),
436                ],
437            ),
438        ];
439
440        assert_eq!(
441            composed_paths(&files),
442            ["/orders/{id}".to_owned(), "/{id}".to_owned()]
443        );
444    }
445
446    fn extracted_routes(files: &[(&str, &str)]) -> Vec<String> {
447        let repo = RepoId::new("repo:api");
448        let observations = files
449            .iter()
450            .map(|(path, source)| {
451                let extension = path.rsplit_once('.').map(|(_, extension)| extension);
452                match extension {
453                    Some("py") => crate::parse_python_source(source),
454                    Some("rs") => crate::parse_rust_source(source),
455                    Some("go") => crate::parse_go_source(source),
456                    Some("java") => crate::parse_java_source(source),
457                    Some("js") => crate::parse_javascript_source_at_path(path, source),
458                    _ => crate::parse_typescript_source_at_path(path, source),
459                }
460            })
461            .collect::<Vec<_>>();
462        let inputs = files
463            .iter()
464            .zip(&observations)
465            .map(|((path, _), observations)| RepositorySourceFile {
466                repo_id: &repo,
467                path,
468                observations,
469            })
470            .collect::<Vec<_>>();
471        let mut routes = compose_router_mounts(&inputs)
472            .into_iter()
473            .flatten()
474            .filter(|observation| {
475                observation.role == SourceRole::Provider
476                    && observation.status == SourceEpistemicStatus::Confirmed
477            })
478            .filter_map(|observation| {
479                Some(format!(
480                    "{} {} {}",
481                    observation.method?, observation.path?, observation.symbol_name?
482                ))
483            })
484            .collect::<Vec<_>>();
485        routes.sort();
486        routes
487    }
488
489    #[test]
490    fn fastapi_and_flask_mounts_should_compose_across_modules() {
491        let routes = extracted_routes(&[
492            (
493                "app/api/users.py",
494                "from fastapi import APIRouter\nrouter = APIRouter(prefix=\"/users\")\n\n@router.get(\"/{user_id}\")\ndef read_user(user_id: int):\n    return {}\n",
495            ),
496            (
497                "app/main.py",
498                "from fastapi import FastAPI\nfrom app.api import users\nfrom app.api.users import router as users_router\napp = FastAPI()\napp.include_router(users.router, prefix=\"/v1\")\napp.include_router(users_router, prefix=\"/v2\")\n",
499            ),
500            (
501                "shop/views.py",
502                "from flask import Blueprint\nbp = Blueprint(\"orders\", __name__, url_prefix=\"/orders\")\n\n@bp.route(\"/<int:order_id>\", methods=[\"GET\"])\ndef show(order_id):\n    return ''\n",
503            ),
504            (
505                "shop/__init__.py",
506                "from flask import Flask\nfrom .views import bp\napp = Flask(__name__)\napp.register_blueprint(bp, url_prefix=\"/shop\")\n",
507            ),
508        ]);
509
510        assert_eq!(
511            routes,
512            [
513                "GET /shop/orders/<int:order_id> show",
514                "GET /v1/users/{user_id} read_user",
515                "GET /v2/users/{user_id} read_user",
516            ]
517        );
518    }
519
520    #[test]
521    fn express_and_nest_mounts_should_compose_across_modules() {
522        let routes = extracted_routes(&[
523            (
524                "src/routes/orders.ts",
525                "import { Router } from 'express';\nconst router = Router();\nrouter.get('/:id', getOrder);\nexport default router;\n",
526            ),
527            (
528                "src/routes/users.js",
529                "const express = require('express');\nfunction buildUsers() {\n  const users = express.Router();\n  users.get('/:id', getUser);\n  return users;\n}\nmodule.exports = { buildUsers };\n",
530            ),
531            (
532                "src/app.ts",
533                "import express from 'express';\nimport orders from './routes/orders';\nconst { buildUsers } = require('./routes/users');\nconst app = express();\nconst api = express.Router();\napi.use('/orders', orders);\napi.use('/users', authenticate, buildUsers());\napp.use('/api', api);\n",
534            ),
535            (
536                "src/catalog/catalog.controller.ts",
537                "import { Controller, Get } from '@nestjs/common';\n@Controller('catalog')\nexport class CatalogController {\n  @Get(':sku')\n  findOne() {}\n  @Get()\n  findAll() {}\n}\n",
538            ),
539            (
540                "src/main.ts",
541                "import { NestFactory } from '@nestjs/core';\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.setGlobalPrefix('v2');\n}\n",
542            ),
543        ]);
544
545        assert_eq!(
546            routes,
547            [
548                "GET /api/orders/:id getOrder",
549                "GET /api/users/:id getUser",
550                "GET /v2/catalog findAll",
551                "GET /v2/catalog/:sku findOne",
552            ]
553        );
554    }
555
556    #[test]
557    fn spring_class_mappings_should_prefix_method_mappings() {
558        let routes = extracted_routes(&[(
559            "src/main/java/shop/OrderController.java",
560            "import org.springframework.web.bind.annotation.*;\n@RestController\n@RequestMapping(\"/api/orders\")\npublic class OrderController {\n  @GetMapping(\"/{id}\")\n  public Order get(@PathVariable long id) { return null; }\n  @PostMapping\n  public Order create() { return null; }\n}\n",
561        )]);
562
563        assert_eq!(
564            routes,
565            ["GET /api/orders/{id} get", "POST /api/orders create"]
566        );
567    }
568
569    #[test]
570    fn gin_chi_and_net_http_mounts_should_compose_across_packages() {
571        let routes = extracted_routes(&[
572            (
573                "internal/routes/orders.go",
574                "package routes\n\nimport \"github.com/gin-gonic/gin\"\n\nfunc RegisterOrders(rg *gin.RouterGroup) {\n\trg.GET(\"/:id\", getOrder)\n}\n",
575            ),
576            (
577                "cmd/api/main.go",
578                "package main\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n\t\"example.com/internal/routes\"\n)\n\nfunc main() {\n\tr := gin.Default()\n\tv1 := r.Group(\"/v1\")\n\t{\n\t\tv1.GET(\"/health\", health)\n\t}\n\troutes.RegisterOrders(v1.Group(\"/orders\"))\n}\n",
579            ),
580            (
581                "billing/server.go",
582                "package billing\n\nimport (\n\t\"net/http\"\n\t\"github.com/go-chi/chi/v5\"\n)\n\nfunc invoices() http.Handler {\n\tr := chi.NewRouter()\n\tr.Get(\"/{id}\", getInvoice)\n\treturn r\n}\n\nfunc Router() http.Handler {\n\tr := chi.NewRouter()\n\tr.Route(\"/billing\", func(r chi.Router) {\n\t\tr.Get(\"/status\", status)\n\t\tr.Mount(\"/invoices\", invoices())\n\t})\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"GET /payments/{id}\", getPayment)\n\treturn r\n}\n",
583            ),
584        ]);
585
586        assert_eq!(
587            routes,
588            [
589                "GET /billing/invoices/{id} getInvoice",
590                "GET /billing/status status",
591                "GET /payments/{id} getPayment",
592                "GET /v1/health health",
593                "GET /v1/orders/:id getOrder",
594            ]
595        );
596    }
597
598    #[test]
599    fn axum_and_actix_mounts_should_compose_across_modules() {
600        let routes = extracted_routes(&[
601            (
602                "orders/src/orders.rs",
603                "use axum::{routing::get, Router};\npub fn routes() -> Router {\n    Router::new().route(\"/{id}\", get(get_order))\n}\n",
604            ),
605            (
606                "orders/src/main.rs",
607                "use axum::{routing::get, Router};\nfn app() -> Router {\n    let api = Router::new().route(\"/health\", get(health));\n    Router::new()\n        .nest(\"/orders\", crate::orders::routes())\n        .nest(\"/api\", api)\n}\n",
608            ),
609            (
610                "billing/src/handlers.rs",
611                "use actix_web::{get, web, HttpResponse};\n#[get(\"/invoices/{id}\")]\nasync fn get_invoice() -> HttpResponse { HttpResponse::Ok().finish() }\npub fn config(cfg: &mut web::ServiceConfig) {\n    cfg.service(web::scope(\"/admin\").route(\"/audit\", web::get().to(audit)));\n}\n",
612            ),
613            (
614                "billing/src/main.rs",
615                "use actix_web::{web, App, HttpServer};\nasync fn main() {\n    HttpServer::new(|| {\n        App::new()\n            .service(web::scope(\"/api\").service(handlers::get_invoice))\n            .configure(handlers::config)\n    });\n}\n",
616            ),
617        ]);
618
619        assert_eq!(
620            routes,
621            [
622                "GET /admin/audit audit",
623                "GET /api/health health",
624                "GET /api/invoices/{id} get_invoice",
625                "GET /orders/{id} get_order",
626            ]
627        );
628    }
629
630    #[test]
631    fn mount_cycles_and_unresolved_routers_should_keep_route_paths() {
632        let go = SourceLanguage::Go;
633        let files = [(
634            "internal/http/routes.go",
635            vec![
636                route(go, "/orders", local("a")),
637                route(go, "/users", local("lonely")),
638                mount(go, local("a"), Some(local("b")), "/a"),
639                mount(go, local("b"), Some(local("a")), "/b"),
640                mount(
641                    go,
642                    SymbolRef::Call("missing.Register".to_owned()),
643                    None,
644                    "/x",
645                ),
646            ],
647        )];
648
649        assert_eq!(
650            composed_paths(&files),
651            ["/orders".to_owned(), "/users".to_owned()]
652        );
653    }
654}