requestLog.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. function 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. function TimestampLink({date, link}: {date: moment.MomentInput; link?: string}) {
  83. return 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. }
  92. type Props = AsyncComponent['props'] & {
  93. app: SentryApp;
  94. };
  95. type State = AsyncComponent['state'] & {
  96. currentPage: number;
  97. errorsOnly: boolean;
  98. eventType: string;
  99. requests: SentryAppWebhookRequest[];
  100. };
  101. export default class RequestLog extends AsyncComponent<Props, State> {
  102. shouldReload = true;
  103. get hasNextPage() {
  104. return (this.state.currentPage + 1) * MAX_PER_PAGE < this.state.requests.length;
  105. }
  106. get hasPrevPage() {
  107. return this.state.currentPage > 0;
  108. }
  109. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  110. const {slug} = this.props.app;
  111. const query: any = {};
  112. if (this.state) {
  113. if (this.state.eventType !== ALL_EVENTS) {
  114. query.eventType = this.state.eventType;
  115. }
  116. if (this.state.errorsOnly) {
  117. query.errorsOnly = true;
  118. }
  119. }
  120. return [['requests', `/sentry-apps/${slug}/requests/`, {query}]];
  121. }
  122. getDefaultState() {
  123. return {
  124. ...super.getDefaultState(),
  125. requests: [],
  126. eventType: ALL_EVENTS,
  127. errorsOnly: false,
  128. currentPage: 0,
  129. };
  130. }
  131. handleChangeEventType = (eventType: string) => {
  132. this.setState(
  133. {
  134. eventType,
  135. currentPage: 0,
  136. },
  137. this.remountComponent
  138. );
  139. };
  140. handleChangeErrorsOnly = () => {
  141. this.setState(
  142. {
  143. errorsOnly: !this.state.errorsOnly,
  144. currentPage: 0,
  145. },
  146. this.remountComponent
  147. );
  148. };
  149. handleNextPage = () => {
  150. this.setState({
  151. currentPage: this.state.currentPage + 1,
  152. });
  153. };
  154. handlePrevPage = () => {
  155. this.setState({
  156. currentPage: this.state.currentPage - 1,
  157. });
  158. };
  159. renderLoading() {
  160. return this.renderBody();
  161. }
  162. renderBody() {
  163. const {requests, eventType, errorsOnly, currentPage} = this.state;
  164. const {app} = this.props;
  165. const currentRequests = requests.slice(
  166. currentPage * MAX_PER_PAGE,
  167. (currentPage + 1) * MAX_PER_PAGE
  168. );
  169. return (
  170. <Fragment>
  171. <h5>{t('Request Log')}</h5>
  172. <div>
  173. <p>
  174. {t(
  175. 'This log shows the status of any outgoing webhook requests from Sentry to your integration.'
  176. )}
  177. </p>
  178. <RequestLogFilters>
  179. <CompactSelect
  180. triggerLabel={eventType}
  181. value={eventType}
  182. options={getEventTypes(app).map(type => ({
  183. value: type,
  184. label: type,
  185. }))}
  186. onChange={opt => this.handleChangeEventType(opt?.value)}
  187. />
  188. <StyledErrorsOnlyButton onClick={this.handleChangeErrorsOnly}>
  189. <ErrorsOnlyCheckbox>
  190. <Checkbox checked={errorsOnly} onChange={() => {}} />
  191. {t('Errors Only')}
  192. </ErrorsOnlyCheckbox>
  193. </StyledErrorsOnlyButton>
  194. </RequestLogFilters>
  195. </div>
  196. <Panel>
  197. <PanelHeader>
  198. <TableLayout hasOrganization={app.status !== 'internal'}>
  199. <div>{t('Time')}</div>
  200. <div>{t('Status Code')}</div>
  201. {app.status !== 'internal' && <div>{t('Organization')}</div>}
  202. <div>{t('Event Type')}</div>
  203. <div>{t('Webhook URL')}</div>
  204. </TableLayout>
  205. </PanelHeader>
  206. {!this.state.loading ? (
  207. <PanelBody>
  208. {currentRequests.length > 0 ? (
  209. currentRequests.map((request, idx) => (
  210. <PanelItem key={idx} data-test-id="request-item">
  211. <TableLayout hasOrganization={app.status !== 'internal'}>
  212. <TimestampLink date={request.date} link={request.errorUrl} />
  213. <ResponseCode code={request.responseCode} />
  214. {app.status !== 'internal' && (
  215. <div>
  216. {request.organization ? request.organization.name : null}
  217. </div>
  218. )}
  219. <div>{request.eventType}</div>
  220. <OverflowBox>{request.webhookUrl}</OverflowBox>
  221. </TableLayout>
  222. </PanelItem>
  223. ))
  224. ) : (
  225. <EmptyMessage icon={<IconFlag size="xl" />}>
  226. {t('No requests found in the last 30 days.')}
  227. </EmptyMessage>
  228. )}
  229. </PanelBody>
  230. ) : (
  231. <LoadingIndicator />
  232. )}
  233. </Panel>
  234. <PaginationButtons>
  235. <Button
  236. icon={<IconChevron direction="left" size="sm" />}
  237. onClick={this.handlePrevPage}
  238. disabled={!this.hasPrevPage}
  239. aria-label={t('Previous page')}
  240. />
  241. <Button
  242. icon={<IconChevron direction="right" size="sm" />}
  243. onClick={this.handleNextPage}
  244. disabled={!this.hasNextPage}
  245. aria-label={t('Next page')}
  246. />
  247. </PaginationButtons>
  248. </Fragment>
  249. );
  250. }
  251. }
  252. const TableLayout = styled('div')<{hasOrganization: boolean}>`
  253. display: grid;
  254. grid-template-columns: 1fr 0.5fr ${p => (p.hasOrganization ? '1fr' : '')} 1fr 1fr;
  255. grid-column-gap: ${space(1.5)};
  256. width: 100%;
  257. align-items: center;
  258. `;
  259. const OverflowBox = styled('div')`
  260. word-break: break-word;
  261. `;
  262. const PaginationButtons = styled('div')`
  263. display: flex;
  264. justify-content: flex-end;
  265. align-items: center;
  266. > :first-child {
  267. border-top-right-radius: 0;
  268. border-bottom-right-radius: 0;
  269. }
  270. > :nth-child(2) {
  271. margin-left: -1px;
  272. border-top-left-radius: 0;
  273. border-bottom-left-radius: 0;
  274. }
  275. `;
  276. const RequestLogFilters = styled('div')`
  277. display: flex;
  278. align-items: center;
  279. padding-bottom: ${space(1)};
  280. > :first-child ${StyledButton} {
  281. border-radius: ${p => p.theme.borderRadiusLeft};
  282. }
  283. `;
  284. const ErrorsOnlyCheckbox = styled('div')`
  285. display: flex;
  286. gap: ${space(1)};
  287. align-items: center;
  288. `;
  289. const StyledErrorsOnlyButton = styled(Button)`
  290. margin-left: -1px;
  291. border-top-left-radius: 0;
  292. border-bottom-left-radius: 0;
  293. `;
  294. const StyledIconOpen = styled(IconOpen)`
  295. margin-left: 6px;
  296. color: ${p => p.theme.subText};
  297. `;
  298. const Tags = styled('div')`
  299. margin: -${space(0.5)};
  300. `;
  301. const StyledTag = styled(Tag)`
  302. padding: ${space(0.5)};
  303. display: inline-flex;
  304. `;