organizationContext.tsx 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import {
  2. Component,
  3. createContext,
  4. useCallback,
  5. useContext,
  6. useEffect,
  7. useRef,
  8. } from 'react';
  9. import {fetchOrganizationDetails} from 'sentry/actionCreators/organization';
  10. import {switchOrganization} from 'sentry/actionCreators/organizations';
  11. import {openSudo} from 'sentry/actionCreators/sudoModal';
  12. import {DEPLOY_PREVIEW_CONFIG} from 'sentry/constants';
  13. import {SentryPropTypeValidators} from 'sentry/sentryPropTypeValidators';
  14. import ConfigStore from 'sentry/stores/configStore';
  15. import OrganizationsStore from 'sentry/stores/organizationsStore';
  16. import OrganizationStore from 'sentry/stores/organizationStore';
  17. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  18. import {Organization, User} from 'sentry/types';
  19. import {metric} from 'sentry/utils/analytics';
  20. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  21. import useApi from 'sentry/utils/useApi';
  22. import {useParams} from 'sentry/utils/useParams';
  23. import {useRoutes} from 'sentry/utils/useRoutes';
  24. /**
  25. * Holds the current organization if loaded.
  26. */
  27. export const OrganizationContext = createContext<Organization | null>(null);
  28. /**
  29. * Holds a function to load the organization.
  30. */
  31. const OrganizationLoaderContext = createContext<null | (() => void)>(null);
  32. interface Props {
  33. children: React.ReactNode;
  34. }
  35. /**
  36. * There are still a number of places where we consume the legacy organization
  37. * context. So for now we still need a component that provides this.
  38. */
  39. class LegacyOrganizationContextProvider extends Component<{value: Organization | null}> {
  40. static childContextTypes = {
  41. organization: SentryPropTypeValidators.isOrganization,
  42. };
  43. getChildContext() {
  44. return {organization: this.props.value};
  45. }
  46. render() {
  47. return this.props.children;
  48. }
  49. }
  50. /**
  51. * Ensures that an organization is loaded when the hook is used. This will only
  52. * be done on first render and if an organization is not already loaded.
  53. */
  54. export function useEnsureOrganization() {
  55. const loadOrganization = useContext(OrganizationLoaderContext);
  56. // XXX(epurkhiser): The loadOrganization function is stable as long as the
  57. // organization slug is stable. A change to the organization slug will cause
  58. // the organization to be reloaded.
  59. useEffect(() => loadOrganization?.(), [loadOrganization]);
  60. }
  61. /**
  62. * Context provider responsible for loading the organization into the
  63. * OrganizationStore if it is not already present.
  64. *
  65. * This provider *does not* immediately attempt to load the organization. A
  66. * child component must be responsible for calling `useEnsureOrganization` to
  67. * have the organization loaded.
  68. */
  69. export function OrganizationContextProvider({children}: Props) {
  70. const api = useApi();
  71. const configStore = useLegacyStore(ConfigStore);
  72. const {organizations} = useLegacyStore(OrganizationsStore);
  73. const {organization, error} = useLegacyStore(OrganizationStore);
  74. const hasMadeFirstFetch = useRef(false);
  75. const lastOrganizationSlug: string | null =
  76. configStore.lastOrganization ?? organizations[0]?.slug ?? null;
  77. const routes = useRoutes();
  78. const params = useParams<{orgId?: string}>();
  79. // XXX(epurkhiser): When running in deploy preview mode customer domains are
  80. // not supported correctly. Do NOT use the customer domain from the params.
  81. const orgSlug = DEPLOY_PREVIEW_CONFIG
  82. ? lastOrganizationSlug
  83. : params.orgId || lastOrganizationSlug;
  84. // Provided to the OrganizationLoaderContext. Loads the organization if it is
  85. // not already present.
  86. const loadOrganization = useCallback(() => {
  87. // Nothing to do if we already have the organization loaded
  88. if (organization && organization.slug === orgSlug) {
  89. return;
  90. }
  91. if (!orgSlug) {
  92. return;
  93. }
  94. metric.mark({name: 'organization-details-fetch-start'});
  95. fetchOrganizationDetails(api, orgSlug, false, hasMadeFirstFetch.current);
  96. hasMadeFirstFetch.current = true;
  97. }, [api, orgSlug, organization]);
  98. // Take a measurement for when organization details are done loading and the
  99. // new state is applied
  100. useEffect(
  101. () => {
  102. if (organization === null) {
  103. return;
  104. }
  105. metric.measure({
  106. name: 'app.component.perf',
  107. start: 'organization-details-fetch-start',
  108. data: {
  109. name: 'org-details',
  110. route: getRouteStringFromRoutes(routes),
  111. organization_id: parseInt(organization.id, 10),
  112. },
  113. });
  114. },
  115. // Ignore the `routes` dependency for the metrics measurement
  116. // eslint-disable-next-line react-hooks/exhaustive-deps
  117. [organization]
  118. );
  119. // XXX(epurkhiser): User may be null in some scenarios at this point in app
  120. // boot. We should fix the types here in the future
  121. const user: User | null = configStore.user;
  122. // If we've had an error it may be possible for the user to use the sudo
  123. // modal to load the organization.
  124. useEffect(() => {
  125. if (!error) {
  126. return;
  127. }
  128. if (user?.isSuperuser && error.status === 403) {
  129. openSudo({isSuperuser: true, needsReload: true});
  130. }
  131. // This `catch` can swallow up errors in development (and tests)
  132. // So let's log them. This may create some noise, especially the test case where
  133. // we specifically test this branch
  134. console.error(error); // eslint-disable-line no-console
  135. }, [user, error]);
  136. // Switch organizations when the orgId changes
  137. const lastOrgId = useRef(orgSlug);
  138. useEffect(() => {
  139. if (orgSlug && lastOrgId.current !== orgSlug) {
  140. // Only switch on: org1 -> org2
  141. // Not on: undefined -> org1
  142. // Also avoid: org1 -> undefined -> org1
  143. if (lastOrgId.current) {
  144. switchOrganization();
  145. }
  146. lastOrgId.current = orgSlug;
  147. }
  148. }, [orgSlug]);
  149. return (
  150. <OrganizationLoaderContext.Provider value={loadOrganization}>
  151. <OrganizationContext.Provider value={organization}>
  152. <LegacyOrganizationContextProvider value={organization}>
  153. {children}
  154. </LegacyOrganizationContextProvider>
  155. </OrganizationContext.Provider>
  156. </OrganizationLoaderContext.Provider>
  157. );
  158. }