@player-devtools/profiler-plugin 1.0.1-next.0 → 1.0.1-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import { Flow, InProgressState, Player } from "@player-ui/player";
2
- import { describe, expect, test, vi } from "vitest";
2
+ import { SyncHook } from "tapable-ts";
3
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
3
4
  import { ProfilerDevtoolsPlugin } from "../plugin";
4
5
 
5
6
  let count = 2490.0;
@@ -166,3 +167,146 @@ describe("Plugin", () => {
166
167
  await playerPromise;
167
168
  });
168
169
  });
170
+
171
+ /**
172
+ * Publishing the profiler tree is expensive: every publish clones and re-merges the whole recorded
173
+ * tree, and the tree only grows. Publishing after every hook therefore makes total work quadratic
174
+ * in the number of hooks (minutes of main-thread time on iOS, where JavaScriptCore has no JIT).
175
+ * Recording is cheap, so these tests pin down when we publish instead.
176
+ */
177
+ describe("snapshot publishing", () => {
178
+ const PLUGIN = "player-ui-profiler-plugin";
179
+
180
+ beforeEach(() => {
181
+ vi.useFakeTimers();
182
+ });
183
+
184
+ afterEach(() => {
185
+ vi.useRealTimers();
186
+ });
187
+
188
+ const createPlugin = () =>
189
+ new ProfilerDevtoolsPlugin({
190
+ handler: {
191
+ checkIfDevtoolsIsActive: () => true,
192
+ processInteraction: () => {},
193
+ },
194
+ playerID: "ID",
195
+ });
196
+
197
+ const setup = (plugin = createPlugin()) => {
198
+ const hook = new SyncHook<[]>();
199
+ plugin.apply({ hooks: { tick: hook } } as unknown as Player);
200
+
201
+ return {
202
+ hook,
203
+ plugin,
204
+ /** How many data-change snapshots have been published so far */
205
+ dataChanges: () =>
206
+ plugin.store
207
+ .getState()
208
+ .messages.filter(
209
+ (m) => m.type === "PLAYER_DEVTOOLS_PLUGIN_DATA_CHANGE",
210
+ ).length,
211
+ /** The top-level profiler nodes devtools can currently see */
212
+ publishedRootNodes: () =>
213
+ plugin.store.getState().plugins[PLUGIN]?.flow.data?.rawNodes as
214
+ | unknown[]
215
+ | undefined,
216
+ };
217
+ };
218
+
219
+ const interact = (plugin: ProfilerDevtoolsPlugin, type: string) =>
220
+ plugin.processInteraction({
221
+ payload: { type },
222
+ type: "PLAYER_DEVTOOLS_PLUGIN_INTERACTION",
223
+ });
224
+
225
+ test("does not publish a snapshot for every hook call", () => {
226
+ const { hook, dataChanges } = setup();
227
+ const before = dataChanges();
228
+
229
+ for (let i = 0; i < 500; i++) hook.call();
230
+
231
+ expect(dataChanges() - before).toBeLessThanOrEqual(1);
232
+ });
233
+
234
+ test("publishes everything that was recorded once the interval has passed", () => {
235
+ const { hook, publishedRootNodes } = setup();
236
+
237
+ for (let i = 0; i < 500; i++) hook.call();
238
+ vi.advanceTimersByTime(1_000);
239
+
240
+ expect(publishedRootNodes()).toHaveLength(500);
241
+ });
242
+
243
+ test("backs off after a slow publish", () => {
244
+ const plugin = createPlugin();
245
+ // Make every store update "cost" 500ms of wall-clock time, like publishing a huge tree.
246
+ plugin.store.subscribe(() => {
247
+ vi.setSystemTime(Date.now() + 500);
248
+ });
249
+ const { hook, dataChanges } = setup(plugin);
250
+ const before = dataChanges();
251
+
252
+ hook.call();
253
+ vi.advanceTimersByTime(2_000);
254
+ // The last publish was slow, so the next one has to wait much longer than that.
255
+ expect(dataChanges()).toBe(before);
256
+
257
+ vi.advanceTimersByTime(10_000);
258
+ expect(dataChanges()).toBe(before + 1);
259
+ });
260
+
261
+ /** Let devtools see a non-empty tree, then record more hooks that are still waiting to publish. */
262
+ const publishThenRecordMore = (hook: SyncHook<[]>) => {
263
+ for (let i = 0; i < 50; i++) hook.call();
264
+ vi.advanceTimersByTime(1_000);
265
+ for (let i = 0; i < 50; i++) hook.call();
266
+ };
267
+
268
+ test("start-profiling publishes the reset tree immediately, even while throttled", () => {
269
+ const { plugin, hook, publishedRootNodes } = setup();
270
+ publishThenRecordMore(hook);
271
+ // Sanity: devtools currently shows a tree, so an empty one is a real change
272
+ expect(publishedRootNodes()!.length).toBeGreaterThan(0);
273
+
274
+ interact(plugin, "start-profiling");
275
+
276
+ expect(publishedRootNodes()).toHaveLength(0);
277
+ });
278
+
279
+ test("reset-profiling publishes the cleared tree immediately, even while throttled", () => {
280
+ const { plugin, hook, publishedRootNodes } = setup();
281
+ publishThenRecordMore(hook);
282
+ // Sanity: devtools currently shows a tree, so an empty one is a real change
283
+ expect(publishedRootNodes()!.length).toBeGreaterThan(0);
284
+
285
+ interact(plugin, "reset-profiling");
286
+
287
+ expect(publishedRootNodes()).toHaveLength(0);
288
+ });
289
+
290
+ test("stop-profiling publishes the complete tree and cancels the pending publish", () => {
291
+ const { plugin, hook, dataChanges, publishedRootNodes } = setup();
292
+ for (let i = 0; i < 100; i++) hook.call();
293
+
294
+ interact(plugin, "stop-profiling");
295
+
296
+ expect(publishedRootNodes()).toHaveLength(100);
297
+ const afterStop = dataChanges();
298
+ vi.advanceTimersByTime(10_000);
299
+ expect(dataChanges()).toBe(afterStop);
300
+ });
301
+
302
+ test("teardown cancels a pending publish", () => {
303
+ const { plugin, hook, dataChanges } = setup();
304
+ hook.call();
305
+
306
+ plugin.teardown();
307
+ const afterTeardown = dataChanges();
308
+ vi.advanceTimersByTime(10_000);
309
+
310
+ expect(dataChanges()).toBe(afterTeardown);
311
+ });
312
+ });
@@ -279,4 +279,53 @@ describe("Profiler", () => {
279
279
  expect(rootNodes).toHaveLength(2);
280
280
  expect(rootNodes[0]!.children).toHaveLength(1);
281
281
  });
