requestLog.tsx 9.7 KB

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