requestLog.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import {Fragment, useCallback, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import memoize from 'lodash/memoize';
  4. import type moment from 'moment-timezone';
  5. import {Button, StyledButton} from 'sentry/components/button';
  6. import {CompactSelect} from 'sentry/components/compactSelect';
  7. import {Tag, type TagProps} from 'sentry/components/core/badge/tag';
  8. import {Checkbox} from 'sentry/components/core/checkbox';
  9. import {DateTime} from 'sentry/components/dateTime';
  10. import EmptyMessage from 'sentry/components/emptyMessage';
  11. import ExternalLink from 'sentry/components/links/externalLink';
  12. import LoadingIndicator from 'sentry/components/loadingIndicator';
  13. import Panel from 'sentry/components/panels/panel';
  14. import PanelBody from 'sentry/components/panels/panelBody';
  15. import PanelHeader from 'sentry/components/panels/panelHeader';
  16. import PanelItem from 'sentry/components/panels/panelItem';
  17. import {IconChevron, IconFlag, IconOpen} from 'sentry/icons';
  18. import {t} from 'sentry/locale';
  19. import {space} from 'sentry/styles/space';
  20. import type {
  21. SentryApp,
  22. SentryAppSchemaIssueLink,
  23. SentryAppWebhookRequest,
  24. } from 'sentry/types/integrations';
  25. import {shouldUse24Hours} from 'sentry/utils/dates';
  26. import {type ApiQueryKey, useApiQuery} from 'sentry/utils/queryClient';
  27. const ALL_EVENTS = t('All Events');
  28. const MAX_PER_PAGE = 10;
  29. const is24Hours = shouldUse24Hours();
  30. const componentHasSelectUri = (issueLinkComponent: SentryAppSchemaIssueLink): boolean => {
  31. const hasSelectUri = (fields: any[]): boolean =>
  32. fields.some(field => field.type === 'select' && 'uri' in field);
  33. const createHasSelectUri =
  34. hasSelectUri(issueLinkComponent.create.required_fields) ||
  35. hasSelectUri(issueLinkComponent.create.optional_fields || []);
  36. const linkHasSelectUri =
  37. hasSelectUri(issueLinkComponent.link.required_fields) ||
  38. hasSelectUri(issueLinkComponent.link.optional_fields || []);
  39. return createHasSelectUri || linkHasSelectUri;
  40. };
  41. const getEventTypes = memoize((app: SentryApp) => {
  42. // TODO(nola): ideally this would be kept in sync with EXTENDED_VALID_EVENTS on the backend
  43. let issueLinkEvents: string[] = [];
  44. const issueLinkComponent = (app.schema.elements || []).find(
  45. element => element.type === 'issue-link'
  46. );
  47. if (issueLinkComponent) {
  48. issueLinkEvents = ['external_issue.created', 'external_issue.linked'];
  49. if (componentHasSelectUri(issueLinkComponent)) {
  50. issueLinkEvents.push('select_options.requested');
  51. }
  52. }
  53. const events = [
  54. ALL_EVENTS,
  55. // Internal apps don't have installation webhooks
  56. ...(app.status !== 'internal'
  57. ? ['installation.created', 'installation.deleted']
  58. : []),
  59. ...(app.events.includes('error') ? ['error.created'] : []),
  60. ...(app.events.includes('issue')
  61. ? ['issue.created', 'issue.resolved', 'issue.ignored', 'issue.assigned']
  62. : []),
  63. ...(app.isAlertable
  64. ? [
  65. 'event_alert.triggered',
  66. 'metric_alert.open',
  67. 'metric_alert.resolved',
  68. 'metric_alert.critical',
  69. 'metric_alert.warning',
  70. ]
  71. : []),
  72. ...issueLinkEvents,
  73. ];
  74. return events;
  75. });
  76. function ResponseCode({code}: {code: number}) {
  77. let type: TagProps['type'] = 'error';
  78. if (code <= 399 && code >= 300) {
  79. type = 'warning';
  80. } else if (code <= 299 && code >= 100) {
  81. type = 'success';
  82. }
  83. return (
  84. <Tags>
  85. <StyledTag type={type}>{code === 0 ? 'timeout' : code}</StyledTag>
  86. </Tags>
  87. );
  88. }
  89. function TimestampLink({date, link}: {date: moment.MomentInput; link?: string}) {
  90. return link ? (
  91. <ExternalLink href={link}>
  92. <DateTime date={date} />
  93. <StyledIconOpen size="xs" />
  94. </ExternalLink>
  95. ) : (
  96. <DateTime date={date} format={is24Hours ? 'MMM D, YYYY HH:mm:ss z' : 'll LTS z'} />
  97. );
  98. }
  99. interface RequestLogProps {
  100. app: SentryApp;
  101. }
  102. function makeRequestLogQueryKey(
  103. slug: string,
  104. query: Record<string, string>
  105. ): ApiQueryKey {
  106. return [`/sentry-apps/${slug}/webhook-requests/`, {query}];
  107. }
  108. export default function RequestLog({app}: RequestLogProps) {
  109. const [currentPage, setCurrentPage] = useState(0);
  110. const [errorsOnly, setErrorsOnly] = useState(false);
  111. const [eventType, setEventType] = useState(ALL_EVENTS);
  112. const {slug} = app;
  113. const query: any = {};
  114. if (eventType !== ALL_EVENTS) {
  115. query.eventType = eventType;
  116. }
  117. if (errorsOnly) {
  118. query.errorsOnly = true;
  119. }
  120. const {
  121. data: requests = [],
  122. isLoading,
  123. refetch,
  124. } = useApiQuery<SentryAppWebhookRequest[]>(makeRequestLogQueryKey(slug, query), {
  125. staleTime: Infinity,
  126. });
  127. const currentRequests = useMemo(
  128. () => requests.slice(currentPage * MAX_PER_PAGE, (currentPage + 1) * MAX_PER_PAGE),
  129. [currentPage, requests]
  130. );
  131. const hasNextPage = useMemo(
  132. () => (currentPage + 1) * MAX_PER_PAGE < requests.length,
  133. [currentPage, requests]
  134. );
  135. const hasPrevPage = useMemo(() => currentPage > 0, [currentPage]);
  136. const handleChangeEventType = useCallback(
  137. (newEventType: string) => {
  138. setEventType(newEventType);
  139. setCurrentPage(0);
  140. refetch();
  141. },
  142. [refetch]
  143. );
  144. const handleChangeErrorsOnly = useCallback(() => {
  145. setErrorsOnly(!errorsOnly);
  146. setCurrentPage(0);
  147. refetch();
  148. }, [errorsOnly, refetch]);
  149. const handleNextPage = useCallback(() => {
  150. setCurrentPage(currentPage + 1);
  151. }, [currentPage]);
  152. const handlePrevPage = useCallback(() => {
  153. setCurrentPage(currentPage - 1);
  154. }, [currentPage]);
  155. return (
  156. <Fragment>
  157. <h5>{t('Request Log')}</h5>
  158. <div>
  159. <p>
  160. {t(
  161. 'This log shows the status of any outgoing webhook requests from Sentry to your integration.'
  162. )}
  163. </p>
  164. <RequestLogFilters>
  165. <CompactSelect
  166. triggerLabel={eventType}
  167. value={eventType}
  168. options={getEventTypes(app).map(type => ({
  169. value: type,
  170. label: type,
  171. }))}
  172. onChange={opt => handleChangeEventType(opt?.value)}
  173. />
  174. <StyledErrorsOnlyButton onClick={handleChangeErrorsOnly}>
  175. <ErrorsOnlyCheckbox>
  176. <Checkbox checked={errorsOnly} onChange={() => {}} />
  177. {t('Errors Only')}
  178. </ErrorsOnlyCheckbox>
  179. </StyledErrorsOnlyButton>
  180. </RequestLogFilters>
  181. </div>
  182. <Panel>
  183. <PanelHeader>
  184. <TableLayout hasOrganization={app.status !== 'internal'}>
  185. <div>{t('Time')}</div>
  186. <div>{t('Status Code')}</div>
  187. {app.status !== 'internal' && <div>{t('Organization')}</div>}
  188. <div>{t('Event Type')}</div>
  189. <div>{t('Webhook URL')}</div>
  190. </TableLayout>
  191. </PanelHeader>
  192. {!isLoading ? (
  193. <PanelBody>
  194. {currentRequests.length > 0 ? (
  195. currentRequests.map((request, idx) => (
  196. <PanelItem key={idx} data-test-id="request-item">
  197. <TableLayout hasOrganization={app.status !== 'internal'}>
  198. <TimestampLink date={request.date} link={request.errorUrl} />
  199. <ResponseCode code={request.responseCode} />
  200. {app.status !== 'internal' && (
  201. <div>{request.organization ? request.organization.name : null}</div>
  202. )}
  203. <div>{request.eventType}</div>
  204. <OverflowBox>{request.webhookUrl}</OverflowBox>
  205. </TableLayout>
  206. </PanelItem>
  207. ))
  208. ) : (
  209. <EmptyMessage icon={<IconFlag size="xl" />}>
  210. {t('No requests found in the last 30 days.')}
  211. </EmptyMessage>
  212. )}
  213. </PanelBody>
  214. ) : (
  215. <LoadingIndicator />
  216. )}
  217. </Panel>
  218. <PaginationButtons>
  219. <Button
  220. icon={<IconChevron direction="left" />}
  221. onClick={handlePrevPage}
  222. disabled={!hasPrevPage}
  223. aria-label={t('Previous page')}
  224. />
  225. <Button
  226. icon={<IconChevron direction="right" />}
  227. onClick={handleNextPage}
  228. disabled={!hasNextPage}
  229. aria-label={t('Next page')}
  230. />
  231. </PaginationButtons>
  232. </Fragment>
  233. );
  234. }
  235. const TableLayout = styled('div')<{hasOrganization: boolean}>`
  236. display: grid;
  237. grid-template-columns: 1fr 0.5fr ${p => (p.hasOrganization ? '1fr' : '')} 1fr 1fr;
  238. grid-column-gap: ${space(1.5)};
  239. width: 100%;
  240. align-items: center;
  241. `;
  242. const OverflowBox = styled('div')`
  243. word-break: break-word;
  244. `;
  245. const PaginationButtons = styled('div')`
  246. display: flex;
  247. justify-content: flex-end;
  248. align-items: center;
  249. > :first-child {
  250. border-top-right-radius: 0;
  251. border-bottom-right-radius: 0;
  252. }
  253. > :nth-child(2) {
  254. margin-left: -1px;
  255. border-top-left-radius: 0;
  256. border-bottom-left-radius: 0;
  257. }
  258. `;
  259. const RequestLogFilters = styled('div')`
  260. display: flex;
  261. align-items: center;
  262. padding-bottom: ${space(1)};
  263. > :first-child ${StyledButton} {
  264. border-radius: ${p => p.theme.borderRadius} 0 0 ${p => p.theme.borderRadius};
  265. }
  266. `;
  267. const ErrorsOnlyCheckbox = styled('div')`
  268. display: flex;
  269. gap: ${space(1)};
  270. align-items: center;
  271. `;
  272. const StyledErrorsOnlyButton = styled(Button)`
  273. margin-left: -1px;
  274. border-top-left-radius: 0;
  275. border-bottom-left-radius: 0;
  276. `;
  277. const StyledIconOpen = styled(IconOpen)`
  278. margin-left: 6px;
  279. color: ${p => p.theme.subText};
  280. `;
  281. const Tags = styled('div')`
  282. margin: -${space(0.5)};
  283. `;
  284. const StyledTag = styled(Tag)`
  285. padding: ${space(0.5)};
  286. `;