organizationContext.tsx 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 type {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 lastOrganizationSlug: string | null =
  75. configStore.lastOrganization ?? organizations[0]?.slug ?? null;
  76. const routes = useRoutes();
  77. const params = useParams<{orgId?: string}>();
  78. // XXX(epurkhiser): When running in deploy preview mode customer domains are
  79. // not supported correctly. Do NOT use the customer domain from the params.
  80. const orgSlug = DEPLOY_PREVIEW_CONFIG
  81. ? lastOrganizationSlug
  82. : params.orgId || lastOrganizationSlug;
  83. // Provided to the OrganizationLoaderContext. Loads the organization if it is
  84. // not already present.
  85. const loadOrganization = useCallback(() => {
  86. // Nothing to do if we already have the organization loaded
  87. if (organization && organization.slug === orgSlug) {
  88. return;
  89. }
  90. if (!orgSlug) {
  91. return;
  92. }
  93. metric.mark({name: 'organization-details-fetch-start'});
  94. fetchOrganizationDetails(api, orgSlug, false, true);
  95. }, [api, orgSlug, organization]);
  96. // Take a measurement for when organization details are done loading and the
  97. // new state is applied
  98. useEffect(
  99. () => {
  100. if (organization === null) {
  101. return;
  102. }
  103. metric.measure({
  104. name: 'app.component.perf',
  105. start: 'organization-details-fetch-start',
  106. data: {
  107. name: 'org-details',
  108. route: getRouteStringFromRoutes(routes),
  109. organization_id: parseInt(organization.id, 10),
  110. },
  111. });
  112. },
  113. // Ignore the `routes` dependency for the metrics measurement
  114. // eslint-disable-next-line react-hooks/exhaustive-deps
  115. [organization]
  116. );
  117. // XXX(epurkhiser): User may be null in some scenarios at this point in app
  118. // boot. We should fix the types here in the future
  119. const user: User | null = configStore.user;
  120. // If we've had an error it may be possible for the user to use the sudo
  121. // modal to load the organization.
  122. useEffect(() => {
  123. if (!error) {
  124. return;
  125. }
  126. if (user?.isSuperuser && error.status === 403) {
  127. openSudo({isSuperuser: true, needsReload: true});
  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]);
  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={loadOrganization}>
  149. <OrganizationContext.Provider value={organization}>
  150. <LegacyOrganizationContextProvider value={organization}>
  151. {children}
  152. </LegacyOrganizationContextProvider>
  153. </OrganizationContext.Provider>
  154. </OrganizationLoaderContext.Provider>
  155. );
  156. }