ui-entrypoints-api.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /**
  2. * `GET /api/entrypoints` and the panel it draws (CG-54).
  3. *
  4. * Two indexed projects over two real loopback servers, because the two answers
  5. * this endpoint has to get right are opposites:
  6. *
  7. * - **A routed service.** `__tests__/fixtures/payroll-go` is a Go HTTP service
  8. * whose four routes are registered in one router file and served from
  9. * another, which is exactly the shape that makes "group routes by file"
  10. * ambiguous — and the reason the payload carries the registration site as
  11. * well as the handler. It is also the issue's acceptance case: the routes
  12. * appear with their handlers, and the route's own handler reaches the store
  13. * as a flow.
  14. * - **A library.** A TypeScript project with no routes at all, where the panel
  15. * must fall back to the files that run something and the tests that exercise
  16. * them, and must NOT draw an empty Routes box: "this isn't a web app" is an
  17. * answer, not a failure.
  18. *
  19. * The grouping itself is pure and lives in `ui/src/lib/entry-model.ts`; it is
  20. * driven here from the real payload so a wire change that the pure tests would
  21. * happily keep passing still fails somewhere.
  22. */
  23. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  24. import * as http from 'http';
  25. import * as fs from 'fs';
  26. import * as os from 'os';
  27. import * as path from 'path';
  28. import CodeGraph from '../src/index';
  29. import { createGraphApi, startUiServer, type GraphApi, type UiServerHandle } from '../src/ui-server';
  30. import { resetEntryPointsCache } from '../src/ui-server/api/entrypoints';
  31. import { splitRouteName } from '../src/ui-server/api/routes';
  32. import { isTestFile, isTestPath } from '../src/search/query-utils';
  33. import { buildEntryPanel, frameworkPhrase } from '../ui/src/lib/entry-model';
  34. import type { WireEntryPoints } from '../ui/src/lib/api';
  35. const FIXTURE_GO = path.join(__dirname, 'fixtures', 'payroll-go');
  36. interface Instance {
  37. dir: string;
  38. root: string;
  39. cg: CodeGraph;
  40. api: GraphApi;
  41. server: UiServerHandle;
  42. }
  43. function request(port: number, requestPath: string): Promise<{ status: number; body: string; type?: string }> {
  44. return new Promise((resolve, reject) => {
  45. const req = http.request(
  46. {
  47. host: '127.0.0.1',
  48. port,
  49. path: requestPath,
  50. method: 'GET',
  51. headers: { Host: `127.0.0.1:${port}` },
  52. setHost: false,
  53. },
  54. (res) => {
  55. const chunks: Buffer[] = [];
  56. res.on('data', (c: Buffer) => chunks.push(c));
  57. res.on('end', () =>
  58. resolve({
  59. status: res.statusCode ?? 0,
  60. body: Buffer.concat(chunks).toString('utf-8'),
  61. type: res.headers['content-type'],
  62. })
  63. );
  64. }
  65. );
  66. req.on('error', reject);
  67. req.end();
  68. });
  69. }
  70. async function getJson(instance: Instance, requestPath: string, expected = 200): Promise<any> {
  71. const res = await request(instance.server.port, requestPath);
  72. expect(res.type).toBe('application/json; charset=utf-8');
  73. expect(res.status).toBe(expected);
  74. return JSON.parse(res.body);
  75. }
  76. async function serve(root: string, dir: string, cg: CodeGraph): Promise<Instance> {
  77. const api = createGraphApi({ projectRoot: root });
  78. const server = await startUiServer({ projectRoot: root, port: 0, api: api.handler });
  79. return { dir, root, cg, api, server };
  80. }
  81. function write(root: string, rel: string, body: string): void {
  82. const full = path.join(root, rel);
  83. fs.mkdirSync(path.dirname(full), { recursive: true });
  84. fs.writeFileSync(full, body);
  85. }
  86. async function stop(instance: Instance | undefined): Promise<void> {
  87. if (!instance) return;
  88. await instance.server.close();
  89. instance.api.close();
  90. instance.cg.destroy();
  91. fs.rmSync(instance.dir, { recursive: true, force: true });
  92. }
  93. /* ======================================================================== */
  94. /* A routed Go service — the issue's acceptance case */
  95. /* ======================================================================== */
  96. describe('entry points on a routed service', () => {
  97. let go: Instance;
  98. let payload: WireEntryPoints;
  99. beforeAll(async () => {
  100. resetEntryPointsCache();
  101. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-ui-entry-go-'));
  102. fs.cpSync(FIXTURE_GO, dir, { recursive: true });
  103. // A stray index in the checked-in tree would be copied in and reused.
  104. fs.rmSync(path.join(dir, '.codegraph'), { recursive: true, force: true });
  105. const cg = CodeGraph.initSync(dir);
  106. await cg.indexAll();
  107. go = await serve(dir, dir, cg);
  108. payload = (await getJson(go, '/api/entrypoints')) as WireEntryPoints;
  109. }, 120_000);
  110. afterAll(async () => {
  111. await stop(go);
  112. });
  113. it('names the framework the route list came from', () => {
  114. expect(payload.frameworks).toContain('go');
  115. expect(frameworkPhrase(payload.frameworks)).toContain('go');
  116. });
  117. it('lists every route with the symbol that serves it', () => {
  118. expect(payload.routes.routed).toBe(true);
  119. expect(payload.routes.routeCount).toBe(4);
  120. const rows = payload.routes.items.items;
  121. expect(rows).toHaveLength(4);
  122. expect(rows.map((r) => r.url)).toEqual(
  123. expect.arrayContaining([
  124. 'POST /v1/payroll/cycles/{cycleID}/run',
  125. 'GET /v1/payroll/cycles/{cycleID}',
  126. 'GET /v1/payroll/cycles/{cycleID}/payslips',
  127. 'GET /healthz',
  128. ])
  129. );
  130. const run = rows.find((r) => r.url.startsWith('POST '));
  131. expect(run).toBeDefined();
  132. expect(run?.method).toBe('POST');
  133. expect(run?.path).toBe('/v1/payroll/cycles/{cycleID}/run');
  134. expect(run?.handler).toBe('RunCycle');
  135. expect(run?.file).toBe('internal/transport/httpapi/payroll_handler.go');
  136. // A row has to be navigable, or it is a label.
  137. expect(run?.handlerId).toBeTruthy();
  138. expect(rows.every((r) => r.handlerId)).toBe(true);
  139. });
  140. it('carries where each URL is registered, which is not where it is served', () => {
  141. const rows = payload.routes.items.items;
  142. // Every route is registered by NewRouter; three of the four are served
  143. // from a different file. Without the registration site there is nothing
  144. // to group four routes under.
  145. expect(new Set(rows.map((r) => r.routeFile))).toEqual(
  146. new Set(['internal/transport/httpapi/router.go'])
  147. );
  148. expect(new Set(rows.map((r) => r.file)).size).toBe(2);
  149. expect(rows.every((r) => r.routeLine > 0)).toBe(true);
  150. });
  151. it('groups the panel by the router file, with the handler in the meta line', () => {
  152. const panel = buildEntryPanel(payload);
  153. const routes = panel.sections.find((s) => s.id === 'routes');
  154. expect(routes).toBeDefined();
  155. expect(routes?.groups).toHaveLength(1);
  156. expect(routes?.groups[0]?.path).toBe('internal/transport/httpapi/router.go');
  157. expect(routes?.groups[0]?.rows).toHaveLength(4);
  158. // The framework rides in the section header, beside the count.
  159. expect(routes?.meta).toContain('go');
  160. const run = routes?.groups[0]?.rows.find((r) => r.method === 'POST');
  161. expect(run?.name).toBe('/v1/payroll/cycles/{cycleID}/run');
  162. expect(run?.meta).toBe('RunCycle · payroll_handler.go:34');
  163. expect(run?.target).toEqual({
  164. type: 'symbol',
  165. id: expect.any(String),
  166. name: 'RunCycle',
  167. kind: 'method',
  168. });
  169. // A route names a callable symbol, so it can start a flow.
  170. expect(run?.flowFrom).toBe('RunCycle');
  171. });
  172. it('draws the flow from a route handler down to the store', async () => {
  173. // The issue's "route -> insertNode-style flow": the POST handler reaching
  174. // the row that lands in the database.
  175. const flow = await getJson(go, '/api/flow?from=RunCycle&to=Upsert');
  176. expect(flow.flows.length).toBeGreaterThan(0);
  177. const hops = flow.flows[0].hops.map((h: any) => h.node.name);
  178. expect(hops[0]).toBe('RunCycle');
  179. expect(hops[hops.length - 1]).toBe('Upsert');
  180. expect(hops).toContain('runPayrollCycleAll');
  181. // Every hop after the first carries the edge that got there.
  182. expect(flow.flows[0].hops.slice(1).every((h: any) => h.edge)).toBe(true);
  183. });
  184. it('answers a second time from the cache', async () => {
  185. const again = await getJson(go, '/api/entrypoints');
  186. expect(again.timing.cached).toBe(true);
  187. expect(again.routes.items.items).toEqual(payload.routes.items.items);
  188. });
  189. it('refuses a route window it cannot answer truthfully', async () => {
  190. // Under three rows the engine's own "is this routed" test cannot run, so
  191. // the parameter is floored rather than silently answering "not routed".
  192. const body = await getJson(go, '/api/entrypoints?routes=2', 400);
  193. expect(body.error).toMatch(/routes/);
  194. });
  195. });
  196. /* ======================================================================== */
  197. /* A library — no routes, and no empty Routes box */
  198. /* ======================================================================== */
  199. describe('entry points on a project with no routes', () => {
  200. let lib: Instance;
  201. let payload: WireEntryPoints;
  202. beforeAll(async () => {
  203. resetEntryPointsCache();
  204. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-ui-entry-lib-'));
  205. const root = path.join(dir, 'project');
  206. fs.mkdirSync(root, { recursive: true });
  207. write(
  208. root,
  209. 'src/store.ts',
  210. `export function insertNode(name: string): string {
  211. return name.trim();
  212. }
  213. export function readNode(name: string): string {
  214. return insertNode(name);
  215. }
  216. `
  217. );
  218. // Module-level statements: the only reason an executable root is visible.
  219. write(
  220. root,
  221. 'src/main.ts',
  222. `import { insertNode, readNode } from './store';
  223. const first = insertNode('boot');
  224. const second = readNode('warm');
  225. export const started = [first, second];
  226. `
  227. );
  228. write(
  229. root,
  230. '__tests__/store.test.ts',
  231. `import { insertNode } from '../src/store';
  232. export function exercisesTheStore(): string {
  233. return insertNode('x');
  234. }
  235. exercisesTheStore();
  236. `
  237. );
  238. // A fixture is not a test, even though the ranking treats it as one.
  239. write(root, '__tests__/fixtures/sample.ts', `export const sample = 1;\n`);
  240. const cg = CodeGraph.initSync(root, {
  241. config: { include: ['src/**/*.ts', '__tests__/**/*.ts'], exclude: [] },
  242. });
  243. await cg.indexAll();
  244. cg.resolveReferences();
  245. lib = await serve(root, dir, cg);
  246. payload = (await getJson(lib, '/api/entrypoints')) as WireEntryPoints;
  247. }, 120_000);
  248. afterAll(async () => {
  249. await stop(lib);
  250. });
  251. it('says it is not a routed app instead of drawing an empty list', () => {
  252. expect(payload.routes.routed).toBe(false);
  253. expect(payload.routes.items.items).toEqual([]);
  254. expect(payload.routes.items.total).toBe(0);
  255. const panel = buildEntryPanel(payload);
  256. // No Routes heading at all — an empty box under a heading reads as a
  257. // failure, and this is the ordinary shape of a library.
  258. expect(panel.sections.map((s) => s.id)).not.toContain('routes');
  259. // …and the panel is not empty: it fell back to what does exist.
  260. expect(panel.empty).toBeNull();
  261. expect(panel.sections.length).toBeGreaterThan(0);
  262. });
  263. it('falls back to the file that runs something at module level', () => {
  264. const files = payload.files.items.map((f) => f.file);
  265. expect(files).toContain('src/main.ts');
  266. expect(files).not.toContain('__tests__/store.test.ts');
  267. const main = payload.files.items.find((f) => f.file === 'src/main.ts');
  268. expect(main?.calls).toBeGreaterThan(0);
  269. expect(main?.reaches).toBeGreaterThan(0);
  270. const panel = buildEntryPanel(payload);
  271. const section = panel.sections.find((s) => s.id === 'files');
  272. expect(section?.title).toBe('Top-level files with calls');
  273. expect(section?.groups[0]?.path).toBe('src');
  274. // A file has no name the path finder can look up, so no flow chip.
  275. expect(section?.groups[0]?.rows.every((r) => r.flowFrom === null)).toBe(true);
  276. expect(section?.groups[0]?.rows[0]?.target).toEqual({ type: 'file', path: 'src/main.ts' });
  277. });
  278. it('lists the tests by what they exercise', () => {
  279. const tests = payload.tests.items.map((t) => t.file);
  280. expect(tests).toContain('__tests__/store.test.ts');
  281. // A fixture reaches nothing and is not a test; either reason keeps it out.
  282. expect(tests).not.toContain('__tests__/fixtures/sample.ts');
  283. const suite = payload.tests.items.find((t) => t.file === '__tests__/store.test.ts');
  284. expect(suite?.reaches).toBeGreaterThan(0);
  285. expect(suite?.refs).toBeGreaterThanOrEqual(suite?.reaches ?? 0);
  286. const panel = buildEntryPanel(payload);
  287. const section = panel.sections.find((s) => s.id === 'tests');
  288. expect(section?.title).toBe('Tests');
  289. expect(section?.groups[0]?.rows[0]?.meta).toMatch(/^exercises \d+ files? · \d+ references?$/);
  290. });
  291. it('counts the tests exactly, and the derived lists as a floor', () => {
  292. // Every count equals a list in the same payload, or is labelled a floor.
  293. expect(payload.tests.total).toBe(payload.tests.items.length);
  294. expect(payload.files.total).toBeGreaterThanOrEqual(payload.files.items.length);
  295. expect(payload.hubs.total).toBeGreaterThanOrEqual(payload.hubs.items.length);
  296. const panel = buildEntryPanel(payload);
  297. expect(panel.sections.find((s) => s.id === 'tests')?.floor).toBe(false);
  298. expect(panel.sections.find((s) => s.id === 'files')?.floor).toBe(true);
  299. });
  300. });
  301. /* ======================================================================== */
  302. /* The narrow test predicate */
  303. /* ======================================================================== */
  304. describe('what counts as a test', () => {
  305. it('keeps the suites and drops the examples', () => {
  306. for (const suite of [
  307. 'foo_test.go',
  308. 'src/foo.test.ts',
  309. 'src/__tests__/foo.ts',
  310. 'test/foo.rb',
  311. 'src/FooTest.java',
  312. 'app/src/jvmTest/Bar.kt',
  313. ]) {
  314. expect(isTestPath(suite), suite).toBe(true);
  315. expect(isTestFile(suite), suite).toBe(true);
  316. }
  317. // Examples, benchmarks and fixtures are still off-target for RANKING —
  318. // nothing about this change moves that — but they are not tests, and a
  319. // heading that says "Tests" must not gather them.
  320. for (const other of ['examples/demo.ts', 'benchmarks/run.ts', 'fixtures/a.ts']) {
  321. expect(isTestFile(other), other).toBe(true);
  322. expect(isTestPath(other), other).toBe(false);
  323. }
  324. });
  325. });
  326. /* ======================================================================== */
  327. /* Route names */
  328. /* ======================================================================== */
  329. describe('splitting a route name', () => {
  330. it('takes the verb off when there is one', () => {
  331. expect(splitRouteName('POST /v1/users')).toEqual({ method: 'POST', path: '/v1/users' });
  332. expect(splitRouteName('ANY /healthz')).toEqual({ method: 'ANY', path: '/healthz' });
  333. });
  334. it('leaves a file-routed page whole', () => {
  335. // A verb column invented out of the first path segment would be a lie, and
  336. // the URL would lose its head.
  337. expect(splitRouteName('/blog/[slug]')).toEqual({ method: null, path: '/blog/[slug]' });
  338. expect(splitRouteName('user.created handler')).toEqual({
  339. method: null,
  340. path: 'user.created handler',
  341. });
  342. });
  343. });