organizationContext.tsx 6.1 KB

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