@parca/profile 0.19.25 → 0.19.26

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.
@@ -0,0 +1,89 @@
1
+ // Copyright 2022 The Parca Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+
14
+ import {useCallback, useEffect, useRef, useState} from 'react';
15
+
16
+ export interface ViewportState {
17
+ scrollTop: number;
18
+ scrollLeft: number;
19
+ containerHeight: number;
20
+ containerWidth: number;
21
+ }
22
+
23
+ export const useScrollViewport = (containerRef: React.RefObject<HTMLDivElement>): ViewportState => {
24
+ const [viewport, setViewport] = useState<ViewportState>({
25
+ scrollTop: 0,
26
+ scrollLeft: 0,
27
+ containerHeight: 0,
28
+ containerWidth: 0,
29
+ });
30
+
31
+ const throttleRef = useRef<number | null>(null);
32
+
33
+ const updateViewport = useCallback(() => {
34
+ if (containerRef.current !== null) {
35
+ const container = containerRef.current;
36
+
37
+ const newViewport = {
38
+ scrollTop: container.scrollTop,
39
+ scrollLeft: container.scrollLeft,
40
+ containerHeight: container.clientHeight,
41
+ containerWidth: container.clientWidth,
42
+ };
43
+
44
+ setViewport(newViewport);
45
+ }
46
+ }, [containerRef]);
47
+
48
+ // Throttling Strategy:
49
+ // Use requestAnimationFrame to throttle scroll events to 60fps max
50
+ // This ensures smooth performance while preventing excessive re-renders
51
+ const throttledUpdateViewport = useCallback(() => {
52
+ if (throttleRef.current !== null) {
53
+ cancelAnimationFrame(throttleRef.current);
54
+ }
55
+ throttleRef.current = requestAnimationFrame(updateViewport);
56
+ }, [updateViewport]);
57
+
58
+ useEffect(() => {
59
+ const container = containerRef.current;
60
+ if (container === null) return;
61
+
62
+ // ResizeObserver Strategy:
63
+ // Monitor container size changes (window resize, layout shifts)
64
+ // to update viewport dimensions for accurate culling calculations
65
+ const resizeObserver = new ResizeObserver(() => {
66
+ throttledUpdateViewport();
67
+ });
68
+
69
+ // Container Scroll Event Strategy:
70
+ // Use passive event listeners for better scroll performance
71
+ // Throttle with requestAnimationFrame to maintain 60fps target
72
+ container.addEventListener('scroll', throttledUpdateViewport, {passive: true});
73
+ resizeObserver.observe(container);
74
+
75
+ // Initialize viewport state on mount
76
+ updateViewport();
77
+
78
+ return () => {
79
+ // Cleanup: Remove event listeners and cancel pending animations
80
+ container.removeEventListener('scroll', throttledUpdateViewport);
81
+ resizeObserver.disconnect();
82
+ if (throttleRef.current !== null) {
83
+ cancelAnimationFrame(throttleRef.current);
84
+ }
85
+ };
86
+ }, [containerRef, throttledUpdateViewport, updateViewport]);
87
+
88
+ return viewport;
89
+ };
@@ -0,0 +1,167 @@
1
+ // Copyright 2022 The Parca Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+
14
+ import {useMemo, useRef} from 'react';
15
+
16
+ import {Table} from 'apache-arrow';
17
+
18
+ import {RowHeight} from './FlameGraphNodes';
19
+ import {FIELD_CUMULATIVE, FIELD_DEPTH, FIELD_VALUE_OFFSET} from './index';
20
+ import {ViewportState} from './useScrollViewport';
21
+ import {getMaxDepth} from './utils';
22
+
23
+ /**
24
+ * This function groups rows by their depth level.
25
+ * Instead of scanning all rows to find depth matches, we pre-compute
26
+ * buckets so viewport rendering only examines depth ranges that are relevant.
27
+ */
28
+ const useDepthBuckets = <TRow extends Record<string, any>>(
29
+ table: Table<TRow> | undefined
30
+ ): number[][] => {
31
+ return useMemo(() => {
32
+ if (table === undefined) return [];
33
+
34
+ const depthColumn = table.getChild(FIELD_DEPTH);
35
+ if (depthColumn === null) return [];
36
+
37
+ // Find max depth
38
+ const maxDepth = getMaxDepth(depthColumn);
39
+
40
+ // Create buckets for each depth level
41
+ const buckets: number[][] = Array.from({length: maxDepth + 1}, () => []);
42
+
43
+ // Populate buckets with row indices
44
+ for (let row = 0; row < table.numRows; row++) {
45
+ const depth = depthColumn.get(row) ?? 0;
46
+ buckets[depth].push(row);
47
+ }
48
+
49
+ return buckets;
50
+ }, [table]);
51
+ };
52
+
53
+ export interface UseVisibleNodesParams {
54
+ table: Table<any>;
55
+ viewport: ViewportState;
56
+ total: bigint;
57
+ width: number;
58
+ selectedRow: number;
59
+ effectiveDepth: number;
60
+ }
61
+
62
+ /**
63
+ * useVisibleNodes returns row indices visible in the current viewport through multi-stage culling.
64
+ * Combines depth buckets, horizontal bounds checking, and size filtering to
65
+ * minimize rendered nodes from potentially 100K+ rows to ~hundreds.
66
+ *
67
+ * We use depth buckets to only iterate through the rows that are visible in the viewport vertically.
68
+ * After that we use horizontal bounds checking to only iterate through the rows that are visible in the viewport horizontally.
69
+ * Finally we use size filtering to only iterate through the rows that are visible in the viewport by size.
70
+ *
71
+ * Critical for maintaining 60fps performance on large flamegraphs where
72
+ * rendering all nodes would freeze the browser.
73
+ */
74
+ export const useVisibleNodes = ({
75
+ table,
76
+ viewport,
77
+ total,
78
+ width,
79
+ selectedRow,
80
+ effectiveDepth,
81
+ }: UseVisibleNodesParams): number[] => {
82
+ const depthBuckets = useDepthBuckets(table);
83
+ const lastResultRef = useRef<{
84
+ key: string;
85
+ result: number[];
86
+ }>({key: '', result: []});
87
+
88
+ return useMemo(() => {
89
+ // Create a stable key for memoization to prevent unnecessary recalculations
90
+ const memoKey = `${viewport.scrollTop}-${viewport.containerHeight}-${selectedRow}-${effectiveDepth}-${width}`;
91
+
92
+ // Return cached result if viewport hasn't meaningfully changed
93
+ if (lastResultRef.current.key === memoKey) {
94
+ return lastResultRef.current.result;
95
+ }
96
+
97
+ if (table === null || viewport.containerHeight === 0) return [];
98
+
99
+ const visibleRows: number[] = [];
100
+ const {scrollTop, containerHeight} = viewport;
101
+
102
+ // Viewport Culling Algorithm:
103
+ // 1. Calculate visible depth range based on scroll position and container height
104
+ // 2. Add 5-row buffer above/below for smooth scrolling experience
105
+ const startDepth = Math.max(0, Math.floor(scrollTop / RowHeight) - 5);
106
+ const endDepth = Math.min(
107
+ effectiveDepth,
108
+ Math.ceil((scrollTop + containerHeight) / RowHeight) + 5
109
+ );
110
+
111
+ const cumulativeColumn = table.getChild(FIELD_CUMULATIVE);
112
+ const valueOffsetColumn = table.getChild(FIELD_VALUE_OFFSET);
113
+
114
+ const selectionOffset =
115
+ valueOffsetColumn?.get(selectedRow) !== null &&
116
+ valueOffsetColumn?.get(selectedRow) !== undefined
117
+ ? BigInt(valueOffsetColumn?.get(selectedRow))
118
+ : 0n;
119
+ const selectionCumulative =
120
+ cumulativeColumn?.get(selectedRow) !== null ? BigInt(cumulativeColumn?.get(selectedRow)) : 0n;
121
+
122
+ const totalNumber = Number(total);
123
+ const selectionOffsetNumber = Number(selectionOffset);
124
+ const selectionCumulativeNumber = Number(selectionCumulative);
125
+
126
+ // Iterate only through visible depth range instead of all rows
127
+ for (let depth = startDepth; depth <= endDepth && depth < depthBuckets.length; depth++) {
128
+ // Skip if depth is beyond effective depth limit
129
+ if (effectiveDepth !== undefined && depth > effectiveDepth) {
130
+ continue;
131
+ }
132
+
133
+ const rowsAtDepth = depthBuckets[depth];
134
+
135
+ for (const row of rowsAtDepth) {
136
+ const cumulative =
137
+ cumulativeColumn?.get(row) !== null ? Number(cumulativeColumn?.get(row)) : 0;
138
+
139
+ const valueOffset =
140
+ valueOffsetColumn?.get(row) !== null && valueOffsetColumn?.get(row) !== undefined
141
+ ? Number(valueOffsetColumn?.get(row))
142
+ : 0;
143
+
144
+ // Horizontal culling: Skip nodes outside selection bounds
145
+ if (
146
+ valueOffset + cumulative <= selectionOffsetNumber ||
147
+ valueOffset >= selectionOffsetNumber + selectionCumulativeNumber
148
+ ) {
149
+ continue;
150
+ }
151
+
152
+ // Size culling: Skip nodes too small to be visible (< 1px width)
153
+ const computedWidth = (cumulative / totalNumber) * width;
154
+ if (computedWidth <= 1) {
155
+ continue;
156
+ }
157
+
158
+ visibleRows.push(row);
159
+ }
160
+ }
161
+
162
+ // Cache the result with the current key
163
+ lastResultRef.current = {key: memoKey, result: visibleRows};
164
+
165
+ return visibleRows;
166
+ }, [depthBuckets, viewport, total, width, selectedRow, effectiveDepth, table]);
167
+ };
@@ -11,7 +11,7 @@
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
13
 
14
- import {Table} from 'apache-arrow';
14
+ import {Table, Vector} from 'apache-arrow';
15
15
 
16
16
  import {
17
17
  BINARY_FEATURE_TYPES,
@@ -203,3 +203,14 @@ export function isCurrentPathFrameMatch(
203
203
  a.labels === b.labels
204
204
  );
205
205
  }
206
+
207
+ export function getMaxDepth(depthColumn: Vector<any> | null): number {
208
+ if (depthColumn === null) return 0;
209
+
210
+ let max = 0;
211
+ for (const val of depthColumn) {
212
+ const numVal = Number(val);
213
+ if (numVal > max) max = numVal;
214
+ }
215
+ return max;
216
+ }