organization.tsx 5.9 KB

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