Skip to content

Commit 2e71bcc

Browse files
authored
perf(ui): cache build-meta in the panel's RPC client (#410)
devframe 1.2.4 added client-side RPC caching. The panel now caches pangular:build-meta only, through an explicit PANEL_CACHED_RPC list, since its answer does not change while the dev server runs. The cache is cleared when the connection drops, so a restarted server is always asked again.
1 parent e0de840 commit 2e71bcc

11 files changed

Lines changed: 300 additions & 75 deletions

File tree

‎app/src/__tests__/app-shell.test.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ const connection = vi.hoisted(() => ({
88
answers: [] as boolean[],
99
/** Sends a `connection:status` event to the last connected client's listeners. */
1010
emitStatus: (_status: string) => {},
11+
/** The options each attempt passed to `connectDevframe`. */
12+
options: [] as unknown[],
13+
/** How many clients the panel closed. */
14+
closed: 0,
1115
}));
1216

1317
function fakeClient(): DevframeRpcClient {
@@ -27,12 +31,15 @@ function fakeClient(): DevframeRpcClient {
2731
return () => {};
2832
},
2933
},
30-
close: () => {},
34+
close: () => {
35+
connection.closed++;
36+
},
3137
} as unknown as DevframeRpcClient;
3238
}
3339

3440
vi.mock('devframe/client', () => ({
35-
connectDevframe: () => {
41+
connectDevframe: (options?: unknown) => {
42+
connection.options.push(options);
3643
const ok = connection.answers[connection.attempts++] ?? false;
3744
return ok ? Promise.resolve(fakeClient()) : Promise.reject(new Error('no server'));
3845
},
@@ -55,6 +62,8 @@ afterEach(() => {
5562
document.body.innerHTML = '';
5663
connection.attempts = 0;
5764
connection.answers = [];
65+
connection.options = [];
66+
connection.closed = 0;
5867
TestBed.resetTestingModule();
5968
});
6069

@@ -112,6 +121,25 @@ describe('App connection retry', () => {
112121
fixture.destroy();
113122
});
114123

124+
it('caches only build-meta, in a new client after the connection drops', async () => {
125+
connection.answers = [true, true];
126+
const fixture = TestBed.createComponent(App);
127+
await settle(fixture);
128+
expect(connection.options[0]).toMatchObject({
129+
cacheOptions: { functions: ['pangular:build-meta'] },
130+
});
131+
132+
// A restarted server gets a new client, so nothing cached before is reused.
133+
connection.emitStatus('disconnected');
134+
await settle(fixture);
135+
expect(connection.closed).toBe(1);
136+
await vi.waitFor(() => expect(connection.attempts).toBe(2), { timeout: 3000 });
137+
expect(connection.options[1]).toMatchObject({
138+
cacheOptions: { functions: ['pangular:build-meta'] },
139+
});
140+
fixture.destroy();
141+
});
142+
115143
it('stops retrying once the panel is gone', async () => {
116144
connection.answers = [false, true];
117145
const fixture = TestBed.createComponent(App);

‎app/src/app.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import { hostPageId, scopeToPage } from './page-id';
4646
import { angularNativePage, type PlatformPage } from './native-page';
4747
import { initialTab, storeTab, storedTab } from './tab-memory';
4848
import { detectBaseURL } from './base-url';
49-
import { clearHighlightsOnHide, rpcTry } from './rpc';
49+
import { clearHighlightsOnHide, panelCacheOptions, rpcTry } from './rpc';
5050
import { EditorOpener } from './ui/source-link';
5151
import { viewAccent } from './view-accents';
5252
import {
@@ -1279,7 +1279,10 @@ export class App implements OnInit, OnDestroy {
12791279
this.connecting = true;
12801280
clearTimeout(this.retryTimer);
12811281
const baseURL = detectBaseURL();
1282-
connectDevframe(baseURL ? { baseURL } : {}).then(
1282+
connectDevframe({
1283+
...(baseURL ? { baseURL } : {}),
1284+
cacheOptions: panelCacheOptions(),
1285+
}).then(
12831286
(client) => {
12841287
this.connecting = false;
12851288
if (this.destroyed) {

‎app/src/rpc.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
1+
import { PANEL_CACHED_RPC } from '@pangular-inspector/devtools/config';
12
import type { DevframeRpcClient } from 'devframe/client';
23

4+
/**
5+
* The panel client's devframe `cacheOptions`: an explicit list, so only the
6+
* functions in `PANEL_CACHED_RPC` are cached, never whatever else the server
7+
* advertises as cacheable. devframe clears it when the connection changes.
8+
*/
9+
export function panelCacheOptions(): { functions: string[] } {
10+
return { functions: [...PANEL_CACHED_RPC] };
11+
}
12+
313
/** Calls a `pangular` RPC; resolves `null` without a client, rejections propagate. */
414
export function rpcCall(
515
client: DevframeRpcClient | null,

‎apps/docs/src/content/contributing/development.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,8 @@ If a code change needs no docs change, add the `no-docs` label to the pull reque
232232
3. Map it to its inspector in `RPC_INSPECTOR` in `packages/devtools/src/config.ts`, so turning the inspector off removes it.
233233
4. Call it from the UI in `app/src/pages/`.
234234

235+
The panel's devframe client caches the functions listed in `PANEL_CACHED_RPC` in `packages/devtools/src/config.ts`, and only those. A cached call is answered from the client until the connection drops, so a restarted server is asked again. Add a function there only when its answer can't change while the server runs, and give it `type: 'static'` or `cacheable: true`. Live page data and source scans never qualify.
236+
235237
### Add a tab
236238

237239
1. Create a component in `app/src/pages/`.

‎apps/docs/src/content/inspectors/dashboard.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ The Forms and SSR & HTTP cards read the live page only, and update while it runs
102102

103103
If the project block says **Project details unavailable**, check that the dev server is running, then click **Try again**. In a [static report](../getting-started/cli.md#static-report) there is no **Try again** button, so run `pangular build` again to rebuild the report.
104104

105+
The panel reads the project details once per connection and keeps them. If you upgrade a package or edit `angular.json` while the dev server runs, restart the dev server or reload the panel to see the change.
106+
105107
## FAQ
106108

107109
<ngmd-accordion>

extension/ui/assets/browser-agent-rpc-BXhoSh1z-BF1s_IvO.js renamed to extension/ui/assets/browser-agent-rpc-BXhoSh1z-rr8okg_T.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 69 additions & 69 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎extension/ui/index.html‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2+
import { tmpdir } from 'node:os';
3+
import { join } from 'node:path';
4+
import { defineDevframe } from 'devframe';
5+
import { createDevServer } from 'devframe/adapters/dev';
6+
import { connectDevframe, type DevframeRpcClient } from 'devframe/client';
7+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8+
import { PANEL_CACHED_RPC, RPC_INSPECTOR, SHARED_RPC } from '../config.ts';
9+
import { getBuildMeta } from '../rpc/build-meta.ts';
10+
11+
type Started = Awaited<ReturnType<typeof createDevServer>>;
12+
13+
/**
14+
* A devframe server with the real `build-meta` and a live query, each counting
15+
* the calls that reach the server, so the tests see what the client cached.
16+
*/
17+
async function startServer(cwd: string, calls: Map<string, number>): Promise<Started> {
18+
const count = (name: string) => calls.set(name, (calls.get(name) ?? 0) + 1);
19+
const definition = defineDevframe({
20+
id: 'pangular',
21+
name: 'Pangular Inspector',
22+
version: '0.0.0',
23+
packageName: '@pangular-inspector/devtools',
24+
homepage: 'https://pangular-inspector.dev',
25+
description: 'Cache test server',
26+
setup(ctx) {
27+
const my = ctx.scope('pangular');
28+
my.rpc.register({
29+
...getBuildMeta,
30+
setup: async (setupCtx) => {
31+
// The dev server's context reads process.cwd(); point it at the fixture.
32+
const { handler } = await getBuildMeta.setup!({ ...setupCtx, cwd });
33+
return {
34+
handler: (...args: []) => {
35+
count('build-meta');
36+
return handler!(...args);
37+
},
38+
};
39+
},
40+
});
41+
my.rpc.register({
42+
name: 'list-pages',
43+
type: 'query',
44+
jsonSerializable: true,
45+
handler: () => {
46+
count('list-pages');
47+
return [];
48+
},
49+
});
50+
},
51+
});
52+
return createDevServer(definition, {
53+
host: '127.0.0.1',
54+
port: 0,
55+
auth: false,
56+
mcp: false,
57+
openBrowser: false,
58+
});
59+
}
60+
61+
function scoped(client: DevframeRpcClient) {
62+
return client.scope('pangular').rpc as unknown as {
63+
call: (name: string) => Promise<unknown>;
64+
};
65+
}
66+
67+
describe('panel RPC cache', () => {
68+
let cwd: string;
69+
const servers: Started[] = [];
70+
const clients: DevframeRpcClient[] = [];
71+
72+
beforeEach(() => {
73+
cwd = mkdtempSync(join(tmpdir(), 'pangular-cache-'));
74+
writeFileSync(join(cwd, 'package.json'), JSON.stringify({ name: 'cache-demo' }));
75+
});
76+
77+
afterEach(async () => {
78+
for (const client of clients.splice(0)) client.close?.();
79+
for (const server of servers.splice(0)) await server.close().catch(() => undefined);
80+
rmSync(cwd, { recursive: true, force: true });
81+
vi.unstubAllGlobals();
82+
});
83+
84+
async function connect(server: Started): Promise<DevframeRpcClient> {
85+
// The browser client resolves the socket URL against its page location.
86+
vi.stubGlobal('location', new URL(`${server.origin}/`));
87+
// It also reuses the connection an earlier client stored on the global
88+
// object, which points at an earlier server here.
89+
const stored = globalThis as Record<string, unknown>;
90+
delete stored['__DEVFRAME_CONNECTION__'];
91+
delete stored['__DEVFRAME_CONNECTION_META__'];
92+
const client = await connectDevframe({
93+
baseURL: `${server.origin}/`,
94+
cacheOptions: { functions: [...PANEL_CACHED_RPC] },
95+
webmcp: false,
96+
callTimeout: 5000,
97+
});
98+
clients.push(client);
99+
await client.ensureTrusted();
100+
return client;
101+
}
102+
103+
async function start(calls: Map<string, number>): Promise<Started> {
104+
const server = await startServer(cwd, calls);
105+
servers.push(server);
106+
return server;
107+
}
108+
109+
it('lists only static or cacheable functions the panel server registers', () => {
110+
expect(PANEL_CACHED_RPC).toEqual(['pangular:build-meta']);
111+
expect(getBuildMeta.type).toBe('static');
112+
expect(getBuildMeta.cacheable).toBe(true);
113+
for (const name of PANEL_CACHED_RPC) {
114+
const bare = name.replace(/^pangular:/, '');
115+
expect(SHARED_RPC.includes(bare) || bare in RPC_INSPECTOR).toBe(true);
116+
}
117+
});
118+
119+
it('answers a repeat build-meta call from the cache', async () => {
120+
const calls = new Map<string, number>();
121+
const client = await connect(await start(calls));
122+
const first = (await scoped(client).call('build-meta')) as { projectName: string };
123+
const second = await scoped(client).call('build-meta');
124+
expect(first.projectName).toBe('cache-demo');
125+
expect(second).toEqual(first);
126+
expect(calls.get('build-meta')).toBe(1);
127+
expect(client.cacheManager.has('pangular:build-meta', [])).toBe(true);
128+
});
129+
130+
it('sends every call of a function outside the list to the server', async () => {
131+
const calls = new Map<string, number>();
132+
const client = await connect(await start(calls));
133+
await scoped(client).call('list-pages');
134+
await scoped(client).call('list-pages');
135+
await scoped(client).call('list-pages');
136+
expect(calls.get('list-pages')).toBe(3);
137+
expect(client.cacheManager.has('pangular:list-pages', [])).toBe(false);
138+
});
139+
140+
it('asks a restarted server again instead of serving the old answer', async () => {
141+
const before = new Map<string, number>();
142+
const server = await start(before);
143+
const client = await connect(server);
144+
await scoped(client).call('build-meta');
145+
expect(client.cacheManager.has('pangular:build-meta', [])).toBe(true);
146+
147+
const dropped = new Promise<void>((resolve) =>
148+
client.events.on('connection:status', (status) => {
149+
if (status !== 'connected') resolve();
150+
}),
151+
);
152+
await server.close();
153+
await dropped;
154+
// devframe clears the cache when the connection status changes.
155+
expect(client.cacheManager.has('pangular:build-meta', [])).toBe(false);
156+
157+
writeFileSync(join(cwd, 'package.json'), JSON.stringify({ name: 'renamed-demo' }));
158+
const after = new Map<string, number>();
159+
const next = await connect(await start(after));
160+
const meta = (await scoped(next).call('build-meta')) as { projectName: string };
161+
expect(meta.projectName).toBe('renamed-demo');
162+
expect(after.get('build-meta')).toBe(1);
163+
});
164+
});

‎packages/devtools/src/config.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,17 @@ export const SHARED_RPC: readonly string[] = [
992992
'axe-result',
993993
];
994994

995+
/**
996+
* Server RPC functions the panel's devframe client caches (its `cacheOptions`),
997+
* so a repeat call is answered without a round trip. Only functions whose
998+
* answer can't change while the server runs belong here, each one `static` or
999+
* marked `cacheable: true`. Live page data and source scans never do: they
1000+
* change as the app runs and as files are edited. devframe drops the cache
1001+
* when the connection drops, and the panel connects a new client then, so a
1002+
* restarted server is asked again.
1003+
*/
1004+
export const PANEL_CACHED_RPC: readonly string[] = ['pangular:build-meta'];
1005+
9951006
/**
9961007
* The inspector each server RPC function belongs to. A function missing here
9971008
* is shared and always registered.

0 commit comments

Comments
 (0)