organization.tsx 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. // XXX(epurkhiser): Ensure the LatestContextStore is initialized before we set
  2. // the active org. Otherwise we will trigger an action that does nothing
  3. import 'sentry/stores/latestContextStore';
  4. import * as Sentry from '@sentry/react';
  5. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  6. import {setActiveOrganization} from 'sentry/actionCreators/organizations';
  7. import type {ApiResult} from 'sentry/api';
  8. import {Client} from 'sentry/api';
  9. import OrganizationStore from 'sentry/stores/organizationStore';
  10. import PageFiltersStore from 'sentry/stores/pageFiltersStore';
  11. import ProjectsStore from 'sentry/stores/projectsStore';
  12. import TeamStore from 'sentry/stores/teamStore';
  13. import type {Organization, Team} from 'sentry/types/organization';
  14. import type {Project} from 'sentry/types/project';
  15. import FeatureFlagOverrides from 'sentry/utils/featureFlagOverrides';
  16. import {
  17. addOrganizationFeaturesHandler,
  18. buildSentryFeaturesHandler,
  19. } from 'sentry/utils/featureFlags';
  20. import {getPreloadedDataPromise} from 'sentry/utils/getPreloadedData';
  21. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  22. import type RequestError from 'sentry/utils/requestError/requestError';
  23. async function fetchOrg(
  24. api: Client,
  25. slug: string,
  26. usePreload?: boolean
  27. ): Promise<Organization> {
  28. const [org] = await getPreloadedDataPromise(
  29. 'organization',
  30. slug,
  31. () =>
  32. // This data should get preloaded in static/sentry/index.ejs
  33. // If this url changes make sure to update the preload
  34. api.requestPromise(`/organizations/${slug}/`, {
  35. includeAllArgs: true,
  36. query: {detailed: 0, include_feature_flags: 1},
  37. }),
  38. usePreload
  39. );
  40. if (!org) {
  41. throw new Error('retrieved organization is falsey');
  42. }
  43. FeatureFlagOverrides.singleton().loadOrg(org);
  44. addOrganizationFeaturesHandler({
  45. organization: org,
  46. handler: buildSentryFeaturesHandler('feature.organizations:'),
  47. });
  48. OrganizationStore.onUpdate(org, {replace: true});
  49. setActiveOrganization(org);
  50. const scope = Sentry.getCurrentScope();
  51. // XXX(dcramer): this is duplicated in sdk.py on the backend
  52. scope.setTag('organization', org.id);
  53. scope.setTag('organization.slug', org.slug);
  54. scope.setContext('organization', {id: org.id, slug: org.slug});
  55. return org;
  56. }
  57. async function fetchProjectsAndTeams(
  58. slug: string,
  59. usePreload?: boolean
  60. ): Promise<[ApiResult<Project[]>, ApiResult<Team[]>]> {
  61. // Create a new client so the request is not cancelled
  62. const uncancelableApi = new Client();
  63. const projectsPromise = getPreloadedDataPromise(
  64. 'projects',
  65. slug,
  66. () =>
  67. // This data should get preloaded in static/sentry/index.ejs
  68. // If this url changes make sure to update the preload
  69. uncancelableApi.requestPromise(`/organizations/${slug}/projects/`, {
  70. includeAllArgs: true,
  71. query: {
  72. all_projects: 1,
  73. collapse: ['latestDeploys', 'unusedFeatures'],
  74. },
  75. }),
  76. usePreload
  77. );
  78. const teamsPromise = getPreloadedDataPromise(
  79. 'teams',
  80. slug,
  81. // This data should get preloaded in static/sentry/index.ejs
  82. // If this url changes make sure to update the preload
  83. () =>
  84. uncancelableApi.requestPromise(`/organizations/${slug}/teams/`, {
  85. includeAllArgs: true,
  86. }),
  87. usePreload
  88. );
  89. try {
  90. return await Promise.all([projectsPromise, teamsPromise]);
  91. } catch (err) {
  92. // It's possible these requests fail with a 403 if the user has a role with
  93. // insufficient access to projects and teams, but *can* access org details
  94. // (e.g. billing). An example of this is in org settings.
  95. //
  96. // Ignore 403s and bubble up other API errors
  97. if (err.status !== 403) {
  98. throw err;
  99. }
  100. }
  101. return [
  102. [[], undefined, undefined],
  103. [[], undefined, undefined],
  104. ];
  105. }
  106. /**
  107. * Fetches an organization's details
  108. *
  109. * @param api A reference to the api client
  110. * @param slug The organization slug
  111. * @param silent Should we silently update the organization (do not clear the
  112. * current organization in the store)
  113. * @param usePreload Should the preloaded data be used if available?
  114. */
  115. export async function fetchOrganizationDetails(
  116. api: Client,
  117. slug: string,
  118. silent: boolean,
  119. usePreload?: boolean
  120. ): Promise<void> {
  121. if (!silent) {
  122. OrganizationStore.reset();
  123. ProjectsStore.reset();
  124. TeamStore.reset();
  125. PageFiltersStore.onReset();
  126. }
  127. const getErrorMessage = (err: RequestError) => {
  128. if (typeof err.responseJSON?.detail === 'string') {
  129. return err.responseJSON?.detail;
  130. }
  131. if (typeof err.responseJSON?.detail?.message === 'string') {
  132. return err.responseJSON?.detail.message;
  133. }
  134. return null;
  135. };
  136. const loadOrganization = async () => {
  137. let org: Organization | undefined = undefined;
  138. try {
  139. org = await fetchOrg(api, slug, usePreload);
  140. } catch (err) {
  141. if (!err) {
  142. throw err;
  143. }
  144. OrganizationStore.onFetchOrgError(err);
  145. if (err.status === 403 || err.status === 401) {
  146. const errMessage = getErrorMessage(err);
  147. if (errMessage) {
  148. addErrorMessage(errMessage);
  149. throw errMessage;
  150. }
  151. return undefined;
  152. }
  153. Sentry.captureException(err);
  154. }
  155. return org;
  156. };
  157. const loadTeamsAndProjects = async () => {
  158. const [[projects], [teams, , resp]] = await fetchProjectsAndTeams(slug, usePreload);
  159. ProjectsStore.loadInitialData(projects ?? []);
  160. const teamPageLinks = resp?.getResponseHeader('Link');
  161. if (teamPageLinks) {
  162. const paginationObject = parseLinkHeader(teamPageLinks);
  163. const hasMore = paginationObject?.next?.results ?? false;
  164. const cursor = paginationObject.next?.cursor;
  165. TeamStore.loadInitialData(teams, hasMore, cursor);
  166. } else {
  167. TeamStore.loadInitialData(teams);
  168. }
  169. return [projects, teams];
  170. };
  171. await Promise.all([loadOrganization(), loadTeamsAndProjects()]);
  172. }