index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import {createContext} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import pick from 'lodash/pick';
  5. import moment from 'moment';
  6. import Alert from 'app/components/alert';
  7. import AsyncComponent from 'app/components/asyncComponent';
  8. import LoadingIndicator from 'app/components/loadingIndicator';
  9. import NoProjectMessage from 'app/components/noProjectMessage';
  10. import GlobalSelectionHeader from 'app/components/organizations/globalSelectionHeader';
  11. import {getParams} from 'app/components/organizations/globalSelectionHeader/getParams';
  12. import PickProjectToContinue from 'app/components/pickProjectToContinue';
  13. import {DEFAULT_STATS_PERIOD} from 'app/constants';
  14. import {URL_PARAM} from 'app/constants/globalSelectionHeader';
  15. import {IconInfo, IconWarning} from 'app/icons';
  16. import {t} from 'app/locale';
  17. import {PageContent} from 'app/styles/organization';
  18. import space from 'app/styles/space';
  19. import {
  20. Deploy,
  21. GlobalSelection,
  22. Organization,
  23. ReleaseMeta,
  24. ReleaseProject,
  25. ReleaseWithHealth,
  26. SessionApiResponse,
  27. SessionField,
  28. } from 'app/types';
  29. import {formatVersion} from 'app/utils/formatters';
  30. import routeTitleGen from 'app/utils/routeTitle';
  31. import {getCount} from 'app/utils/sessions';
  32. import withGlobalSelection from 'app/utils/withGlobalSelection';
  33. import withOrganization from 'app/utils/withOrganization';
  34. import AsyncView from 'app/views/asyncView';
  35. import {DisplayOption} from '../list/utils';
  36. import {getReleaseBounds, ReleaseBounds} from '../utils';
  37. import ReleaseHealthRequest, {
  38. ReleaseHealthRequestRenderProps,
  39. } from '../utils/releaseHealthRequest';
  40. import ReleaseHeader from './releaseHeader';
  41. const DEFAULT_FRESH_RELEASE_STATS_PERIOD = '24h';
  42. type ReleaseContextType = {
  43. release: ReleaseWithHealth;
  44. project: Required<ReleaseProject>;
  45. deploys: Deploy[];
  46. releaseMeta: ReleaseMeta;
  47. refetchData: () => void;
  48. defaultStatsPeriod: string;
  49. getHealthData: ReleaseHealthRequestRenderProps['getHealthData'];
  50. isHealthLoading: ReleaseHealthRequestRenderProps['isHealthLoading'];
  51. hasHealthData: boolean;
  52. releaseBounds: ReleaseBounds;
  53. };
  54. const ReleaseContext = createContext<ReleaseContextType>({} as ReleaseContextType);
  55. type RouteParams = {
  56. orgId: string;
  57. release: string;
  58. };
  59. type Props = RouteComponentProps<RouteParams, {}> & {
  60. organization: Organization;
  61. selection: GlobalSelection;
  62. releaseMeta: ReleaseMeta;
  63. defaultStatsPeriod: string;
  64. getHealthData: ReleaseHealthRequestRenderProps['getHealthData'];
  65. isHealthLoading: ReleaseHealthRequestRenderProps['isHealthLoading'];
  66. };
  67. type State = {
  68. release: ReleaseWithHealth;
  69. deploys: Deploy[];
  70. sessions: SessionApiResponse | null;
  71. } & AsyncView['state'];
  72. class ReleasesDetail extends AsyncView<Props, State> {
  73. shouldReload = true;
  74. getTitle() {
  75. const {params, organization, selection} = this.props;
  76. const {release} = this.state;
  77. // The release details page will always have only one project selected
  78. const project = release?.projects.find(p => p.id === selection.projects[0]);
  79. return routeTitleGen(
  80. t('Release %s', formatVersion(params.release)),
  81. organization.slug,
  82. false,
  83. project?.slug
  84. );
  85. }
  86. getDefaultState() {
  87. return {
  88. ...super.getDefaultState(),
  89. deploys: [],
  90. sessions: null,
  91. };
  92. }
  93. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  94. const {organization, location, params, releaseMeta, defaultStatsPeriod} = this.props;
  95. const basePath = `/organizations/${organization.slug}/releases/${encodeURIComponent(
  96. params.release
  97. )}/`;
  98. const endpoints: ReturnType<AsyncView['getEndpoints']> = [
  99. [
  100. 'release',
  101. basePath,
  102. {
  103. query: {
  104. adoptionStages: 1,
  105. ...getParams(pick(location.query, [...Object.values(URL_PARAM)]), {
  106. defaultStatsPeriod,
  107. }),
  108. },
  109. },
  110. ],
  111. ];
  112. if (releaseMeta.deployCount > 0) {
  113. endpoints.push(['deploys', `${basePath}deploys/`]);
  114. }
  115. // Used to figure out if the release has any health data
  116. endpoints.push([
  117. 'sessions',
  118. `/organizations/${organization.slug}/sessions/`,
  119. {
  120. query: {
  121. project: location.query.project,
  122. environment: location.query.environment ?? [],
  123. query: `release:"${params.release}"`,
  124. field: 'sum(session)',
  125. statsPeriod: '90d',
  126. interval: '1d',
  127. },
  128. },
  129. ]);
  130. return endpoints;
  131. }
  132. renderError(...args) {
  133. const possiblyWrongProject = Object.values(this.state.errors).find(
  134. e => e?.status === 404 || e?.status === 403
  135. );
  136. if (possiblyWrongProject) {
  137. return (
  138. <PageContent>
  139. <Alert type="error" icon={<IconWarning />}>
  140. {t('This release may not be in your selected project.')}
  141. </Alert>
  142. </PageContent>
  143. );
  144. }
  145. return super.renderError(...args);
  146. }
  147. renderLoading() {
  148. return (
  149. <PageContent>
  150. <LoadingIndicator />
  151. </PageContent>
  152. );
  153. }
  154. renderBody() {
  155. const {
  156. organization,
  157. location,
  158. selection,
  159. releaseMeta,
  160. defaultStatsPeriod,
  161. getHealthData,
  162. isHealthLoading,
  163. } = this.props;
  164. const {release, deploys, sessions, reloading} = this.state;
  165. const project = release?.projects.find(p => p.id === selection.projects[0]);
  166. const releaseBounds = getReleaseBounds(release);
  167. if (!project || !release) {
  168. if (reloading) {
  169. return <LoadingIndicator />;
  170. }
  171. return null;
  172. }
  173. return (
  174. <NoProjectMessage organization={organization}>
  175. <StyledPageContent>
  176. <ReleaseHeader
  177. location={location}
  178. organization={organization}
  179. release={release}
  180. project={project}
  181. releaseMeta={releaseMeta}
  182. refetchData={this.fetchData}
  183. />
  184. <ReleaseContext.Provider
  185. value={{
  186. release,
  187. project,
  188. deploys,
  189. releaseMeta,
  190. refetchData: this.fetchData,
  191. defaultStatsPeriod,
  192. getHealthData,
  193. isHealthLoading,
  194. hasHealthData: getCount(sessions?.groups, SessionField.SESSIONS) > 0,
  195. releaseBounds,
  196. }}
  197. >
  198. {this.props.children}
  199. </ReleaseContext.Provider>
  200. </StyledPageContent>
  201. </NoProjectMessage>
  202. );
  203. }
  204. }
  205. class ReleasesDetailContainer extends AsyncComponent<
  206. Omit<Props, 'releaseMeta' | 'getHealthData' | 'isHealthLoading'>,
  207. {releaseMeta: ReleaseMeta | null} & AsyncComponent['state']
  208. > {
  209. shouldReload = true;
  210. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  211. const {organization, params} = this.props;
  212. // fetch projects this release belongs to
  213. return [
  214. [
  215. 'releaseMeta',
  216. `/organizations/${organization.slug}/releases/${encodeURIComponent(
  217. params.release
  218. )}/meta/`,
  219. ],
  220. ];
  221. }
  222. get hasReleaseComparison() {
  223. return this.props.organization.features.includes('release-comparison');
  224. }
  225. componentDidMount() {
  226. this.removeGlobalDateTimeFromUrl();
  227. }
  228. componentDidUpdate(prevProps, prevContext: Record<string, any>) {
  229. super.componentDidUpdate(prevProps, prevContext);
  230. this.removeGlobalDateTimeFromUrl();
  231. }
  232. removeGlobalDateTimeFromUrl() {
  233. const {router, location} = this.props;
  234. const {start, end, statsPeriod, utc, ...restQuery} = location.query;
  235. if (!this.hasReleaseComparison) {
  236. return;
  237. }
  238. if (start || end || statsPeriod || utc) {
  239. router.replace({
  240. ...location,
  241. query: restQuery,
  242. });
  243. }
  244. }
  245. renderError(...args) {
  246. const has404Errors = Object.values(this.state.errors).find(e => e?.status === 404);
  247. if (has404Errors) {
  248. // This catches a 404 coming from the release endpoint and displays a custom error message.
  249. return (
  250. <PageContent>
  251. <Alert type="error" icon={<IconWarning />}>
  252. {t('This release could not be found.')}
  253. </Alert>
  254. </PageContent>
  255. );
  256. }
  257. return super.renderError(...args);
  258. }
  259. isProjectMissingInUrl() {
  260. const projectId = this.props.location.query.project;
  261. return !projectId || typeof projectId !== 'string';
  262. }
  263. renderLoading() {
  264. return (
  265. <PageContent>
  266. <LoadingIndicator />
  267. </PageContent>
  268. );
  269. }
  270. renderProjectsFooterMessage() {
  271. return (
  272. <ProjectsFooterMessage>
  273. <IconInfo size="xs" /> {t('Only projects with this release are visible.')}
  274. </ProjectsFooterMessage>
  275. );
  276. }
  277. renderBody() {
  278. const {organization, params, router, location, selection} = this.props;
  279. const {releaseMeta} = this.state;
  280. if (!releaseMeta) {
  281. return null;
  282. }
  283. const {projects} = releaseMeta;
  284. const isFreshRelease = moment(releaseMeta.released).isAfter(
  285. moment().subtract(24, 'hours')
  286. );
  287. const defaultStatsPeriod = isFreshRelease
  288. ? DEFAULT_FRESH_RELEASE_STATS_PERIOD
  289. : DEFAULT_STATS_PERIOD;
  290. if (this.isProjectMissingInUrl()) {
  291. return (
  292. <PickProjectToContinue
  293. projects={projects.map(({id, slug}) => ({
  294. id: String(id),
  295. slug,
  296. }))}
  297. router={router}
  298. nextPath={{
  299. pathname: `/organizations/${organization.slug}/releases/${encodeURIComponent(
  300. params.release
  301. )}/`,
  302. }}
  303. noProjectRedirectPath={`/organizations/${organization.slug}/releases/`}
  304. />
  305. );
  306. }
  307. return (
  308. <GlobalSelectionHeader
  309. lockedMessageSubject={t('release')}
  310. shouldForceProject={projects.length === 1}
  311. forceProject={
  312. projects.length === 1 ? {...projects[0], id: String(projects[0].id)} : undefined
  313. }
  314. specificProjectSlugs={projects.map(p => p.slug)}
  315. disableMultipleProjectSelection
  316. showProjectSettingsLink
  317. projectsFooterMessage={this.renderProjectsFooterMessage()}
  318. defaultSelection={{
  319. datetime: {
  320. start: null,
  321. end: null,
  322. utc: false,
  323. period: defaultStatsPeriod,
  324. },
  325. }}
  326. showDateSelector={!this.hasReleaseComparison}
  327. >
  328. <ReleaseHealthRequest
  329. releases={[params.release]}
  330. organization={organization}
  331. selection={selection}
  332. location={location}
  333. display={[DisplayOption.SESSIONS, DisplayOption.USERS]}
  334. defaultStatsPeriod={defaultStatsPeriod}
  335. disable={this.hasReleaseComparison}
  336. >
  337. {({isHealthLoading, getHealthData}) => (
  338. <ReleasesDetail
  339. {...this.props}
  340. releaseMeta={releaseMeta}
  341. defaultStatsPeriod={defaultStatsPeriod}
  342. getHealthData={getHealthData}
  343. isHealthLoading={isHealthLoading}
  344. />
  345. )}
  346. </ReleaseHealthRequest>
  347. </GlobalSelectionHeader>
  348. );
  349. }
  350. }
  351. const StyledPageContent = styled(PageContent)`
  352. padding: 0;
  353. `;
  354. const ProjectsFooterMessage = styled('div')`
  355. display: grid;
  356. align-items: center;
  357. grid-template-columns: min-content 1fr;
  358. grid-gap: ${space(1)};
  359. `;
  360. export {ReleaseContext, ReleasesDetailContainer};
  361. export default withGlobalSelection(withOrganization(ReleasesDetailContainer));