This commit is contained in:
eyaltam19011971 2026-11-04 02:04:05 +00:00 • committed by GitHub
commit ce930fbc65
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 173 additions and 2 deletions

View file

@ -20,6 +20,7 @@ import { nextjsFileToRouteURL, normalizeFetchURL } from '../route-extractors/nex
import { buildFetchWrapperIndex } from '../route-extractors/fetch-wrapper-index.js';
import { expoFileToRouteURL } from '../route-extractors/expo.js';
import { phpFileToRouteURL } from '../route-extractors/php.js';
import { extractAxumRoutes } from '../route-extractors/axum.js';
import {
extractResponseShapes,
extractPHPResponseShapes,
@ -379,6 +380,20 @@ export const routesPhase: PipelinePhase<RoutesOutput> = {
});
}
const rustRouteCandidates = allPaths.filter((p) => p.endsWith('.rs'));
if (rustRouteCandidates.length > 0) {
const rustContents = await readFileContents(ctx.repoPath, rustRouteCandidates);
for (const [filePath, content] of rustContents) {
if (!content.includes('.route(')) continue;
for (const route of extractAxumRoutes(content)) {
addRoute(ensureSlash(route.routePath), {
filePath,
source: 'rust-axum-route',
});
}
}
}
let handlerContents: Map<string, string> | undefined;
if (routeRegistry.size > 0) {
// Resolve once so content attribution, the route stamp, and the edge use

View file

@ -0,0 +1,37 @@
// Rust Axum route extraction utilities.
//
// Axum commonly declares routes through chained Router::route calls:
// Router::new()
// .route("/api/items", get(list_items))
// .route(
// "/api/items/:id",
// get(get_item).put(update_item),
// )
//
// The route phase only needs the mounted URL and owning file to create Route
// nodes. Handler-level call resolution remains the responsibility of the Rust
// call graph.
export interface AxumRoute {
routePath: string;
}
const AXUM_ROUTE_PATTERN = /\.route\s*\(\s*["'`]([^"'`]+)["'`]/g;
export function extractAxumRoutes(content: string): AxumRoute[] {
const routes: AxumRoute[] = [];
const seen = new Set<string>();
AXUM_ROUTE_PATTERN.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = AXUM_ROUTE_PATTERN.exec(content)) !== null) {
const routePath = match[1]?.trim();
if (!routePath?.startsWith('/')) continue;
if (seen.has(routePath)) continue;
seen.add(routePath);
routes.push({ routePath });
}
return routes;
}

View file

@ -96,13 +96,15 @@ export function routeMatches(fetchURL: string, routeURL: string): boolean {
const fetchParts = fetchURL.split('/').filter(Boolean);
const routeParts = routeURL.split('/').filter(Boolean);
const isDynamicSegment = (part: string) => part.startsWith('[') || part.startsWith(':');
// Check for catch-all route: [...param] or optional catch-all [[...param]]
const lastRoutePart = routeParts[routeParts.length - 1];
if (lastRoutePart?.startsWith('[...') || lastRoutePart?.startsWith('[[...')) {
// Catch-all: match if fetch has at least as many segments as route (minus catch-all)
if (fetchParts.length < routeParts.length - 1) return false;
return routeParts.slice(0, -1).every((part, i) => {
if (part.startsWith('[') || fetchParts[i].startsWith('[')) return true;
if (isDynamicSegment(part) || isDynamicSegment(fetchParts[i])) return true;
return part === fetchParts[i];
});
}
@ -110,7 +112,7 @@ export function routeMatches(fetchURL: string, routeURL: string): boolean {
if (fetchParts.length !== routeParts.length) return false;
return fetchParts.every((part, i) => {
if (part.startsWith('[') || routeParts[i].startsWith('[')) return true;
if (isDynamicSegment(part) || isDynamicSegment(routeParts[i])) return true;
return part === routeParts[i];
});
}

View file

@ -0,0 +1,4 @@
export async function loadBilling() {
await fetch('/api/v1/workspace/billing/usage');
await fetch(`/api/v1/provider/accounts/${accountId}/licenses/quantity`);
}

View file

@ -0,0 +1,28 @@
use axum::{routing::{get, post, put}, Router};
pub struct SharedState;
pub fn routes() -> Router<SharedState> {
Router::new()
.route(
"/api/v1/workspace/billing/subscription",
get(my_subscription_handler),
)
.route("/api/v1/workspace/billing/usage", get(my_usage_handler))
.route("/api/v1/workspace/billing/plan", get(my_plan_handler))
.route(
"/api/v1/provider/accounts/:id/subscription",
get(get_subscription_handler).post(create_subscription_handler),
)
.route(
"/api/v1/provider/accounts/:id/licenses/quantity",
put(update_account_license_quantity_handler),
)
}
pub async fn my_subscription_handler() {}
pub async fn my_usage_handler() {}
pub async fn my_plan_handler() {}
pub async fn get_subscription_handler() {}
pub async fn create_subscription_handler() {}
pub async fn update_account_license_quantity_handler() {}

View file

@ -80,3 +80,37 @@ describe('Next.js route mapping', () => {
}
});
});
describe('Rust Axum route mapping', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(FIXTURES, 'rust-axum-routes'), () => {});
}, 60000);
it('creates Route nodes for Axum Router::route declarations', () => {
const routes = getNodesByLabel(result, 'Route');
expect(routes).toContain('/api/v1/workspace/billing/usage');
expect(routes).toContain('/api/v1/workspace/billing/subscription');
expect(routes).toContain('/api/v1/provider/accounts/:id/licenses/quantity');
});
it('creates HANDLES_ROUTE edges from the Rust route file', () => {
const edges = getRelationships(result, 'HANDLES_ROUTE');
const usageRoute = edges.find((e) => e.target === '/api/v1/workspace/billing/usage');
expect(usageRoute).toBeDefined();
expect(usageRoute!.sourceFilePath).toContain('src/routes.rs');
expect(usageRoute!.rel.reason).toBe('rust-axum-route');
});
it('matches frontend fetch consumers to Axum colon-parameter routes', () => {
const edges = getRelationships(result, 'FETCHES');
expect(
edges.find(
(e) =>
e.sourceFilePath.includes('provider-api.ts') &&
e.target === '/api/v1/provider/accounts/:id/licenses/quantity',
),
).toBeDefined();
});
});

View file

@ -7,6 +7,7 @@ import {
normalizeFetchURL,
routeMatches,
} from '../../src/core/ingestion/route-extractors/nextjs.js';
import { extractAxumRoutes } from '../../src/core/ingestion/route-extractors/axum.js';
import { phpFileToRouteURL } from '../../src/core/ingestion/route-extractors/php.js';
import {
extractMiddlewareChain,
@ -195,6 +196,21 @@ describe('routeMatches', () => {
expect(routeMatches('/api/orgs/[param]/grants', '/api/orgs/[slug]/grants')).toBe(true);
});
it('matches Axum colon dynamic segments against concrete and normalized fetches', () => {
expect(
routeMatches(
'/api/v1/provider/accounts/acct-1/licenses',
'/api/v1/provider/accounts/:id/licenses',
),
).toBe(true);
expect(
routeMatches(
'/api/v1/provider/accounts/[param]/licenses/quantity',
'/api/v1/provider/accounts/:id/licenses/quantity',
),
).toBe(true);
});
it('matches catch-all routes against longer paths', () => {
expect(routeMatches('/api/docs/a/b/c', '/api/[...slug]')).toBe(true);
expect(routeMatches('/api/proxy/x', '/api/[...slug]')).toBe(true);
@ -215,6 +231,41 @@ describe('routeMatches', () => {
});
});
// ---------------------------------------------------------------------------
// Rust Axum route extractor
// ---------------------------------------------------------------------------
describe('extractAxumRoutes', () => {
it('extracts chained single-line and multiline Router::route declarations', () => {
const routes = extractAxumRoutes(`
pub fn routes() -> axum::Router<State> {
axum::Router::new()
.route("/api/v1/workspace/billing/usage", get(my_usage_handler))
.route(
"/api/v1/provider/accounts/:id/licenses/quantity",
put(update_account_license_quantity_handler),
)
}
`);
expect(routes.map((route) => route.routePath)).toEqual([
'/api/v1/workspace/billing/usage',
'/api/v1/provider/accounts/:id/licenses/quantity',
]);
});
it('ignores non-absolute routes and deduplicates repeated paths', () => {
const routes = extractAxumRoutes(`
Router::new()
.route("relative", get(relative))
.route("/api/v1/workspace/billing/usage", get(a))
.route("/api/v1/workspace/billing/usage", post(b))
`);
expect(routes.map((route) => route.routePath)).toEqual(['/api/v1/workspace/billing/usage']);
});
});
// ---------------------------------------------------------------------------
// Response shape extraction (brace-depth parser edge cases)
// ---------------------------------------------------------------------------