282
+
283
+ describe("maxRootNodes", () => {
284
+ test("drops the oldest finished root nodes beyond the limit", () => {
285
+ const p = new Profiler(undefined, { maxRootNodes: 3 });
286
+ p.start();
287
+
288
+ for (const name of ["a", "b", "c", "d", "e"]) {
289
+ p.startTimer(name);
290
+ p.endTimer({ hookName: name });
291
+ }
292
+
293
+ const { rootNodes } = p.stopProfiler();
294
+ expect(rootNodes.map((n) => n.name)).toEqual(["c", "d", "e"]);
295
+ });
296
+
297
+ test("never drops a root node that is still in progress", () => {
298
+ const p = new Profiler(undefined, { maxRootNodes: 1 });
299
+ p.start();
300
+
301
+ p.startTimer("finished");
302
+ p.endTimer({ hookName: "finished" });
303
+ p.startTimer("in-progress");
304
+ p.startTimer("child");
305
+ p.endTimer({ hookName: "child" });
306
+
307
+ const { rootNodes } = p.stopProfiler();
308
+ expect(rootNodes.map((n) => n.name)).toEqual(["in-progress"]);
309
+
310
+ // It can still finish normally after older roots were dropped
311
+ p.endTimer({ hookName: "in-progress" });
312
+ expect(p.stopProfiler().rootNodes[0]!.endTime).toBeDefined();
313
+ });
314
+
315
+ test("keeps everything when the limit is not reached", () => {
316
+ const p = new Profiler(undefined, { maxRootNodes: 10 });
317
+ p.start();
318
+
319
+ for (const name of ["a", "b", "c"]) {
320
+ p.startTimer(name);
321
+ p.endTimer({ hookName: name });
322
+ }
323
+
324
+ expect(p.stopProfiler().rootNodes.map((n) => n.name)).toEqual([
325
+ "a",
326
+ "b",
327
+ "c",
328
+ ]);
329
+ });
330
+ });
282
331
  });
