index.tsx 11 KB

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