organization.tsx 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 {ResponseMeta} 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 {getPreloadedDataPromise} from 'sentry/utils/getPreloadedData';
  17. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  18. async function fetchOrg(
  19. api: Client,
  20. slug: string,
  21. usePreload?: boolean
  22. ): Promise<Organization> {
  23. const [org] = await getPreloadedDataPromise(
  24. 'organization',
  25. slug,
  26. () =>
  27. // This data should get preloaded in static/sentry/index.ejs
  28. // If this url changes make sure to update the preload
  29. api.requestPromise(`/organizations/${slug}/`, {
  30. includeAllArgs: true,
  31. query: {detailed: 0, include_feature_flags: 1},
  32. }),
  33. usePreload
  34. );
  35. if (!org) {
  36. throw new Error('retrieved organization is falsey');
  37. }
  38. FeatureFlagOverrides.singleton().loadOrg(org);
  39. OrganizationStore.onUpdate(org, {replace: true});
  40. setActiveOrganization(org);
  41. const scope = Sentry.getCurrentScope();
  42. // XXX(dcramer): this is duplicated in sdk.py on the backend
  43. scope.setTag('organization', org.id);
  44. scope.setTag('organization.slug', org.slug);
  45. scope.setContext('organization', {id: org.id, slug: org.slug});
  46. return org;
  47. }
  48. async function fetchProjectsAndTeams(
  49. slug: string,
  50. usePreload?: boolean
  51. ): Promise<
  52. [
  53. [Project[], string | undefined, XMLHttpRequest | ResponseMeta | undefined],
  54. [Team[], string | undefined, XMLHttpRequest | ResponseMeta | undefined],
  55. ]
  56. > {
  57. // Create a new client so the request is not cancelled
  58. const uncancelableApi = new Client();
  59. const projectsPromise = getPreloadedDataPromise(
  60. 'projects',
  61. slug,
  62. () =>
  63. // This data should get preloaded in static/sentry/index.ejs
  64. // If this url changes make sure to update the preload
  65. uncancelableApi.requestPromise(`/organizations/${slug}/projects/`, {
  66. includeAllArgs: true,
  67. query: {
  68. all_projects: 1,
  69. collapse: ['latestDeploys', 'unusedFeatures'],
  70. },
  71. }),
  72. usePreload
  73. );
  74. const teamsPromise = getPreloadedDataPromise(
  75. 'teams',
  76. slug,
  77. // This data should get preloaded in static/sentry/index.ejs
  78. // If this url changes make sure to update the preload
  79. () =>
  80. uncancelableApi.requestPromise(`/organizations/${slug}/teams/`, {
  81. includeAllArgs: true,
  82. }),
  83. usePreload
  84. );
  85. try {
  86. return await Promise.all([projectsPromise, teamsPromise]);
  87. } catch (err) {
  88. // It's possible these requests fail with a 403 if the user has a role with
  89. // insufficient access to projects and teams, but *can* access org details
  90. // (e.g. billing). An example of this is in org settings.
  91. //
  92. // Ignore 403s and bubble up other API errors
  93. if (err.status !== 403) {
  94. throw err;
  95. }
  96. }
  97. return [
  98. [[], undefined, undefined],
  99. [[], undefined, undefined],
  100. ];
  101. }
  102. /**
  103. * Fetches an organization's details
  104. *
  105. * @param api A reference to the api client
  106. * @param slug The organization slug
  107. * @param silent Should we silently update the organization (do not clear the
  108. * current organization in the store)
  109. * @param usePreload Should the preloaded data be used if available?
  110. */
  111. export function fetchOrganizationDetails(
  112. api: Client,
  113. slug: string,
  114. silent: boolean,
  115. usePreload?: boolean
  116. ) {
  117. if (!silent) {
  118. OrganizationStore.reset();
  119. ProjectsStore.reset();
  120. TeamStore.reset();
  121. PageFiltersStore.onReset();
  122. }
  123. const getErrorMessage = err => {
  124. if (typeof err.responseJSON?.detail === 'string') {
  125. return err.responseJSON?.detail;
  126. }
  127. if (typeof err.responseJSON?.detail?.message === 'string') {
  128. return err.responseJSON?.detail.message;
  129. }
  130. return null;
  131. };
  132. const loadOrganization = () => {
  133. return new Promise(async (resolve, reject) => {
  134. let org: Organization | undefined = undefined;
  135. try {
  136. org = await fetchOrg(api, slug, usePreload);
  137. } catch (err) {
  138. if (!err) {
  139. reject(err);
  140. return;
  141. }
  142. OrganizationStore.onFetchOrgError(err);
  143. if (err.status === 403 || err.status === 401) {
  144. const errMessage = getErrorMessage(err);
  145. if (errMessage) {
  146. addErrorMessage(errMessage);
  147. reject(errMessage);
  148. }
  149. return;
  150. }
  151. Sentry.captureException(err);
  152. }
  153. resolve(org);
  154. });
  155. };
  156. const loadTeamsAndProjects = () => {
  157. return new Promise(async resolve => {
  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. resolve([projects, teams]);
  170. });
  171. };
  172. return Promise.all([loadOrganization(), loadTeamsAndProjects()]);
  173. }