@@ -1,11 +1,39 @@
1
1
  import type { ProfilerNode } from "../types";
2
2
  import { getNowTime } from "@player-devtools/plugin";
3
3
 
4
+ export interface ProfilerOptions {
5
+ /**
6
+ * Upper bound on the number of top-level nodes that are kept. Once it is exceeded the oldest
7
+ * finished top-level nodes are dropped, so a profiler that is never stopped can't grow forever.
8
+ * A node that is still in progress is never dropped. Unbounded when not set.
9
+ */
10
+ maxRootNodes?: number;
11
+ }
12
+
4
13
  export class Profiler {
5
14
  private rootNodes: ProfilerNode[] = [];
6
15
  private stack: ProfilerNode[] = [];
7
16
 
8
- constructor(private readonly onUpdate?: () => void) {}
17
+ constructor(
18
+ private readonly onUpdate?: () => void,
19
+ private readonly options: ProfilerOptions = {},
20
+ ) {}
21
+
22
+ /** Drop the oldest finished top-level nodes until we are back within `maxRootNodes`. */
23
+ private trimRootNodes(): void {
24
+ const { maxRootNodes } = this.options;
25
+ if (maxRootNodes === undefined) return;
26
+
27
+ const excess = this.rootNodes.length - maxRootNodes;
28
+ let drop = 0;
29
+ while (drop < excess && this.rootNodes[drop]!.endTime !== undefined) {
30
+ drop++;
31
+ }
32
+
33
+ if (drop > 0) {
34
+ this.rootNodes.splice(0, drop);
35
+ }
36
+ }
9
37
 
10
38
  start(): void {
11
39
  this.rootNodes = [];
@@ -65,6 +93,7 @@ export class Profiler {
65
93
  this.stack[this.stack.length - 1]!.children.push(node);
66
94
  } else {
67
95
  this.rootNodes.push(node);
96
+ this.trimRootNodes();
68
97
  }
69
98
 
70
99
  this.stack.push(node);
package/src/plugin.ts CHANGED
@@ -12,7 +12,9 @@ import {
12
12
  INTERACTIONS,
13
13
  ProfilerPluginData,
14
14
  } from "@player-devtools/profiler-plugin-content";
15
- import { dset } from "dset/merge";
15
+ // Not `dset/merge`: merging arrays by index never shrinks them, which leaves stale nodes behind
16
+ // whenever a shorter tree replaces a longer one (reset, restart, dropped root nodes).
17
+ import { dset } from "dset";
16
18
  import { produce } from "immer";
17
19
  import { Profiler, transformProfilerData } from "./helpers";
18
20
  import type { ProfilerNode } from "./types";
@@ -48,11 +50,42 @@ const pluginData = ProfilerPluginData;
48
50
 
49
51
  const pluginID = pluginData.id;
50
52
 
53
+ /**
54
+ * Publishing the tree to devtools clones and re-merges all of it, so a publish costs time
55
+ * proportional to everything recorded so far. Recording itself is cheap. Publishing after every
56
+ * hook made the total work quadratic: minutes of main-thread time on iOS, where JavaScriptCore
57
+ * runs without a JIT. So recording happens on every hook, but publishing is rate limited:
58
+ */
59
+
60
+ /** Never publish more often than this (ms), however many hooks fire. */
61
+ const MIN_PUBLISH_INTERVAL_MS = 250;
62
+
63
+ /**
64
+ * After a publish, wait at least this many times as long as it took before publishing again.
65
+ * Publishing then uses at most ~1/(1 + factor) of the main thread, however big the tree gets.
66
+ */
67
+ const PUBLISH_BACKOFF_FACTOR = 10;
68
+
69
+ /** How many top-level nodes to keep, so a profiler that is never stopped can't grow forever. */
70
+ const MAX_ROOT_NODES = 1000;
71
+
51
72
  export class ProfilerDevtoolsPlugin extends DevtoolsPlugin {
52
73
  name = "ProfilerDevtoolsPlugin";
53
74
 
54
75
  private readonly profilerObj: Profiler;
55
76
 
77
+ /** The profiler tree changed since the last publish */
78
+ private publishPending = false;
79
+
80
+ /** True while a publish is running, to ignore updates that it triggers itself */
81
+ private publishing = false;
82
+
83
+ /** Earliest time (Date.now) at which the next publish may run */
84
+ private nextPublishAt = 0;
85
+
86
+ /** Trailing publish for updates that arrived while we were waiting */
87
+ private publishTimer: ReturnType<typeof setTimeout> | undefined;
88
+
56
89
  private readonly interactionMap: Map<string, () => void> = new Map([
57
90
  [INTERACTIONS.START_PROFILING, () => this.startProfiler()],
58
91
  [INTERACTIONS.STOP_PROFILING, () => this.stopProfiler()],
@@ -65,25 +98,81 @@ export class ProfilerDevtoolsPlugin extends DevtoolsPlugin {
65
98
  pluginData,
66
99
  });
67
100
 
68
- this.profilerObj = new Profiler(() => {
69
- const { rootNodes } = this.profilerObj.getSnapshot();
70
- const newState = this.produceState(
71
- [
72
- ["plugins", pluginID, "flow", "data", "rootNode"],
73
- transformProfilerData(wrapInRoot(rootNodes)),
74
- ],
75
- [["plugins", pluginID, "flow", "data", "rawNodes"], rootNodes],
76
- );
77
- this.store.dispatch(
78
- genDataChangeTransaction({
79
- playerID: this.playerID,
80
- data: newState.plugins[pluginID]?.flow.data,
81
- pluginID,
82
- }),
83
- );
101
+ this.profilerObj = new Profiler(() => this.requestPublish(), {
102
+ maxRootNodes: MAX_ROOT_NODES,
84
103
  });
85
104
  }
86
105
 
106
+ /** Clone the recorded tree and send it to devtools. Cost grows with the size of the tree. */
107
+ private publishSnapshot(): void {
108
+ const { rootNodes } = this.profilerObj.getSnapshot();
109
+ const newState = this.produceState(
110
+ [
111
+ ["plugins", pluginID, "flow", "data", "rootNode"],
112
+ transformProfilerData(wrapInRoot(rootNodes)),
113
+ ],
114
+ [["plugins", pluginID, "flow", "data", "rawNodes"], rootNodes],
115
+ );
116
+ this.store.dispatch(
117
+ genDataChangeTransaction({
118
+ playerID: this.playerID,
119
+ data: newState.plugins[pluginID]?.flow.data,
120
+ pluginID,
121
+ }),
122
+ );
123
+ }
124
+
125
+ /**
126
+ * The recorded tree changed. Publish it now if we are allowed to, otherwise make sure a single
127
+ * trailing publish happens once we are, so the latest state is never left unpublished.
128
+ */
129
+ private requestPublish(): void {
130
+ this.publishPending = true;
131
+
132
+ if (this.publishing || this.publishTimer !== undefined) return;
133
+
134
+ const wait = this.nextPublishAt - Date.now();
135
+ if (wait <= 0) {
136
+ this.flushPublish();
137
+ } else if (typeof setTimeout === "function") {
138
+ this.publishTimer = setTimeout(() => {
139
+ this.publishTimer = undefined;
140
+ this.flushPublish();
141
+ }, wait);
142
+ }
143
+ }
144
+
145
+ /** Publish now if anything changed since the last publish, and set when the next one may run. */
146
+ private flushPublish(): void {
147
+ if (!this.publishPending || this.publishing) return;
148
+
149
+ this.cancelScheduledPublish();
150
+ this.publishPending = false;
151
+ this.publishing = true;
152
+
153
+ const start = Date.now();
154
+ try {
155
+ this.publishSnapshot();
156
+ } finally {
157
+ this.publishing = false;
158
+ }
159
+ const end = Date.now();
160
+
161
+ this.nextPublishAt =
162
+ end +
163
+ Math.max(MIN_PUBLISH_INTERVAL_MS, PUBLISH_BACKOFF_FACTOR * (end - start));
164
+
165
+ // Something changed while we were publishing
166
+ if (this.publishPending) this.requestPublish();
167
+ }
168
+
169
+ private cancelScheduledPublish(): void {
170
+ if (this.publishTimer !== undefined) {
171
+ clearTimeout(this.publishTimer);
172
+ this.publishTimer = undefined;
173
+ }
174
+ }
175
+
87
176
  /**
88
177
  * Produces a new store state with each `[path, value]` pair written into the
89
178
  * draft via `dset`, leaving the live store untouched.
@@ -100,6 +189,8 @@ export class ProfilerDevtoolsPlugin extends DevtoolsPlugin {
100
189
 
101
190
  private startProfiler(): void {
102
191
  this.profilerObj.start();
192
+ // Explicit user action: show the reset tree now rather than when the rate limit allows
193
+ this.flushPublish();
103
194
  const newState = produce(this.store.getState(), (draft) => {
104
195
  dset(draft, ["plugins", pluginID, "flow", "data", "profiling"], true);
105
196
  dset(
@@ -119,6 +210,8 @@ export class ProfilerDevtoolsPlugin extends DevtoolsPlugin {
119
210
 
120
211
  private clearProfiler(): void {
121
212
  this.profilerObj.clear();
213
+ // Explicit user action: show the cleared tree now rather than when the rate limit allows
214
+ this.flushPublish();
122
215
  }
123
216
 
124
217
  private stopProfiler(): ReturnType<Profiler["stopProfiler"]> {
@@ -140,6 +233,9 @@ export class ProfilerDevtoolsPlugin extends DevtoolsPlugin {
140
233
  pluginID,
141
234
  }),
142
235
  );
236
+ // This publish already contains everything that was recorded, so nothing is left pending
237
+ this.publishPending = false;
238
+ this.cancelScheduledPublish();
143
239
  return result;
144
240
  }
145
241
 
@@ -182,4 +278,9 @@ export class ProfilerDevtoolsPlugin extends DevtoolsPlugin {
182
278
 
183
279
  this.interactionMap.get(type)?.();
184
280
  }
281
+
282
+ teardown(): void {
283
+ this.cancelScheduledPublish();
284
+ super.teardown();
285
+ }
185
286
  }
@@ -1,9 +1,20 @@
1
1
  import type { ProfilerNode } from "../types";
2
+ export interface ProfilerOptions {
3
+ /**
4
+ * Upper bound on the number of top-level nodes that are kept. Once it is exceeded the oldest
5
+ * finished top-level nodes are dropped, so a profiler that is never stopped can't grow forever.
6
+ * A node that is still in progress is never dropped. Unbounded when not set.
7
+ */
8
+ maxRootNodes?: number;
9
+ }
2
10
  export declare class Profiler {
3
11
  private readonly onUpdate?;
12
+ private readonly options;
4
13
  private rootNodes;
5
14
  private stack;
6
- constructor(onUpdate?: (() => void) | undefined);
15
+ constructor(onUpdate?: (() => void) | undefined, options?: ProfilerOptions);
16
+ /** Drop the oldest finished top-level nodes until we are back within `maxRootNodes`. */
17
+ private trimRootNodes;
7
18
  start(): void;
8
19
  clear(): void;
9
20
  private cloneNode;
package/types/plugin.d.ts CHANGED
@@ -4,8 +4,26 @@ import type { Player } from "@player-ui/player";
4
4
  export declare class ProfilerDevtoolsPlugin extends DevtoolsPlugin {
5
5
  name: string;
6
6
  private readonly profilerObj;
7
+ /** The profiler tree changed since the last publish */
8
+ private publishPending;
9
+ /** True while a publish is running, to ignore updates that it triggers itself */
10
+ private publishing;
11
+ /** Earliest time (Date.now) at which the next publish may run */
12
+ private nextPublishAt;
13
+ /** Trailing publish for updates that arrived while we were waiting */
14
+ private publishTimer;
7
15
  private readonly interactionMap;
8
16
  constructor(options: Omit<DevtoolsPluginOptions, "pluginData">);
17
+ /** Clone the recorded tree and send it to devtools. Cost grows with the size of the tree. */
18
+ private publishSnapshot;
19
+ /**
20
+ * The recorded tree changed. Publish it now if we are allowed to, otherwise make sure a single
21
+ * trailing publish happens once we are, so the latest state is never left unpublished.
22
+ */
23
+ private requestPublish;
24
+ /** Publish now if anything changed since the last publish, and set when the next one may run. */
25
+ private flushPublish;
26
+ private cancelScheduledPublish;
9
27
  /**
10
28
  * Produces a new store state with each `[path, value]` pair written into the
11
29
  * draft via `dset`, leaving the live store untouched.
@@ -16,5 +34,6 @@ export declare class ProfilerDevtoolsPlugin extends DevtoolsPlugin {
16
34
  private stopProfiler;
17
35
  apply(player: Player): void;
18
36
  processInteraction(interaction: DevtoolsPluginInteractionEvent): void;
37
+ teardown(): void;
19
38
  }
20
39
  //# sourceMappingURL=plugin.d.ts.map