index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. import {useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import keyBy from 'lodash/keyBy';
  5. import moment from 'moment';
  6. import Badge from 'sentry/components/badge';
  7. import {Button} from 'sentry/components/button';
  8. import ButtonBar from 'sentry/components/buttonBar';
  9. import TimeSince from 'sentry/components/timeSince';
  10. import Version from 'sentry/components/version';
  11. import VersionHoverCard from 'sentry/components/versionHoverCard';
  12. import {IconChevron} from 'sentry/icons';
  13. import {t} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import {Series} from 'sentry/types/echarts';
  16. import useOrganization from 'sentry/utils/useOrganization';
  17. import usePageFilters from 'sentry/utils/usePageFilters';
  18. import Chart from 'sentry/views/starfish/components/chart';
  19. import Detail from 'sentry/views/starfish/components/detailPanel';
  20. import {FormattedCode} from 'sentry/views/starfish/components/formattedCode';
  21. import {generateMarkLine} from 'sentry/views/starfish/components/sparkline';
  22. import ProfileView from 'sentry/views/starfish/modules/databaseModule/panel/profileView';
  23. import QueryTransactionTable, {
  24. PanelSort,
  25. } from 'sentry/views/starfish/modules/databaseModule/panel/queryTransactionTable';
  26. import SimilarQueryView from 'sentry/views/starfish/modules/databaseModule/panel/similarQueryView';
  27. import {
  28. useQueryExampleTransaction,
  29. useQueryGetEvent,
  30. useQueryPanelEventCount,
  31. useQueryPanelGraph,
  32. useQueryPanelSparklines,
  33. useQueryPanelTable,
  34. useQueryTransactionByTPMAndDuration,
  35. } from 'sentry/views/starfish/modules/databaseModule/queries';
  36. import {queryToSeries} from 'sentry/views/starfish/modules/databaseModule/utils';
  37. import {getDateFilters} from 'sentry/views/starfish/utils/dates';
  38. import {zeroFillSeries} from 'sentry/views/starfish/utils/zeroFillSeries';
  39. import {DataRow, MainTableSort} from '../databaseTableView';
  40. const INTERVAL = 12;
  41. const SPARKLINE_INTERVAL = 24;
  42. type DbQueryDetailProps = {
  43. isDataLoading: boolean;
  44. mainTableSort: MainTableSort;
  45. onRowChange: (row: DataRow | undefined) => void;
  46. row: DataRow;
  47. nextRow?: DataRow;
  48. prevRow?: DataRow;
  49. transaction?: string;
  50. };
  51. export type TransactionListDataRow = {
  52. count: number;
  53. example: string;
  54. frequency: number;
  55. group_id: string;
  56. p75: number;
  57. transaction: string;
  58. uniqueEvents: number;
  59. };
  60. export default function QueryDetail({
  61. row,
  62. nextRow,
  63. prevRow,
  64. isDataLoading,
  65. onClose,
  66. onRowChange,
  67. mainTableSort,
  68. transaction,
  69. }: Partial<DbQueryDetailProps> & {
  70. isDataLoading: boolean;
  71. mainTableSort: MainTableSort;
  72. onClose: () => void;
  73. onRowChange: (row: DataRow) => void;
  74. }) {
  75. return (
  76. <Detail detailKey={row?.description} onClose={onClose}>
  77. {row && (
  78. <QueryDetailBody
  79. mainTableSort={mainTableSort}
  80. onRowChange={onRowChange}
  81. isDataLoading={isDataLoading}
  82. row={row}
  83. nextRow={nextRow}
  84. prevRow={prevRow}
  85. transaction={transaction}
  86. />
  87. )}
  88. </Detail>
  89. );
  90. }
  91. function QueryDetailBody({
  92. row,
  93. nextRow,
  94. prevRow,
  95. onRowChange,
  96. transaction,
  97. isDataLoading: isRowLoading,
  98. }: DbQueryDetailProps) {
  99. const theme = useTheme();
  100. const pageFilter = usePageFilters();
  101. const organization = useOrganization();
  102. const {startTime, endTime} = getDateFilters(pageFilter);
  103. const isNew = row.newish === 1;
  104. const isOld = row.retired === 1;
  105. const [sort, setSort] = useState<PanelSort>({
  106. direction: undefined,
  107. sortHeader: undefined,
  108. });
  109. const {isLoading, data: graphData} = useQueryPanelGraph(row, INTERVAL);
  110. const {isLoading: isTableLoading, data: tableData} = useQueryPanelTable(
  111. row,
  112. sort.sortHeader?.key,
  113. sort.direction,
  114. transaction
  115. );
  116. const {isLoading: isSparklinesLoading, data: sparklineData} = useQueryPanelSparklines(
  117. row,
  118. sort.sortHeader?.key,
  119. sort.direction,
  120. SPARKLINE_INTERVAL,
  121. transaction
  122. );
  123. const {isLoading: isP75GraphLoading, data: transactionGraphData} =
  124. useQueryTransactionByTPMAndDuration(
  125. tableData.map(d => d.transaction).splice(0, 5),
  126. SPARKLINE_INTERVAL
  127. );
  128. const {isLoading: isEventCountLoading, data: eventCountData} =
  129. useQueryPanelEventCount(row);
  130. const {isLoading: isExampleLoading, data: exampleTransaction} =
  131. useQueryExampleTransaction(row);
  132. const {isLoading: isFirstExampleLoading, data: firstSeenExample} = useQueryGetEvent(
  133. exampleTransaction?.[0]?.first
  134. );
  135. const {isLoading: isLastExampleLoading, data: lastSeenExample} = useQueryGetEvent(
  136. exampleTransaction?.[0]?.latest
  137. );
  138. const isDataLoading =
  139. isLoading ||
  140. isTableLoading ||
  141. isEventCountLoading ||
  142. isRowLoading ||
  143. isP75GraphLoading ||
  144. isExampleLoading ||
  145. isFirstExampleLoading ||
  146. isLastExampleLoading ||
  147. isSparklinesLoading;
  148. const eventCountMap = keyBy(eventCountData, 'transaction');
  149. const mergedTableData: TransactionListDataRow[] = tableData.map(data => {
  150. const tableTransaction = data.transaction;
  151. const eventData = eventCountMap[tableTransaction];
  152. if (eventData?.uniqueEvents) {
  153. const frequency = data.count / eventData.uniqueEvents;
  154. return {...data, frequency, ...eventData} as TransactionListDataRow;
  155. }
  156. return data as TransactionListDataRow;
  157. });
  158. const [countSeries, p50Series, p95Series] = throughputQueryToChartData(
  159. graphData,
  160. startTime,
  161. endTime
  162. );
  163. const spmTransactionSeries = queryToSeries(
  164. sparklineData,
  165. 'transaction',
  166. 'spm',
  167. startTime,
  168. endTime,
  169. SPARKLINE_INTERVAL
  170. );
  171. const spanp50TransactionSeries = queryToSeries(
  172. sparklineData,
  173. 'transaction',
  174. 'p50',
  175. startTime,
  176. endTime,
  177. SPARKLINE_INTERVAL
  178. );
  179. const tpmTransactionSeries = queryToSeries(
  180. transactionGraphData,
  181. 'group',
  182. 'epm()',
  183. startTime,
  184. endTime,
  185. SPARKLINE_INTERVAL
  186. );
  187. const p50TransactionSeries = queryToSeries(
  188. transactionGraphData,
  189. 'group',
  190. 'p50(transaction.duration)',
  191. startTime,
  192. endTime,
  193. SPARKLINE_INTERVAL
  194. );
  195. const markLine =
  196. spmTransactionSeries?.[0]?.data && (isNew || isOld)
  197. ? generateMarkLine(
  198. isNew ? 'First Seen' : 'Last Seen',
  199. isNew ? row.firstSeen : row.lastSeen,
  200. spmTransactionSeries[0].data,
  201. theme
  202. )
  203. : undefined;
  204. return (
  205. <div>
  206. <FlexRowContainer>
  207. <FlexRowItem>
  208. <h2>{t('Query Detail')}</h2>
  209. </FlexRowItem>
  210. <FlexRowItem>
  211. <SimplePagination
  212. disableLeft={!prevRow}
  213. disableRight={!nextRow}
  214. onLeftClick={() => onRowChange(prevRow)}
  215. onRightClick={() => onRowChange(nextRow)}
  216. />
  217. </FlexRowItem>
  218. </FlexRowContainer>
  219. <FlexRowContainer>
  220. <FlexRowItem>
  221. <SubHeader>
  222. {t('First Seen')}
  223. {row.newish === 1 && <Badge type="new" text="new" />}
  224. </SubHeader>
  225. {Math.abs(moment(row.firstSeen).diff(startTime, 'minutes')) < 720 ? (
  226. <SubSubHeader>
  227. More than <TimeSince date={row.firstSeen} />{' '}
  228. </SubSubHeader>
  229. ) : (
  230. <span>
  231. <SubSubHeader>
  232. <TimeSince date={row.firstSeen} />{' '}
  233. </SubSubHeader>
  234. {firstSeenExample?.release && (
  235. <VersionHoverCard
  236. organization={organization}
  237. projectSlug="sentry"
  238. releaseVersion={firstSeenExample.release.version}
  239. showUnderline
  240. underlineColor="linkUnderline"
  241. >
  242. <Version version={String(firstSeenExample.release.version)} truncate />
  243. </VersionHoverCard>
  244. )}
  245. </span>
  246. )}
  247. </FlexRowItem>
  248. <FlexRowItem>
  249. <SubHeader>
  250. {t('Last Seen')}
  251. {row.retired === 1 && <Badge type="warning" text="old" />}
  252. </SubHeader>
  253. <SubSubHeader>
  254. <TimeSince date={row.lastSeen} />
  255. </SubSubHeader>
  256. {lastSeenExample?.release && (
  257. <VersionHoverCard
  258. organization={organization}
  259. projectSlug="sentry"
  260. releaseVersion={lastSeenExample.release.version}
  261. showUnderline
  262. underlineColor="linkUnderline"
  263. >
  264. <Version version={String(lastSeenExample.release.version)} truncate />
  265. </VersionHoverCard>
  266. )}
  267. </FlexRowItem>
  268. <FlexRowItem>
  269. <SubHeader>{t('Total Time')}</SubHeader>
  270. <SubSubHeader>{row.total_time.toFixed(2)}ms</SubSubHeader>
  271. </FlexRowItem>
  272. </FlexRowContainer>
  273. <SubHeader>{t('Query Description')}</SubHeader>
  274. <FormattedCode>{highlightSql(row.formatted_desc, row)}</FormattedCode>
  275. <FlexRowContainer>
  276. <FlexRowItem>
  277. <SubHeader>{t('Throughput (Spans Per Minute)')}</SubHeader>
  278. <SubSubHeader>{row.epm.toFixed(3)}</SubSubHeader>
  279. <Chart
  280. statsPeriod="24h"
  281. height={140}
  282. data={[countSeries]}
  283. start=""
  284. end=""
  285. loading={isDataLoading}
  286. utc={false}
  287. stacked
  288. isLineChart
  289. disableXAxis
  290. hideYAxisSplitLine
  291. />
  292. </FlexRowItem>
  293. <FlexRowItem>
  294. <SubHeader>{t('Duration P50 / P95')}</SubHeader>
  295. <SubSubHeader>
  296. {row.p50.toFixed(3)}ms / {row.p95.toFixed(3)}ms
  297. </SubSubHeader>
  298. <Chart
  299. statsPeriod="24h"
  300. height={140}
  301. data={[p50Series, p95Series]}
  302. start=""
  303. end=""
  304. loading={isDataLoading}
  305. utc={false}
  306. chartColors={theme.charts.getColorPalette(4).slice(3, 5)}
  307. stacked
  308. isLineChart
  309. disableXAxis
  310. hideYAxisSplitLine
  311. />
  312. </FlexRowItem>
  313. </FlexRowContainer>
  314. <QueryTransactionTable
  315. isDataLoading={isDataLoading}
  316. onClickSort={s => setSort(s)}
  317. row={row}
  318. sort={sort}
  319. tableData={mergedTableData}
  320. spmData={spmTransactionSeries}
  321. tpmData={tpmTransactionSeries}
  322. spanP50Data={spanp50TransactionSeries}
  323. txnP50Data={p50TransactionSeries}
  324. markLine={markLine}
  325. />
  326. <FlexRowContainer>
  327. <FlexRowItem>
  328. <SubHeader>{t('Example Profile')}</SubHeader>
  329. <ProfileView
  330. spanHash={row.group_id}
  331. transactionNames={tableData.map(d => d.transaction)}
  332. />
  333. </FlexRowItem>
  334. </FlexRowContainer>
  335. <FlexRowContainer>
  336. <FlexRowItem>
  337. <SubHeader>{t('Similar Queries')}</SubHeader>
  338. <SimilarQueryView mainTableRow={row} />
  339. </FlexRowItem>
  340. </FlexRowContainer>
  341. </div>
  342. );
  343. }
  344. type SimplePaginationProps = {
  345. disableLeft?: boolean;
  346. disableRight?: boolean;
  347. onLeftClick?: () => void;
  348. onRightClick?: () => void;
  349. };
  350. function SimplePagination(props: SimplePaginationProps) {
  351. return (
  352. <ButtonBar merged>
  353. <Button
  354. icon={<IconChevron direction="left" size="sm" />}
  355. aria-label={t('Previous')}
  356. disabled={props.disableLeft}
  357. onClick={props.onLeftClick}
  358. />
  359. <Button
  360. icon={<IconChevron direction="right" size="sm" />}
  361. aria-label={t('Next')}
  362. onClick={props.onRightClick}
  363. disabled={props.disableRight}
  364. />
  365. </ButtonBar>
  366. );
  367. }
  368. export const highlightSql = (
  369. description: string,
  370. queryDetail: {action: string; domain: string}
  371. ) => {
  372. let acc = '';
  373. return description.split('').map((token, i) => {
  374. acc += token;
  375. let final: string | React.ReactElement | null = null;
  376. if (acc === queryDetail.action) {
  377. final = <Operation key={i}>{queryDetail.action} </Operation>;
  378. } else if (acc === queryDetail.domain) {
  379. final = <Domain key={i}>{queryDetail.domain} </Domain>;
  380. } else if (
  381. ['FROM', 'INNER', 'JOIN', 'WHERE', 'ON', 'AND', 'NOT', 'NULL', 'IS'].includes(acc)
  382. ) {
  383. final = <Keyword key={i}>{acc}</Keyword>;
  384. } else if (['(', ')'].includes(acc)) {
  385. final = <Bracket key={i}>{acc}</Bracket>;
  386. } else if (token === ' ' || token === '\n' || description[i + 1] === ')') {
  387. final = acc;
  388. } else if (i === description.length - 1) {
  389. final = acc;
  390. }
  391. if (final) {
  392. acc = '';
  393. const result = final;
  394. final = null;
  395. return result;
  396. }
  397. return null;
  398. });
  399. };
  400. const throughputQueryToChartData = (
  401. data: any,
  402. startTime: moment.Moment,
  403. endTime: moment.Moment
  404. ): Series[] => {
  405. const countSeries: Series = {seriesName: 'spm()', data: [] as any[]};
  406. const p50Series: Series = {seriesName: 'p50()', data: [] as any[]};
  407. const p95Series: Series = {seriesName: 'p95()', data: [] as any[]};
  408. data.forEach(({count, p50, p95, interval}) => {
  409. countSeries.data.push({value: count, name: interval});
  410. p50Series.data.push({value: p50, name: interval});
  411. p95Series.data.push({value: p95, name: interval});
  412. });
  413. return [
  414. zeroFillSeries(countSeries, moment.duration(INTERVAL, 'hours'), startTime, endTime),
  415. zeroFillSeries(p50Series, moment.duration(INTERVAL, 'hours'), startTime, endTime),
  416. zeroFillSeries(p95Series, moment.duration(INTERVAL, 'hours'), startTime, endTime),
  417. ];
  418. };
  419. const SubHeader = styled('h3')`
  420. color: ${p => p.theme.gray300};
  421. font-size: ${p => p.theme.fontSizeLarge};
  422. `;
  423. const SubSubHeader = styled('h4')`
  424. margin: 0;
  425. font-weight: normal;
  426. `;
  427. export const FlexRowContainer = styled('div')`
  428. display: flex;
  429. & > div:last-child {
  430. padding-right: ${space(1)};
  431. }
  432. padding-bottom: ${space(2)};
  433. `;
  434. export const FlexRowItem = styled('div')`
  435. padding-right: ${space(4)};
  436. flex: 1;
  437. `;
  438. const Operation = styled('b')`
  439. color: ${p => p.theme.blue400};
  440. `;
  441. const Domain = styled('b')`
  442. color: ${p => p.theme.green400};
  443. margin-right: -${space(0.5)};
  444. `;
  445. const Keyword = styled('b')`
  446. color: ${p => p.theme.yellow400};
  447. `;
  448. const Bracket = styled('b')`
  449. color: ${p => p.theme.pink400};
  450. `;