Skip to content

Commit 19c292d

Browse files
perf(fetchium): key each entity proxy into two WeakMaps instead of three (#91)
* perf(fetchium): key each entity proxy into one WeakMap instead of three Every entity proxy was registered in PROXY_ID (its key), in snapshotSources (its trap-free read record) and, through setScopeOwner, in Signalium's owner map. Hermes walks every WeakMap entry slot on each young GC and keeps those lists at their peak size, so each proxy cost three slots for the session. Store the key on the snapshot-source record and keep that record in PROXY_ID, and register the scope owner on the first reactive method access, the only path that resolves a scope through the proxy. * fix(fetchium): register entity scope owners eagerly `reactiveMethod(entity, fn)` defined outside the entity class resolves its scope owner by the proxy's identity when called, so no trap can register it lazily. Without a class method access first, it threw "Object has no scope owner". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(fetchium): type PROXY_ID with the snapshot-source record Drops the `snapshotSources` cast alias. With one map, a proxy missing from it is never in it, so the hot-reload fallback no longer checks `PROXY_ID`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9872e7d commit 19c292d

8 files changed

Lines changed: 99 additions & 23 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'fetchium': patch
3+
---
4+
5+
Key each entity proxy into two `WeakMap`s instead of three. The proxy's id now lives in its snapshot-source record.

‎packages/fetchium/src/EntityInstance.ts‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,9 @@ class OwnedObjectHandler implements ProxyHandler<Record<string, unknown>> {
172172
// ======================================================
173173

174174
/** Trap-free access to one entity proxy's fields. */
175-
interface EntitySnapshotSource {
175+
export interface EntitySnapshotSource {
176+
/** The entity key `PROXY_ID` brands the proxy with. */
177+
readonly key: number;
176178
/** Identifies this proxy without retaining it. */
177179
readonly id: number;
178180
readonly instance: EntityInstance;
@@ -183,8 +185,6 @@ interface EntitySnapshotSource {
183185
readField(key: string): unknown;
184186
}
185187

186-
const snapshotSources = new WeakMap<object, EntitySnapshotSource>();
187-
188188
let nextSnapshotSourceId = 1;
189189

190190
/** Holds the source id, not the proxy, so a snapshot never retains the entity graph. */
@@ -247,7 +247,7 @@ function snapshotRawValue(value: unknown, prev: unknown, snap: SnapshotFn): unkn
247247
for (let i = 0; i < value.length; i++) {
248248
const item = value[i];
249249
let prevItem = prevArr !== undefined ? prevArr[i] : undefined;
250-
const itemSource = item !== null && typeof item === 'object' ? snapshotSources.get(item) : undefined;
250+
const itemSource = item !== null && typeof item === 'object' ? PROXY_ID.get(item) : undefined;
251251
if (prevArr !== undefined && itemSource !== undefined) {
252252
if (prevBySource !== undefined) {
253253
prevItem = prevBySource.get(itemSource.id);
@@ -353,7 +353,7 @@ function walkFields(
353353
}
354354
}
355355

356-
/** For proxies from a previous instance of this module (hot reload), absent from `snapshotSources`. */
356+
/** For proxies from a previous instance of this module (hot reload), absent from `PROXY_ID`. */
357357
function snapshotProxyByWalking(current: object, prev: unknown, snap: SnapshotFn): unknown {
358358
const obj = current as Record<string, unknown>;
359359
const keys = Object.keys(obj);
@@ -371,10 +371,10 @@ function snapshotProxyByWalking(current: object, prev: unknown, snap: SnapshotFn
371371
}
372372

373373
const snapshotEntity = (current: object, prev: unknown, snap: SnapshotFn): unknown => {
374-
const source = snapshotSources.get(current);
374+
const source = PROXY_ID.get(current);
375375
if (source === undefined) {
376376
// Hot-reloaded proxy. Returning it as-is would stop React re-rendering on its changes.
377-
if (PROXY_ID.has(current) || typeof (current as { toJSON?: unknown }).toJSON === 'function') {
377+
if (typeof (current as { toJSON?: unknown }).toJSON === 'function') {
378378
return snapshotProxyByWalking(current, prev, snap);
379379
}
380380
// A bare `Entity` has no fields to read, only the shape's type defs.
@@ -800,7 +800,7 @@ function filterEntityArray(
800800
const excluded: EntityInstance[] = [];
801801
for (const item of array) {
802802
if (typeof item !== 'object' || item === null) continue;
803-
const entityKey = PROXY_ID.get(item);
803+
const entityKey = PROXY_ID.get(item)?.key;
804804
if (entityKey === undefined) continue;
805805
const entityInstance = queryClient.entityMap.getEntity(entityKey);
806806
if (entityInstance === undefined) continue;
@@ -1154,15 +1154,16 @@ function createProxy(
11541154

11551155
proxy = new Proxy<Record<string, unknown>>({} as Record<string, unknown>, handler);
11561156

1157-
PROXY_ID.set(proxy, key);
1158-
snapshotSources.set(proxy, {
1157+
PROXY_ID.set(proxy, {
1158+
key,
11591159
id: nextSnapshotSourceId++,
11601160
instance,
11611161
notifier: entityNotifier,
11621162
relay: entityRelay,
11631163
keys: entityKeys,
11641164
readField,
11651165
});
1166+
// Eager: `reactiveMethod(proxy, fn)` outside the class looks the owner up by identity, which no trap sees.
11661167
setScopeOwner(proxy, queryClient);
11671168

11681169
return proxy;

‎packages/fetchium/src/QueryClient.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,7 @@ export class QueryClient {
723723
const result = applyEntityRefs(parseResult.ctx, parseResult.data, persist, appendMode);
724724

725725
// Discover the root entity from the returned proxy
726-
const proxyKey = PROXY_ID.get(result.data as object);
726+
const proxyKey = PROXY_ID.get(result.data as object)?.key;
727727
return this.entityMap.getEntity(proxyKey!)!;
728728
}
729729

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { describe, it, expect, vi } from 'vitest';
2+
import { reactiveMethod } from 'signalium';
3+
import { t } from '../typeDefs.js';
4+
import { Entity } from '../proxy.js';
5+
import { getProxyId } from '../proxyId.js';
6+
import { RESTQuery } from '../rest/index.js';
7+
import { fetchQuery } from '../query.js';
8+
import { testWithClient, setupTestClient } from './utils.js';
9+
10+
describe('Entity proxy registry', () => {
11+
const getClient = setupTestClient();
12+
13+
// Hermes walks every WeakMap entry on each young GC. The second map is Signalium's scope owner.
14+
it('keys each entity proxy into two WeakMaps', async () => {
15+
const { client, mockFetch } = getClient();
16+
class User extends Entity {
17+
__typename = t.typename('User');
18+
id = t.id;
19+
name = t.string;
20+
greet() {
21+
return `Hello, ${this.name}!`;
22+
}
23+
}
24+
mockFetch.get('/users', {
25+
users: Array.from({ length: 5 }, (_, id) => ({ __typename: 'User', id, name: `user-${id}` })),
26+
});
27+
28+
const set = vi.spyOn(WeakMap.prototype, 'set');
29+
try {
30+
await testWithClient(client, async () => {
31+
class GetUsers extends RESTQuery {
32+
path = '/users';
33+
result = { users: t.array(t.entity(User)) };
34+
}
35+
const relay = fetchQuery(GetUsers);
36+
await relay;
37+
expect(relay.value!.users.map(user => user.name)).toEqual(['user-0', 'user-1', 'user-2', 'user-3', 'user-4']);
38+
});
39+
const mapsByProxy = new Map<WeakKey, Set<unknown>>();
40+
set.mock.calls.forEach(([key], i) => {
41+
if (getProxyId(key as Record<string, unknown>) === undefined) return;
42+
if (!mapsByProxy.has(key)) mapsByProxy.set(key, new Set());
43+
mapsByProxy.get(key)!.add(set.mock.contexts[i]);
44+
});
45+
expect(mapsByProxy.size).toBeGreaterThan(5);
46+
for (const maps of mapsByProxy.values()) expect(maps.size).toBe(2);
47+
} finally {
48+
set.mockRestore();
49+
}
50+
});
51+
52+
it('owns the scope of a reactive method defined outside the entity class', async () => {
53+
const { client, mockFetch } = getClient();
54+
class Item extends Entity {
55+
__typename = t.typename('Item');
56+
id = t.id;
57+
name = t.string;
58+
}
59+
mockFetch.get('/item', { item: { __typename: 'Item', id: 1, name: 'one' } });
60+
61+
await testWithClient(client, async () => {
62+
class GetItem extends RESTQuery {
63+
path = '/item';
64+
result = { item: t.entity(Item) };
65+
}
66+
const { item } = await fetchQuery(GetItem);
67+
const getName = reactiveMethod(item, () => item.name);
68+
expect(getName()).toBe('one');
69+
});
70+
});
71+
});

‎packages/fetchium/src/__tests__/same-value.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import { describe, it, expect } from 'vitest';
22
import { sameValue, sameRefs, sameKeys } from '../applyEntities.js';
33
import { FormattedValue } from '../typeDefs.js';
44
import { PROXY_ID } from '../proxyId.js';
5-
import type { EntityInstance } from '../EntityInstance.js';
5+
import type { EntityInstance, EntitySnapshotSource } from '../EntityInstance.js';
66

77
// A wrong `true` drops an update, so anything uncertain must compare unequal.
88

99
const proxyLike = (key: number) => {
1010
const obj = {};
11-
PROXY_ID.set(obj, key);
11+
// `sameValue` only checks membership, so the record is never read.
12+
PROXY_ID.set(obj, { key } as EntitySnapshotSource);
1213
return obj;
1314
};
1415

‎packages/fetchium/src/applyEntities.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ function applyEntity(
197197
if (!Array.isArray(raw)) continue;
198198
for (const item of raw) {
199199
if (typeof item !== 'object' || item === null) continue;
200-
const itemKey = PROXY_ID.get(item as object);
200+
const itemKey = PROXY_ID.get(item as object)?.key;
201201
if (itemKey === undefined) continue;
202202
const child = queryClient.entityMap.getEntity(itemKey);
203203
if (child !== undefined) {

‎packages/fetchium/src/parseEntities.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -726,7 +726,7 @@ function valueSatisfiesDef(value: unknown, fieldDef: unknown, queryClient: Query
726726
if (itemDef === undefined || typeof itemDef === 'number') return true;
727727
return arraySatisfies(value, itemDef, queryClient, visiting);
728728
}
729-
const entityKey = PROXY_ID.get(value as object);
729+
const entityKey = PROXY_ID.get(value as object)?.key;
730730
const typename =
731731
entityKey !== undefined
732732
? queryClient.entityMap.getEntity(entityKey)?.typename
@@ -779,7 +779,7 @@ function entitySatisfies(
779779
queryClient: QueryClient,
780780
visiting: TrustMemo,
781781
): boolean {
782-
const entityKey = PROXY_ID.get(value);
782+
const entityKey = PROXY_ID.get(value)?.key;
783783
if (entityKey === undefined) return false;
784784
const child = queryClient.entityMap.getEntity(entityKey);
785785
if (child === undefined) return true;

‎packages/fetchium/src/proxyId.ts‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
/**
2-
* WeakMap that brands entity proxies with their numeric key.
3-
* Shared between EntityInstance (writes) and proxy.ts (reads for
4-
* parseObjectValue / mergeValues identity checks).
5-
*/
6-
export const PROXY_ID = new WeakMap<object, number>();
1+
import type { EntitySnapshotSource } from './EntityInstance.js';
2+
3+
/** Each entity proxy's snapshot source, which carries its entity key, so a proxy costs one entry here. */
4+
export const PROXY_ID = new WeakMap<object, EntitySnapshotSource>();
75

86
export function getProxyId(object: Record<string, unknown>): number | undefined {
9-
return PROXY_ID.get(object);
7+
return PROXY_ID.get(object)?.key;
108
}

0 commit comments

Comments
 (0)