requestLog.tsx 9.9 KB

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