index.tsx 12 KB

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