organizationContext.tsx 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import {createContext, type ReactNode, useEffect, useRef} from 'react';
  2. import * as Sentry from '@sentry/react';
  3. import {switchOrganization} from 'sentry/actionCreators/organizations';
  4. import {openSudo} from 'sentry/actionCreators/sudoModal';
  5. import {
  6. useBootstrapOrganizationQuery,
  7. useBootstrapProjectsQuery,
  8. useBootstrapTeamsQuery,
  9. } from 'sentry/bootstrap/bootstrapRequests';
  10. import {DEPLOY_PREVIEW_CONFIG} from 'sentry/constants';
  11. import ConfigStore from 'sentry/stores/configStore';
  12. import OrganizationsStore from 'sentry/stores/organizationsStore';
  13. import OrganizationStore from 'sentry/stores/organizationStore';
  14. import PageFiltersStore from 'sentry/stores/pageFiltersStore';
  15. import ProjectsStore from 'sentry/stores/projectsStore';
  16. import TeamStore from 'sentry/stores/teamStore';
  17. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  18. import type {Organization} from 'sentry/types/organization';
  19. import type {User} from 'sentry/types/user';
  20. import {useParams} from 'sentry/utils/useParams';
  21. interface OrganizationLoaderContextProps {
  22. bootstrapIsPending: boolean;
  23. }
  24. interface Props {
  25. children: ReactNode;
  26. }
  27. /**
  28. * Holds the current organization if loaded.
  29. */
  30. export const OrganizationContext = createContext<Organization | null>(null);
  31. /**
  32. * Holds a function to load the organization.
  33. */
  34. export const OrganizationLoaderContext = createContext<OrganizationLoaderContextProps>({
  35. bootstrapIsPending: false,
  36. });
  37. /**
  38. * Record if the organization was bootstrapped in the last 10 minutes
  39. */
  40. function setRecentBootstrapTag(orgSlug: string) {
  41. const previousBootstrapKey = `previous-bootstrap-${orgSlug}`;
  42. try {
  43. const previousBootstrapTime = localStorage.getItem(previousBootstrapKey);
  44. const isRecentBoot = previousBootstrapTime
  45. ? Date.now() - Number(previousBootstrapTime) < 10 * 60 * 1000
  46. : false;
  47. Sentry.setTag('is_recent_boot', isRecentBoot);
  48. localStorage.setItem(previousBootstrapKey, `${Date.now()}`);
  49. } catch {
  50. // Ignore errors
  51. }
  52. }
  53. /**
  54. * Context provider responsible for loading the organization into the
  55. * OrganizationStore if it is not already present.
  56. */
  57. export function OrganizationContextProvider({children}: Props) {
  58. const configStore = useLegacyStore(ConfigStore);
  59. const {organizations} = useLegacyStore(OrganizationsStore);
  60. const {organization, error} = useLegacyStore(OrganizationStore);
  61. const lastOrganizationSlug: string | null =
  62. configStore.lastOrganization ?? organizations[0]?.slug ?? null;
  63. const params = useParams<{orgId?: string}>();
  64. const spanRef = useRef<Sentry.Span | null>(null);
  65. // XXX(epurkhiser): When running in deploy preview mode customer domains are
  66. // not supported correctly. Do NOT use the customer domain from the params.
  67. const orgSlug = DEPLOY_PREVIEW_CONFIG
  68. ? lastOrganizationSlug
  69. : params.orgId || lastOrganizationSlug;
  70. const {isFetching: isOrganizationFetching} = useBootstrapOrganizationQuery(orgSlug);
  71. const {isFetching: isTeamsFetching} = useBootstrapTeamsQuery(orgSlug);
  72. const {isFetching: isProjectsFetching} = useBootstrapProjectsQuery(orgSlug);
  73. const bootstrapIsPending =
  74. isOrganizationFetching || isTeamsFetching || isProjectsFetching;
  75. useEffect(() => {
  76. // Clear stores when the org slug changes
  77. if (organization?.slug && organization?.slug !== orgSlug) {
  78. OrganizationStore.reset();
  79. ProjectsStore.reset();
  80. TeamStore.reset();
  81. PageFiltersStore.onReset();
  82. }
  83. }, [orgSlug, organization?.slug]);
  84. useEffect(() => {
  85. if (!orgSlug) {
  86. OrganizationStore.setNoOrganization();
  87. return;
  88. }
  89. if (bootstrapIsPending && !spanRef.current) {
  90. // Measure the time it takes to bootstrap all three requests
  91. setRecentBootstrapTag(orgSlug);
  92. spanRef.current = Sentry.startInactiveSpan({
  93. name: 'ui.bootstrap',
  94. op: 'ui.render',
  95. forceTransaction: true,
  96. });
  97. }
  98. if (!bootstrapIsPending && spanRef.current) {
  99. spanRef.current.end();
  100. spanRef.current = null;
  101. }
  102. }, [bootstrapIsPending, orgSlug]);
  103. // XXX(epurkhiser): User may be null in some scenarios at this point in app
  104. // boot. We should fix the types here in the future
  105. const user: User | null = configStore.user;
  106. // It may be possible for the user to use the sudo modal to load the organization.
  107. useEffect(() => {
  108. if (!error) {
  109. // If the user has an active staff session, the response will not return a
  110. // 403 but access scopes will be an empty list.
  111. if (user?.isSuperuser && user?.isStaff && organization?.access?.length === 0) {
  112. openSudo({
  113. isSuperuser: true,
  114. needsReload: true,
  115. closeEvents: 'none',
  116. closeButton: false,
  117. });
  118. }
  119. return;
  120. }
  121. if (user?.isSuperuser && error.status === 403) {
  122. openSudo({
  123. isSuperuser: true,
  124. needsReload: true,
  125. closeEvents: 'none',
  126. closeButton: false,
  127. });
  128. }
  129. // This `catch` can swallow up errors in development (and tests)
  130. // So let's log them. This may create some noise, especially the test case where
  131. // we specifically test this branch
  132. console.error(error); // eslint-disable-line no-console
  133. }, [user, error, organization]);
  134. // Switch organizations when the orgId changes
  135. const lastOrgId = useRef(orgSlug);
  136. useEffect(() => {
  137. if (orgSlug && lastOrgId.current !== orgSlug) {
  138. // Only switch on: org1 -> org2
  139. // Not on: undefined -> org1
  140. // Also avoid: org1 -> undefined -> org1
  141. if (lastOrgId.current) {
  142. switchOrganization();
  143. }
  144. lastOrgId.current = orgSlug;
  145. }
  146. }, [orgSlug]);
  147. return (
  148. <OrganizationLoaderContext.Provider value={{bootstrapIsPending}}>
  149. <OrganizationContext.Provider value={organization}>
  150. {children}
  151. </OrganizationContext.Provider>
  152. </OrganizationLoaderContext.Provider>
  153. );
  154. }