requestLog.tsx 9.9 KB

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