diff --git a/.changeset/javascript-exception-stack-frames.md b/.changeset/javascript-exception-stack-frames.md new file mode 100644 index 0000000000..48d845b143 --- /dev/null +++ b/.changeset/javascript-exception-stack-frames.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': patch +--- + +feat: Exception panel parses JavaScript stack traces from OpenTelemetry SDKs into frames, with a section per `Caused by:` error diff --git a/packages/app/src/components/DBRowOverviewPanel.tsx b/packages/app/src/components/DBRowOverviewPanel.tsx index 6f7602a2f3..ebad17c2e9 100644 --- a/packages/app/src/components/DBRowOverviewPanel.tsx +++ b/packages/app/src/components/DBRowOverviewPanel.tsx @@ -7,6 +7,10 @@ import { Accordion, Box, Flex, Text } from '@mantine/core'; import { WithClause } from '@/hooks/useRowWhere'; import { getEventBody } from '@/source'; import { getHighlightedAttributesFromData } from '@/utils/highlightedAttributes'; +import { + isJavaScriptRuntime, + parseJavaScriptException, +} from '@/utils/javascriptStack'; import { resolveRowTimestampAnchor } from '@/utils/rowTimestamps'; import { getRequestPanelTitle } from '@/utils/rpcSpanAttributes'; import { isSet } from '@/utils/spanAttributeReaders'; @@ -175,18 +179,36 @@ export function RowOverviewPanel({ // do nothing } + const exception = { + stacktrace: parsedStacktrace, + type: parsedEvents?.['exception.type'], + value: + typeof parsedEvents?.['exception.message'] !== 'string' + ? JSON.stringify(parsedEvents?.['exception.message']) + : parsedEvents?.['exception.message'], + mechanism: parsedEvents?.['exception.mechanism'], + }; + + const parsed = + typeof parsedStacktrace === 'string' && + isJavaScriptRuntime(resourceAttributes) + ? parseJavaScriptException(parsedStacktrace) + : undefined; + if (parsed == null) { + return [exception]; + } return [ { - stacktrace: parsedStacktrace, - type: parsedEvents?.['exception.type'], - value: - typeof parsedEvents?.['exception.message'] !== 'string' - ? JSON.stringify(parsedEvents?.['exception.message']) - : parsedEvents?.['exception.message'], - mechanism: parsedEvents?.['exception.mechanism'], + ...exception, + stacktrace: { frames: parsed.frames }, + rawStacktrace: parsedStacktrace, }, + ...parsed.causes.map(({ frames, ...cause }) => ({ + ...cause, + stacktrace: { frames }, + })), ]; - }, [exceptionAttributes]); + }, [exceptionAttributes, resourceAttributes]); const hasException = exceptionAttributes != null; diff --git a/packages/app/src/components/ExceptionSubpanel.tsx b/packages/app/src/components/ExceptionSubpanel.tsx index 54bb41f13b..add6b41e25 100644 --- a/packages/app/src/components/ExceptionSubpanel.tsx +++ b/packages/app/src/components/ExceptionSubpanel.tsx @@ -3,7 +3,7 @@ import React, { useMemo } from 'react'; import cx from 'classnames'; import { ErrorBoundary } from 'react-error-boundary'; import { Badge } from '@clickhouse/click-ui'; -import { Button, Text, Tooltip } from '@mantine/core'; +import { Button, Text, Tooltip, UnstyledButton } from '@mantine/core'; import { Group, Loader } from '@mantine/core'; import { IconChevronDown, @@ -13,12 +13,14 @@ import { } from '@tabler/icons-react'; import { ColumnDef, Row, Table as TanstackTable } from '@tanstack/react-table'; +import { CopySnippet } from '@/components/ClickStackOnboarding/CopySnippet'; import type { StacktraceBreadcrumb, StacktraceFrame as TStacktraceFrame, } from '@/types'; import { FormatTime } from '@/useFormatTime'; import { useSourceMappedFrame } from '@/useSourceMappedFrame'; +import { UNKNOWN_FUNCTION } from '@/utils/sentryStackParser'; import { Table, TableCellButton } from './Table'; @@ -66,8 +68,8 @@ const StacktraceFrame = ({ }: { filename: string; function?: string; - lineno: number; - colno: number; + lineno?: number; + colno?: number; isLoading?: boolean; }) => { return ( @@ -80,21 +82,26 @@ const StacktraceFrame = ({ }} > {filename} - - :{lineno}:{colno} - - {' in '} - {functionName && ( - - {functionName} + {lineno != null && ( + + :{lineno} + {colno != null && `:${colno}`} )} + {functionName && functionName !== UNKNOWN_FUNCTION && ( + <> + {' in '} + + {functionName} + + + )} {isLoading && } @@ -180,6 +187,8 @@ const StacktraceRowExpandButton = ({ ); }; +const NOT_IN_APP_LABEL = 'Library or framework code'; + const StacktraceRow = ({ row, table, @@ -218,12 +227,16 @@ const StacktraceRow = ({
{!augmentedFrame.in_app && ( - + )} {augmentedFrame && ( @@ -267,7 +280,7 @@ const StacktraceRow = ({ {augmentedFrame.post_context?.map((line, i) => (
- {augmentedFrame.lineno + i + 1} + {(augmentedFrame.lineno ?? 0) + i + 1} {line}
@@ -420,9 +433,9 @@ export const useShowMoreRows = ({ return { visibleRows, hiddenRowsCount, handleToggleMoreRows, isExpanded }; }; -type ExceptionValues = { +type ExceptionValue = { type: string; - value: string; + value?: string; mechanism?: { type: string; handled: boolean; @@ -433,10 +446,226 @@ type ExceptionValues = { target?: string; }; }; - stacktrace?: { - frames: TStacktraceFrame[]; - }; -}[]; + /** A string when the stack text could not be parsed into frames. */ + stacktrace?: { frames: TStacktraceFrame[] } | string; + /** The unparsed stack text, set when `stacktrace` was parsed from it. */ + rawStacktrace?: string; +}; + +const getFrames = ({ stacktrace }: ExceptionValue) => + typeof stacktrace === 'string' ? undefined : stacktrace?.frames; + +const getExceptionTitle = ({ type, value }: ExceptionValue) => + [type, value?.trim()].filter(Boolean).join(': '); + +const ExceptionTitle = ({ + exception, + isCause, + singleLine, +}: { + exception: ExceptionValue; + isCause: boolean; + singleLine: boolean; +}) => { + const message = exception.value?.trim() ?? ''; + + return ( + + {isCause && Caused by: } + {exception.type && ( + + {exception.type} + + )} + + {exception.type && message && ': '} + {singleLine ? message.replace(/\s+/g, ' ') : message} + + + ); +}; + +const ExceptionStacktrace = ({ exception }: { exception: ExceptionValue }) => { + const stacktraceFrames = useMemo( + () => getFrames(exception)?.slice().reverse() ?? [], + [exception], + ); + + const firstFrameIndex = useMemo(() => { + const firstFrame = getFirstFrame(stacktraceFrames); + return firstFrame ? stacktraceFrames.indexOf(firstFrame) : -1; + }, [stacktraceFrames]); + + const { + handleToggleMoreRows: handleStacktraceToggleMoreRows, + hiddenRowsCount: stacktraceHiddenRowsCount, + visibleRows: stacktraceVisibleRows, + isExpanded: stacktraceExpanded, + } = useShowMoreRows({ + rows: stacktraceFrames, + maxRows: Math.max(5, firstFrameIndex + 1), + }); + + return ( + <> + { + console.error(err); + }} + fallbackRender={() => ( +
+ An error occurred while rendering stacktrace +
+ )} + > + + + + {stacktraceHiddenRowsCount ? ( + + ) : null} + + ); +}; + +const ExceptionValueSection = ({ + exception, + isCause, +}: { + exception: ExceptionValue; + isCause: boolean; +}) => { + const hasFrames = !!getFrames(exception)?.length; + + const unparsedStack = + !isCause && typeof exception.stacktrace === 'string' + ? exception.stacktrace + : ''; + + const collapsible = isCause && hasFrames; + const [expanded, setExpanded] = React.useState(!isCause); + const open = expanded || !collapsible; + const Chevron = expanded ? IconChevronDown : IconChevronRight; + + return ( + + {collapsible ? ( + setExpanded(!expanded)} + > + + + + ) : ( +
+ +
+ )} + + {open && exception.mechanism && ( +
+ + true + ) : ( + false + ) + } + /> + + {exception.mechanism?.data?.function ? ( + + ) : null} + {exception.mechanism?.data?.handler ? ( + + ) : null} + {exception.mechanism?.data?.target ? ( + + ) : null} +
+ )} + + } + > + {open && hasFrames && } + {unparsedStack ? ( +
+          {unparsedStack}
+        
+ ) : null} +
+ ); +}; export const ExceptionSubpanel = ({ logData, @@ -445,29 +674,21 @@ export const ExceptionSubpanel = ({ }: { logData?: any; breadcrumbs?: StacktraceBreadcrumb[]; - exceptionValues: ExceptionValues; + /** The thrown error first, then each error in its `cause` chain. */ + exceptionValues: ExceptionValue[]; }) => { const firstException = exceptionValues[0]; const shouldShowSourceMapFtux = useMemo(() => { - return firstException?.stacktrace?.frames?.some( - f => - f.filename.startsWith('http://') || f.filename.startsWith('https://'), + return ( + firstException && + getFrames(firstException)?.some( + f => + f.filename.startsWith('http://') || f.filename.startsWith('https://'), + ) ); - }, [firstException?.stacktrace?.frames]); - - const stacktraceFrames = useMemo(() => { - if (!firstException?.stacktrace?.frames) { - return []; - } - return firstException?.stacktrace.frames.slice().reverse(); }, [firstException]); - const firstFrameIndex = useMemo(() => { - const firstFrame = getFirstFrame(stacktraceFrames); - return firstFrame ? stacktraceFrames.indexOf(firstFrame) : -1; - }, [stacktraceFrames]); - const chronologicalBreadcrumbs = useMemo(() => { return [ ...(firstException && breadcrumbs @@ -475,9 +696,7 @@ export const ExceptionSubpanel = ({ { category: 'exception', timestamp: new Date(logData?.timestamp ?? 0).getTime() / 1000, - message: [firstException.type, firstException.value] - .filter(Boolean) - .join(': '), + message: getExceptionTitle(firstException), }, ] : []), @@ -485,16 +704,6 @@ export const ExceptionSubpanel = ({ ]; }, [breadcrumbs, firstException, logData?.timestamp]); - const { - handleToggleMoreRows: handleStacktraceToggleMoreRows, - hiddenRowsCount: stacktraceHiddenRowsCount, - visibleRows: stacktraceVisibleRows, - isExpanded: stacktraceExpanded, - } = useShowMoreRows({ - rows: stacktraceFrames, - maxRows: Math.max(5, firstFrameIndex + 1), - }); - const { handleToggleMoreRows: handleBreadcrumbToggleMoreRows, hiddenRowsCount: breadcrumbHiddenRowsCount, @@ -504,118 +713,20 @@ export const ExceptionSubpanel = ({ rows: chronologicalBreadcrumbs, }); - // TODO: show all frames (stackable) return (
- -
- {firstException.type && ( - - {firstException.type} - - )} - - {firstException.type && firstException.value && ': '} - {firstException.value} - -
- - {firstException.mechanism && ( -
- - true - ) : ( - false - ) - } - /> - - {firstException.mechanism?.data?.function ? ( - - ) : null} - {firstException.mechanism?.data?.handler ? ( - - ) : null} - {firstException.mechanism?.data?.target ? ( - - ) : null} -
- )} - {/* {shouldShowSourceMapFtux && } */} - - ) - } - > - { - console.error(err); - }} - fallbackRender={() => ( -
- An error occurred while rendering stacktrace -
- )} - > -
- - - {typeof exceptionValues[0].stacktrace === 'string' && ( -
-            {exceptionValues[0].stacktrace}
-          
- )} + {exceptionValues.map((exception, i) => ( + 0} /> + ))} + {/* {shouldShowSourceMapFtux && } */} - {stacktraceHiddenRowsCount ? ( - - ) : null} - + {firstException?.rawStacktrace && ( + + + + + + )} {breadcrumbVisibleRows.length > 0 && ( diff --git a/packages/app/src/components/__tests__/DBRowOverviewPanel.exception.test.tsx b/packages/app/src/components/__tests__/DBRowOverviewPanel.exception.test.tsx index adcb5ecc2a..117addb116 100644 --- a/packages/app/src/components/__tests__/DBRowOverviewPanel.exception.test.tsx +++ b/packages/app/src/components/__tests__/DBRowOverviewPanel.exception.test.tsx @@ -34,8 +34,38 @@ function renderRow(row: Record) { renderWithMantine(); } -const exceptionShown = () => - mockExceptionSubpanel.mock.calls[0]?.[0].exceptionValues[0]; +const exceptionValuesShown = () => + mockExceptionSubpanel.mock.calls[0]?.[0].exceptionValues; +const exceptionShown = () => exceptionValuesShown()[0]; + +const CHROME_STACK = [ + 'Error: Checkout failed', + ' at checkout (https://example.clickhouse.com/assets/app.js:120:11)', + 'Caused by: TypeError: Failed to fetch', + ' at fetchCart (https://example.clickhouse.com/assets/app.js:42:9)', +].join('\n'); + +const JAVA_STACK = [ + 'java.lang.IllegalStateException: Checkout failed', + '\tat com.example.Checkout.run(Checkout.java:120)', + 'Caused by: java.io.IOException: Failed to fetch', + '\tat com.example.Cart.fetch(Cart.java:42)', +].join('\n'); + +const exceptionRow = ( + language: string | undefined, + stacktrace: string, + key = 'exception.stacktrace', +) => ({ + ...(language != null && { + __hdx_resource_attributes: { 'telemetry.sdk.language': language }, + }), + __hdx_event_attributes: { + 'exception.type': 'Error', + 'exception.message': 'Checkout failed', + [key]: stacktrace, + }, +}); describe('RowOverviewPanel exception section', () => { beforeEach(() => jest.clearAllMocks()); @@ -76,6 +106,103 @@ describe('RowOverviewPanel exception section', () => { expect(exceptionShown()).toMatchObject({ type: 'FromEvent' }); }); + it('parses a JavaScript stack into frames and Caused by sections', () => { + renderRow(exceptionRow('webjs', CHROME_STACK)); + + expect(exceptionValuesShown()).toEqual([ + { + type: 'Error', + value: 'Checkout failed', + mechanism: undefined, + rawStacktrace: CHROME_STACK, + stacktrace: { + frames: [ + { + filename: 'https://example.clickhouse.com/assets/app.js', + function: 'checkout', + lineno: 120, + colno: 11, + in_app: true, + }, + ], + }, + }, + { + type: 'TypeError', + value: 'Failed to fetch', + stacktrace: { + frames: [ + { + filename: 'https://example.clickhouse.com/assets/app.js', + function: 'fetchCart', + lineno: 42, + colno: 9, + in_app: true, + }, + ], + }, + }, + ]); + }); + + it('parses a Node.js exception span event', () => { + renderRow({ + __hdx_resource_attributes: { 'telemetry.sdk.language': 'nodejs' }, + __hdx_events_exception_attributes: { + 'exception.type': 'Error', + 'exception.stacktrace': + 'Error: boom\n at handler (/srv/app/dist/server.js:12:9)', + }, + }); + + expect(exceptionShown().stacktrace.frames).toEqual([ + expect.objectContaining({ function: 'handler', lineno: 12, colno: 9 }), + ]); + }); + + it.each([ + ['a java row with a Java stack', 'java', JAVA_STACK], + ['a python row', 'python', CHROME_STACK], + ['a row without resource attributes', undefined, CHROME_STACK], + ['a webjs row without frames', 'webjs', 'Error: Checkout failed'], + ])('keeps the raw text for %s', (_, language, stacktrace) => { + renderRow(exceptionRow(language, stacktrace)); + + expect(exceptionValuesShown()).toHaveLength(1); + expect(exceptionShown().stacktrace).toBe(stacktrace); + expect(exceptionShown().rawStacktrace).toBeUndefined(); + }); + + it('keeps JSON parsed_stacktrace rows unchanged', () => { + const parsedStacktrace = { + frames: [ + { + filename: 'https://example.clickhouse.com/assets/app.js', + function: 'checkout', + lineno: 120, + colno: 11, + in_app: true, + }, + ], + }; + renderRow( + exceptionRow( + 'webjs', + JSON.stringify(parsedStacktrace), + 'exception.parsed_stacktrace', + ), + ); + + expect(exceptionValuesShown()).toEqual([ + { + type: 'Error', + value: 'Checkout failed', + mechanism: undefined, + stacktrace: parsedStacktrace, + }, + ]); + }); + it('hides the section without exception attributes', () => { renderRow({ __hdx_event_attributes: { 'http.request.method': 'GET' }, diff --git a/packages/app/src/components/__tests__/ExceptionSubpanel.test.tsx b/packages/app/src/components/__tests__/ExceptionSubpanel.test.tsx index 3b90aafde3..38d1c2f54b 100644 --- a/packages/app/src/components/__tests__/ExceptionSubpanel.test.tsx +++ b/packages/app/src/components/__tests__/ExceptionSubpanel.test.tsx @@ -1,5 +1,6 @@ import React from 'react'; -import { screen } from '@testing-library/react'; +import { screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { ExceptionSubpanel } from '@/components/ExceptionSubpanel'; @@ -76,3 +77,371 @@ describe('ExceptionSubpanel breadcrumbs', () => { expect(badgeStates()).toEqual([[level, state]]); }); }); + +const APP = 'https://example.clickhouse.com/assets/app.js'; +const FRAMEWORK = + 'https://example.clickhouse.com/_next/static/chunks/framework-2c79e2a64abdb08b.js'; +const RAW_STACK = [ + 'Error: Checkout failed', + ` at checkout (${APP}:120:11)`, + ` at Object.Ub (${FRAMEWORK}:9:16994)`, + 'Caused by: TypeError: Failed to fetch', + ` at fetchCart (${APP}:42:9)`, +].join('\n'); + +const PARSED_EXCEPTION_VALUES = [ + { + type: 'Error', + value: 'Checkout failed', + rawStacktrace: RAW_STACK, + stacktrace: { + frames: [ + { + filename: FRAMEWORK, + function: 'Object.Ub', + lineno: 9, + colno: 16994, + in_app: false, + }, + { + filename: APP, + function: 'checkout', + lineno: 120, + colno: 11, + in_app: true, + }, + ], + }, + }, + { + type: 'TypeError', + value: 'Failed to fetch', + stacktrace: { + frames: [ + { + filename: APP, + function: 'fetchCart', + lineno: 42, + colno: 9, + in_app: true, + }, + ], + }, + }, +]; + +const rowTexts = () => + screen.getAllByRole('row').map(row => row.textContent?.trim()); + +describe('ExceptionSubpanel stack frames', () => { + it('renders the thrown exception with its frames, newest first', () => { + renderWithMantine( + , + ); + + expect(rowTexts()).toEqual([ + `${APP}:120:11 in checkout`, + `${FRAMEWORK}:9:16994 in Object.Ub`, + ]); + expect( + screen + .getAllByLabelText('Library or framework code') + .map(icon => icon.closest('tr')?.textContent?.trim()), + ).toEqual([`${FRAMEWORK}:9:16994 in Object.Ub`]); + expect(screen.getByText('Error').closest('div')?.textContent).toBe( + 'Error: Checkout failed', + ); + expect(screen.getByText('Error').closest('button')).toBeNull(); + }); + + it('collapses each cause to its title until expanded', async () => { + renderWithMantine( + , + ); + const causes = () => + screen + .getAllByRole('button', { name: /^Caused by: / }) + .map(cause => [cause.textContent, cause.getAttribute('aria-expanded')]); + + expect(causes()).toEqual([ + ['Caused by: TypeError: Failed to fetch', 'false'], + ['Caused by: Error: Socket closed', 'false'], + ]); + expect(rowTexts()).toEqual([ + `${APP}:120:11 in checkout`, + `${FRAMEWORK}:9:16994 in Object.Ub`, + ]); + + await userEvent.click( + screen.getByRole('button', { name: /Failed to fetch/ }), + ); + + expect(causes()).toEqual([ + ['Caused by: TypeError: Failed to fetch', 'true'], + ['Caused by: Error: Socket closed', 'false'], + ]); + expect(rowTexts()).toEqual([ + `${APP}:120:11 in checkout`, + `${FRAMEWORK}:9:16994 in Object.Ub`, + `${APP}:42:9 in fetchCart`, + ]); + + await userEvent.click( + screen.getByRole('button', { name: /Failed to fetch/ }), + ); + + expect(rowTexts()).not.toContain(`${APP}:42:9 in fetchCart`); + }); + + it('renders a section without frames as its title alone', () => { + const { container } = renderWithMantine( + , + ); + + // A cause's unparsed text is not shown. Causes only come from a parsed + // stack, whose full text is in "Raw stack trace". + expect( + Array.from(container.querySelectorAll('.panelSectionWrapper'), section => + Array.from(section.children, child => child.textContent), + ), + ).toEqual([ + ['Error: Checkout failed'], + ['Caused by: TypeError: Failed to fetch'], + ['Caused by: Error: Socket closed'], + ]); + expect( + screen.queryByRole('button', { name: /Caused by:/ }), + ).not.toBeInTheDocument(); + }); + + it('keeps the mechanism of a section without frames', () => { + renderWithMantine( + , + ); + + expect(screen.getByText('onerror')).toBeInTheDocument(); + expect(screen.getByText('false')).toBeInTheDocument(); + }); + + it('does not render the frames of a collapsed cause', () => { + renderWithMantine( + , + ); + + // `hidden` also counts rows mounted but hidden by CSS, which would still + // run their source map lookups. + expect(screen.queryAllByRole('row', { hidden: true })).toHaveLength(0); + }); + + it('puts a collapsed cause on one line and its full message on hover', async () => { + renderWithMantine( + , + ); + const cause = screen.getByRole('button', { name: /^Caused by: / }); + const title = () => within(cause).getByText('Error').parentElement; + + expect(cause.textContent).toBe( + 'Caused by: Error: Row 12 is invalid: price must be a number', + ); + expect(title()).toHaveAttribute('data-truncate'); + expect(title()).toHaveAttribute( + 'title', + 'Error: Row 12 is invalid:\r\n price must be a number', + ); + + await userEvent.click(cause); + + expect(cause.textContent).toBe( + 'Caused by: Error: Row 12 is invalid:\r\n price must be a number', + ); + expect(title()).not.toHaveAttribute('data-truncate'); + expect(title()).not.toHaveAttribute('title'); + expect(title()?.style.whiteSpace).toBe('pre-wrap'); + }); + + it('shows the message of an open section with its line breaks', () => { + const longToken = `https://react.dev/errors/418?args[]=${'x'.repeat(400)}`; + renderWithMantine( + , + ); + const title = (type: string) => screen.getByText(type).parentElement; + + expect(screen.getByText('Error').closest('div')?.textContent).toBe( + 'Error: Checkout failed\nfor cart 42', + ); + expect(screen.getByText('TypeError').closest('div')?.textContent).toBe( + `Caused by: TypeError: Failed to fetch\n${longToken}`, + ); + for (const type of ['Error', 'TypeError']) { + expect(title(type)?.style.whiteSpace).toBe('pre-wrap'); + expect(title(type)?.style.overflowWrap).toBe('anywhere'); + expect(title(type)).not.toHaveAttribute('data-truncate'); + expect(title(type)).not.toHaveAttribute('data-line-clamp'); + } + }); + + it('keeps the raw stack trace behind a collapsed section', async () => { + renderWithMantine( + , + ); + const rawText = () => screen.queryByText(/Caused by: TypeError/); + + expect(rawText()).not.toBeInTheDocument(); + await userEvent.click(screen.getByText('Raw stack trace')); + expect(rawText()?.textContent).toBe(RAW_STACK); + }); + + it('omits the line and column of a frame that has none', () => { + renderWithMantine( + , + ); + + expect(rowTexts()).toEqual([ + `${APP}:37 in checkout`, + '[native code] in forEach', + ]); + }); + + it.each(['', '?'])( + 'omits "in" for a frame whose function is %p', + functionName => { + renderWithMantine( + , + ); + + expect(screen.getByRole('row').textContent).toBe(`${APP}:5:10`); + }, + ); + + it('shows an unparsed stack as text', () => { + renderWithMantine( + , + ); + + expect(screen.getByText(/Caused by: TypeError/).textContent).toBe( + RAW_STACK, + ); + expect(screen.queryByRole('row')).not.toBeInTheDocument(); + expect(screen.queryByText('Raw stack trace')).not.toBeInTheDocument(); + }); +}); diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index 9c549f77cc..f5387c1d30 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -58,8 +58,8 @@ export type StacktraceFrame = { filename: string; function: string; module?: string; - lineno: number; - colno: number; + lineno?: number; + colno?: number; in_app: boolean; context_line?: string; pre_context?: string[]; diff --git a/packages/app/src/utils/__tests__/javascriptStack.test.ts b/packages/app/src/utils/__tests__/javascriptStack.test.ts new file mode 100644 index 0000000000..3340ce5cf9 --- /dev/null +++ b/packages/app/src/utils/__tests__/javascriptStack.test.ts @@ -0,0 +1,441 @@ +import { + isJavaScriptRuntime, + parseJavaScriptException, +} from '@/utils/javascriptStack'; + +const APP = 'https://app.example.com/assets/app.js'; + +const framesOf = (stack: string) => parseJavaScriptException(stack)?.frames; + +describe('parseJavaScriptException', () => { + it('parses a Chrome stack oldest first, keeping URLs and 1-based columns', () => { + const stack = [ + "TypeError: Cannot read properties of undefined (reading 'id')", + ' at c (https://app.example.com/_next/static/chunks/pages/checkout-3f2a.js:1:2817)', + ' at Object.Ub (https://app.example.com/_next/static/chunks/framework-2c79e2a64abdb08b.js:9:16994)', + ` at ${APP}:5:10`, + ].join('\n'); + + expect(parseJavaScriptException(stack)).toEqual({ + frames: [ + { filename: APP, function: '?', lineno: 5, colno: 10, in_app: true }, + { + filename: + 'https://app.example.com/_next/static/chunks/framework-2c79e2a64abdb08b.js', + function: 'Object.Ub', + lineno: 9, + colno: 16994, + in_app: false, + }, + { + filename: + 'https://app.example.com/_next/static/chunks/pages/checkout-3f2a.js', + function: 'c', + lineno: 1, + colno: 2817, + in_app: true, + }, + ], + causes: [], + }); + }); + + it('parses Chrome eval and async frames', () => { + const stack = [ + 'Error: bad', + ' at eval (eval at aha (http://localhost:5000/app.js:37:5), :1:1)', + ` at async submit (${APP}:130:5)`, + ' at Object.callback (async http://localhost:5000/app.js:25:7)', + ].join('\n'); + + expect(framesOf(stack)).toEqual([ + { + filename: 'http://localhost:5000/app.js', + function: 'Object.callback', + lineno: 25, + colno: 7, + in_app: true, + }, + { + filename: APP, + function: 'async submit', + lineno: 130, + colno: 5, + in_app: true, + }, + { + filename: 'http://localhost:5000/app.js', + function: 'eval', + lineno: 37, + colno: 5, + in_app: true, + }, + ]); + }); + + it('parses a Node stack and marks library and runtime frames', () => { + const stack = [ + 'Error: boom', + ' at handler (/srv/app/dist/server.js:12:9)', + ' at Layer.handle (/srv/app/node_modules/express/lib/router/layer.js:95:5)', + ' at process.processTicksAndRejections (node:internal/process/task_queues:95:5)', + ' at async Promise.all (index 0)', + ].join('\n'); + + expect(framesOf(stack)).toEqual([ + { + filename: 'index 0', + function: 'async Promise.all', + in_app: false, + }, + { + filename: 'node:internal/process/task_queues', + function: 'process.processTicksAndRejections', + lineno: 95, + colno: 5, + in_app: false, + }, + { + filename: '/srv/app/node_modules/express/lib/router/layer.js', + function: 'Layer.handle', + lineno: 95, + colno: 5, + in_app: false, + }, + { + filename: '/srv/app/dist/server.js', + function: 'handler', + lineno: 12, + colno: 9, + in_app: true, + }, + ]); + }); + + it('parses a Firefox stack, including async and eval frames', () => { + const stack = [ + 'aha@http://localhost:5000/app.js line 37 > eval:1:1', + `checkout@${APP}:120:11`, + `async*submit@${APP}:130:5`, + `@${APP}:150:1`, + ].join('\n'); + + expect(framesOf(stack)).toEqual([ + { filename: APP, function: '?', lineno: 150, colno: 1, in_app: true }, + { + filename: APP, + function: 'async*submit', + lineno: 130, + colno: 5, + in_app: true, + }, + { + filename: APP, + function: 'checkout', + lineno: 120, + colno: 11, + in_app: true, + }, + { + filename: 'http://localhost:5000/app.js', + function: 'aha', + lineno: 37, + in_app: true, + }, + ]); + }); + + it('parses a Safari stack, dropping eval code frames', () => { + const stack = [ + 'forEach@[native code]', + `checkout@${APP}:120:11`, + 'eval code@', + `global code@${APP}:150:1`, + ].join('\n'); + + expect(framesOf(stack)).toEqual([ + { + filename: APP, + function: 'global code', + lineno: 150, + colno: 1, + in_app: true, + }, + { + filename: APP, + function: 'checkout', + lineno: 120, + colno: 11, + in_app: true, + }, + { filename: '[native code]', function: 'forEach', in_app: false }, + ]); + }); + + it('splits Chrome Caused by sections into causes with their own frames', () => { + const stack = [ + 'Error: Checkout failed', + ` at checkout (${APP}:120:11)`, + 'Caused by: TypeError: Failed to fetch', + ` at fetchCart (${APP}:42:9)`, + 'Caused by: Error', + ` at request (${APP}:10:3)`, + ].join('\n'); + + expect(parseJavaScriptException(stack)).toEqual({ + frames: [ + { + filename: APP, + function: 'checkout', + lineno: 120, + colno: 11, + in_app: true, + }, + ], + causes: [ + { + type: 'TypeError', + value: 'Failed to fetch', + frames: [ + { + filename: APP, + function: 'fetchCart', + lineno: 42, + colno: 9, + in_app: true, + }, + ], + }, + { + type: 'Error', + value: '', + frames: [ + { + filename: APP, + function: 'request', + lineno: 10, + colno: 3, + in_app: true, + }, + ], + }, + ], + }); + }); + + it('splits a Firefox stack whose cause has a Name: message line', () => { + const stack = [ + `checkout@${APP}:120:11`, + 'Caused by: TypeError: NetworkError when attempting to fetch resource.', + `fetchCart@${APP}:42:9`, + ].join('\n'); + + expect(parseJavaScriptException(stack)).toEqual({ + frames: [ + { + filename: APP, + function: 'checkout', + lineno: 120, + colno: 11, + in_app: true, + }, + ], + causes: [ + { + type: 'TypeError', + value: 'NetworkError when attempting to fetch resource.', + frames: [ + { + filename: APP, + function: 'fetchCart', + lineno: 42, + colno: 9, + in_app: true, + }, + ], + }, + ], + }); + }); + + it('titles a cause without a Name: prefix by its whole line', () => { + const stack = [ + ` at checkout (${APP}:120:11)`, + 'Caused by: request timed out after 30s', + ].join('\n'); + + expect(parseJavaScriptException(stack)?.causes).toEqual([ + { type: '', value: 'request timed out after 30s', frames: [] }, + ]); + }); + + it('does not read URLs in a multi-line message as frames', () => { + const stack = [ + 'Error: Checkout failed', + 'https://api.example.com/cart returned 500', + ` at checkout (${APP}:120:11)`, + 'Caused by: Error: Request failed', + 'https://api.example.com/cart/items returned 503', + ` at fetchCart (${APP}:42:9)`, + ].join('\n'); + + const parsed = parseJavaScriptException(stack); + + expect(parsed?.frames.map(frame => frame.function)).toEqual(['checkout']); + expect(parsed?.causes).toEqual([ + expect.objectContaining({ + type: 'Error', + value: + 'Request failed\nhttps://api.example.com/cart/items returned 503', + frames: [expect.objectContaining({ function: 'fetchCart' })], + }), + ]); + }); + + it('does not read URLs in a multi-line Firefox cause message as frames', () => { + const stack = [ + `checkout@${APP}:120:11`, + 'Caused by: GraphQLError: Validation failed:', + ' - field "email" is required', + ' - see https://docs.example.com/errors#validation', + `fetchCart@${APP}:42:9`, + ].join('\n'); + + expect(parseJavaScriptException(stack)?.causes).toEqual([ + { + type: 'GraphQLError', + value: [ + 'Validation failed:', + ' - field "email" is required', + ' - see https://docs.example.com/errors#validation', + ].join('\n'), + frames: [expect.objectContaining({ function: 'fetchCart' })], + }, + ]); + }); + + // V8 prints `new Error('\nRow 12 is invalid:')` as a line of `Error: ` + // followed by the message's lines. + it.each([ + [ + 'a message that starts with a line break', + ['Caused by: Error: ', 'Row 12 is invalid:', ' sku is required'], + { type: 'Error', value: 'Row 12 is invalid:\n sku is required' }, + ], + [ + 'a whitespace-only message', + ['Caused by: Error: ', ''], + { type: 'Error', value: '' }, + ], + [ + 'an empty Caused by line', + ['Caused by: ', 'TypeError: Failed to fetch'], + { type: 'TypeError', value: 'Failed to fetch' }, + ], + [ + 'a message without a Name: prefix', + ['Caused by: request timed out after 30s', ''], + { type: '', value: 'request timed out after 30s' }, + ], + ])('trims the blank lines around %s', (_, causeLines, title) => { + const stack = [ + ` at checkout (${APP}:120:11)`, + ...causeLines, + ` at fetchCart (${APP}:42:9)`, + ].join('\n'); + + expect(parseJavaScriptException(stack)?.causes).toEqual([ + { + ...title, + frames: [expect.objectContaining({ function: 'fetchCart' })], + }, + ]); + }); + + it('keeps a URL line of a frameless Firefox cause in its title', () => { + const stack = [ + `checkout@${APP}:1:2`, + 'Caused by: TypeError: bad', + 'see https://docs.example.com/x', + ].join('\n'); + + expect(parseJavaScriptException(stack)?.causes).toEqual([ + { + type: 'TypeError', + value: 'bad\nsee https://docs.example.com/x', + frames: [], + }, + ]); + }); + + it('skips lines with more than 32 parentheses', () => { + const stack = [ + `checkout@${APP}:120:11`, + `submit${'()'.repeat(17)}@${APP}:130:5`, + ].join('\n'); + + expect(framesOf(stack)).toEqual([ + expect.objectContaining({ function: 'checkout' }), + ]); + }); + + it.each([ + ['an error line alone', 'Error: x'], + [ + 'frameless toString() text with a URL', + 'HttpException: GET https://api.example.com/x failed\nCaused by: {"code":1}', + ], + [ + 'a stack over 64 KB', + `Error: x\n${` at fn (${APP}:1:2)\n`.repeat(2000)}`, + ], + ['empty text', ''], + ['a Caused by without frames', 'Error: x\nCaused by: Error: y'], + ])('returns undefined for %s', (_, stack) => { + expect(parseJavaScriptException(stack)).toBeUndefined(); + }); + + it.each([ + ['/srv/app/node_modules/react-dom/cjs/react-dom.js', false], + ['http://localhost:5173/node_modules/.vite/deps/react-dom.js', false], + ['node:internal/process/task_queues', false], + ['internal/modules/cjs/loader.js', false], + [ + 'https://app.example.com/_next/static/chunks/framework-2c79e2a64abdb08b.js', + false, + ], + [ + 'https://app.example.com/_next/static/chunks/webpack-59c5c889f52620d6.js', + false, + ], + ['https://app.example.com/_next/static/chunks/main-app-5f1c09ab.js', false], + ['webpack:///webpack/bootstrap', false], + ['https://app.example.com/static/js/runtime-main.4c1f2b9d.js', false], + ['https://app.example.com/webpack-runtime-8a2b3c.js', false], + [ + 'https://app.example.com/_next/static/chunks/pages/checkout-3f2a.js', + true, + ], + ['https://app.example.com/_next/static/chunks/main-feature.js', true], + ])('sets in_app for %s to %s', (filename, inApp) => { + expect(framesOf(`Error: x\n at fn (${filename}:1:2)`)).toEqual([ + expect.objectContaining({ filename, in_app: inApp }), + ]); + }); +}); + +describe('isJavaScriptRuntime', () => { + it.each([ + ['webjs', true], + ['nodejs', true], + ['java', false], + ['python', false], + [undefined, false], + ])('treats telemetry.sdk.language %s as %s', (language, expected) => { + expect( + isJavaScriptRuntime( + language == null ? {} : { 'telemetry.sdk.language': language }, + ), + ).toBe(expected); + }); +}); diff --git a/packages/app/src/utils/javascriptStack.ts b/packages/app/src/utils/javascriptStack.ts new file mode 100644 index 0000000000..be1d32ad68 --- /dev/null +++ b/packages/app/src/utils/javascriptStack.ts @@ -0,0 +1,124 @@ +import type { StacktraceFrame } from '@/types'; +import { defaultStackParser } from '@/utils/sentryStackParser'; +import type { Attributes } from '@/utils/spanAttributeReaders'; + +const JAVASCRIPT_SDK_LANGUAGES = new Set(['webjs', 'nodejs']); + +// Parsing runs during render on client-controlled text, and a crafted 1 KB line +// still costs the line parsers ~1.5 ms, so longer stacks are shown as text. +const MAX_PARSED_STACK_LENGTH = 64 * 1024; + +const CAUSED_BY_REGEX = /^\s*Caused by: /; +const V8_FRAME_REGEX = /^\s*at /; +const ERROR_TITLE_REGEX = /^([^\s:]+)(?:: ([\s\S]*))?$/; + +// Library, runtime and bundler frames. The old browser SDK deleted Next.js +// framework chunks outright; marking them keeps the frames, and the panel +// opens on the app's newest in-app frame instead of them. +const NOT_IN_APP_FILENAME_PATTERNS = [ + /node_modules/, + /^(node:|internal\/)/, + /\/framework-[0-9a-f]+\.js/, + /\/_next\/static\/chunks\/(main|main-app|webpack|polyfills)(-[0-9a-f]+)?\.js/, + /(^|\/)webpack\/(runtime|bootstrap)/, + /\/(webpack-runtime|runtime[~-]main)[^/]*\.js/, +]; + +type JavaScriptCause = { + type: string; + value: string; + frames: StacktraceFrame[]; +}; + +export type ParsedJavaScriptException = { + frames: StacktraceFrame[]; + causes: JavaScriptCause[]; +}; + +export function isJavaScriptRuntime(resourceAttributes: Attributes): boolean { + const language = resourceAttributes['telemetry.sdk.language']; + return typeof language === 'string' && JAVASCRIPT_SDK_LANGUAGES.has(language); +} + +// Frames without a line number are native, anonymous or `data:` URI frames: +// never app code, and nothing a source map can resolve. +function isInApp({ filename, lineno }: StacktraceFrame): boolean { + return ( + lineno !== undefined && + !NOT_IN_APP_FILENAME_PATTERNS.some(pattern => pattern.test(filename)) + ); +} + +// The `Name: message` header is every line before the first frame, and a +// multi-line message can contain URL lines the Gecko parser would read as +// frames. V8 frames start with `at `. Firefox and Safari frames always contain +// `@` (`fn@url:1:2`, `@url:1:2`, `fn@[native code]`); their main stack has no +// header, but `Caused by:` sections and frameless `toString()` text do. +function getHeaderLength(lines: string[]): number { + const v8FrameIndex = lines.findIndex(line => V8_FRAME_REGEX.test(line)); + if (v8FrameIndex !== -1) { + return v8FrameIndex; + } + const geckoFrameIndex = lines.findIndex(line => line.includes('@')); + return geckoFrameIndex === -1 ? lines.length : geckoFrameIndex; +} + +function parseSection(lines: string[]) { + const headerLength = getHeaderLength(lines); + const frames = defaultStackParser(lines.join('\n'), headerLength).map( + frame => ({ ...frame, in_app: isInApp(frame) }), + ); + return { header: lines.slice(0, headerLength), frames }; +} + +// The title is the `Caused by:` line joined with the header lines below it, so +// a message that starts with a line break (`Error: \nDetails`) would keep it +// and open with a blank line. Only the start is trimmed before matching: a +// whitespace-only message leaves `Error: `, whose space the regex needs. +function parseCauseTitle( + title: string, +): Pick { + const text = title.trimStart(); + const match = ERROR_TITLE_REGEX.exec(text); + return match + ? { type: match[1], value: (match[2] ?? '').trim() } + : { type: '', value: text.trimEnd() }; +} + +/** + * Parses an `Error.stack` string from a JavaScript SDK, which appends each + * error in the `cause` chain as a Java-style `Caused by: Name: message` + * section. Frames are oldest first. Returns undefined when no section has a + * frame or the text is too long to parse, so the caller can show it instead. + */ +export function parseJavaScriptException( + stack: string, +): ParsedJavaScriptException | undefined { + if (stack.length > MAX_PARSED_STACK_LENGTH) { + return undefined; + } + const sections: { title?: string; lines: string[] }[] = [{ lines: [] }]; + for (const line of stack.split('\n')) { + if (CAUSED_BY_REGEX.test(line)) { + sections.push({ title: line.replace(CAUSED_BY_REGEX, ''), lines: [] }); + } else { + sections[sections.length - 1].lines.push(line); + } + } + + const [main, ...causes] = sections.map(({ title, lines }) => ({ + title, + ...parseSection(lines), + })); + if (![main, ...causes].some(section => section.frames.length > 0)) { + return undefined; + } + + return { + frames: main.frames, + causes: causes.map(({ title, header, frames }) => ({ + ...parseCauseTitle([title, ...header].join('\n')), + frames, + })), + }; +} diff --git a/packages/app/src/utils/sentryStackParser.ts b/packages/app/src/utils/sentryStackParser.ts new file mode 100644 index 0000000000..37aad8ab04 --- /dev/null +++ b/packages/app/src/utils/sentryStackParser.ts @@ -0,0 +1,330 @@ +// Parses JavaScript `Error.stack` text into frames: Sentry's Chrome (V8) and +// Gecko (Firefox, Safari) line parsers and `createStackParser`, ported from +// sentry-javascript 11.10.0: +// https://github.com/getsentry/sentry-javascript/blob/11.10.0/packages/browser/src/stack-parsers.ts +// https://github.com/getsentry/sentry-javascript/blob/11.10.0/packages/core/src/utils/stacktrace.ts +// +// Changes from upstream: +// - Typed against HyperDX's `StacktraceFrame`, without upstream's `exec()` +// result casts. +// - Only the Chrome and Gecko line parsers (upstream's +// `defaultStackLineParsers`); WinJS and Opera are dropped. +// - `createStackParser` drops the unused `framesToPop` parameter. +// - The final reverse no longer strips `sentryWrapped` and +// `captureException`/`captureMessage` frames. Those target Sentry's own SDK +// and would drop an app's own `captureException` frame. +// - The `data:` URI frame sets `in_app` like every other frame. +// - `createStackParser` skips lines with more than 32 parentheses. +// +// MIT License +// +// Copyright (c) 2019 Functional Software, Inc. dba Sentry +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// The line parsers were originally forked from https://github.com/csnover/TraceKit, +// and were largely re-written as part of raven-js. Upstream's TraceKit notice: +// +// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of this +// software and associated documentation files(the 'Software'), to deal in the Software +// without restriction, including without limitation the rights to use, copy, modify, +// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be included in all copies +// or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import type { StacktraceFrame } from '@/types'; + +type StackLineParserFn = (line: string) => StacktraceFrame | undefined; +type StackLineParser = [priority: number, parse: StackLineParserFn]; + +const STACKTRACE_FRAME_LIMIT = 50; +const MAX_LINE_PARENTHESES = 32; +export const UNKNOWN_FUNCTION = '?'; +// Used to sanitize webpack (error: *) wrapped stack errors +const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/; + +const CHROME_PRIORITY = 30; +const GECKO_PRIORITY = 50; + +function createFrame( + filename: string, + func: string, + lineno?: number, + colno?: number, +): StacktraceFrame { + const frame: StacktraceFrame = { + filename, + function: func === '' ? UNKNOWN_FUNCTION : func, + in_app: true, // All browser frames are considered in_app + }; + + if (lineno !== undefined) { + frame.lineno = lineno; + } + + if (colno !== undefined) { + frame.colno = colno; + } + + return frame; +} + +// This regex matches frames that have no function name (ie. are at the top level of a module). +// For example "at http://localhost:5000//script.js:1:126" +// Frames _with_ function names usually look as follows: "at commitLayoutEffects (react-dom.development.js:23426:1)" +const chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i; + +// This regex matches all the frames that have a function name. +const chromeRegex = + /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; + +const chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/; + +// Matches stack frames with data URIs instead of filename so we can still get the function name +// Example: "at dynamicFn (data:application/javascript,export function dynamicFn() {..." +const chromeDataUriRegex = /at (.+?) ?\(data:(.+?),/; + +// Chromium based browsers: Chrome, Brave, new Opera, new Edge +const chromeStackParserFn: StackLineParserFn = line => { + const dataUriMatch = line.match(chromeDataUriRegex); + if (dataUriMatch) { + return { + filename: ``, + function: dataUriMatch[1], + in_app: true, + }; + } + + // If the stack line has no function name, we need to parse it differently + const noFnParts = chromeRegexNoFnName.exec(line); + + if (noFnParts) { + const [, filename, line, col] = noFnParts; + return createFrame(filename, UNKNOWN_FUNCTION, +line, +col); + } + + const parts = chromeRegex.exec(line); + + if (parts) { + const isEval = parts[2]?.indexOf('eval') === 0; // start of line + + if (isEval) { + const subMatch = chromeEvalRegex.exec(parts[2]); + + if (subMatch) { + // throw out eval line/column and use top-most line/column number + parts[2] = subMatch[1]; // url + parts[3] = subMatch[2]; // line + parts[4] = subMatch[3]; // column + } + } + + const [func, filename] = extractSafariExtensionDetails( + parts[1] || UNKNOWN_FUNCTION, + parts[2], + ); + + return createFrame( + filename, + func, + parts[3] ? +parts[3] : undefined, + parts[4] ? +parts[4] : undefined, + ); + } + + return; +}; + +const chromeStackLineParser: StackLineParser = [ + CHROME_PRIORITY, + chromeStackParserFn, +]; + +// gecko regex: `(?:bundle|\d+\.js)`: `bundle` is for react native, `\d+\.js` also but specifically for ram bundles because it +// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js +// We need this specific case for now because we want no other regex to match. +const geckoREgex = + /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i; +const geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; + +const gecko: StackLineParserFn = line => { + const parts = geckoREgex.exec(line); + + if (parts) { + const isEval = parts[3] && parts[3].indexOf(' > eval') > -1; + if (isEval) { + const subMatch = geckoEvalRegex.exec(parts[3]); + + if (subMatch) { + // throw out eval line/column and use top-most line number + parts[1] = parts[1] || 'eval'; + parts[3] = subMatch[1]; + parts[4] = subMatch[2]; + parts[5] = ''; // no column when eval + } + } + + let filename = parts[3]; + let func = parts[1] || UNKNOWN_FUNCTION; + [func, filename] = extractSafariExtensionDetails(func, filename); + + return createFrame( + filename, + func, + parts[4] ? +parts[4] : undefined, + parts[5] ? +parts[5] : undefined, + ); + } + + return; +}; + +const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko]; + +/** + * Safari web extensions, starting version unknown, can produce "frames-only" stacktraces. + * What it means, is that instead of format like: + * + * Error: wat + * at function@url:row:col + * at function@url:row:col + * at function@url:row:col + * + * it produces something like: + * + * function@url:row:col + * function@url:row:col + * function@url:row:col + * + * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch. + * This function is extracted so that we can use it in both places without duplicating the logic. + * Unfortunately "just" changing RegExp is too complicated now and making it pass all tests + * and fix this case seems like an impossible, or at least way too time-consuming task. + */ +const extractSafariExtensionDetails = ( + func: string, + filename: string, +): [string, string] => { + const isSafariExtension = func.indexOf('safari-extension') !== -1; + const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1; + + return isSafariExtension || isSafariWebExtension + ? [ + func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION, + isSafariExtension + ? `safari-extension:${filename}` + : `safari-web-extension:${filename}`, + ] + : [func, filename]; +}; + +function createStackParser(...parsers: StackLineParser[]) { + const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); + + return (stack: string, skipFirstLines: number = 0): StacktraceFrame[] => { + const frames: StacktraceFrame[] = []; + const lines = stack.split('\n'); + + for (let i = skipFirstLines; i < lines.length; i++) { + let line = lines[i]; + // Truncate lines over 1kb because many of the regular expressions use + // backtracking which results in run time that increases exponentially + // with input size. Huge strings can result in hangs/Denial of Service: + // https://github.com/getsentry/sentry-javascript/issues/2286 + if (line.length > 1024) { + line = line.slice(0, 1024); + } + + // Upstream parses the page's own `Error.stack`; this parses stored text + // anyone can send. The Gecko regex backtracks in proportion to the + // number of `(` times `)` in a line, which the 1 KB cut doesn't bound + // (~90 ms for one line). Real frames have a handful. + if (line.replace(/[^()]/g, '').length > MAX_LINE_PARENTHESES) { + continue; + } + + // https://github.com/getsentry/sentry-javascript/issues/5459 + // Remove webpack (error: *) wrappers + const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) + ? line.replace(WEBPACK_ERROR_REGEXP, '$1') + : line; + + // https://github.com/getsentry/sentry-javascript/issues/7813 + // Skip Error: lines + // Using includes() instead of a regex to avoid O(n²) backtracking on long lines + // https://github.com/getsentry/sentry-javascript/issues/20052 + if (cleanedLine.includes('Error: ')) { + continue; + } + + for (const parser of sortedParsers) { + const frame = parser(cleanedLine); + + if (frame) { + frames.push(frame); + break; + } + } + + if (frames.length >= STACKTRACE_FRAME_LIMIT) { + break; + } + } + + return reverseFrames(frames); + }; +} + +/** + * Enforces a limit of max number of frames. Assumes stack input is ordered + * from top to bottom and returns the reverse representation so call site of + * the function that caused the crash is the last frame in the array. + */ +function reverseFrames(stack: ReadonlyArray) { + if (!stack.length) { + return []; + } + + const localStack = Array.from(stack).reverse(); + const lastFrame = localStack[localStack.length - 1]; + + return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({ + ...frame, + filename: frame.filename || lastFrame.filename, + function: frame.function || UNKNOWN_FUNCTION, + })); +} + +/** Frames oldest first, every frame `in_app: true`, at most 50. */ +export const defaultStackParser = createStackParser( + chromeStackLineParser, + geckoStackLineParser, +); diff --git a/packages/app/styles/LogSidePanel.module.scss b/packages/app/styles/LogSidePanel.module.scss index 6a3e3d1c43..74c3c6f900 100644 --- a/packages/app/styles/LogSidePanel.module.scss +++ b/packages/app/styles/LogSidePanel.module.scss @@ -64,6 +64,10 @@ .panelSectionWrapperTitle { padding: 18px 24px; border-bottom: 1px solid var(--color-border); + + &:last-child { + border-bottom: none; + } } .kbdShortcuts {