api.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. import {browserHistory} from 'react-router';
  2. import * as Sentry from '@sentry/react';
  3. import Cookies from 'js-cookie';
  4. import * as qs from 'query-string';
  5. import {openSudo, redirectToProject} from 'sentry/actionCreators/modal';
  6. import {EXPERIMENTAL_SPA} from 'sentry/constants';
  7. import {
  8. PROJECT_MOVED,
  9. SUDO_REQUIRED,
  10. SUPERUSER_REQUIRED,
  11. } from 'sentry/constants/apiErrorCodes';
  12. import controlsilopatterns from 'sentry/data/controlsiloUrlPatterns';
  13. import {metric} from 'sentry/utils/analytics';
  14. import getCsrfToken from 'sentry/utils/getCsrfToken';
  15. import {uniqueId} from 'sentry/utils/guid';
  16. import RequestError from 'sentry/utils/requestError/requestError';
  17. import {sanitizePath} from 'sentry/utils/requestError/sanitizePath';
  18. import ConfigStore from './stores/configStore';
  19. import OrganizationStore from './stores/organizationStore';
  20. export class Request {
  21. /**
  22. * Is the request still in flight
  23. */
  24. alive: boolean;
  25. /**
  26. * Promise which will be resolved when the request has completed
  27. */
  28. requestPromise: Promise<Response>;
  29. /**
  30. * AbortController to cancel the in-flight request. This will not be set in
  31. * unsupported browsers.
  32. */
  33. aborter?: AbortController;
  34. constructor(requestPromise: Promise<Response>, aborter?: AbortController) {
  35. this.requestPromise = requestPromise;
  36. this.aborter = aborter;
  37. this.alive = true;
  38. }
  39. cancel() {
  40. this.alive = false;
  41. this.aborter?.abort();
  42. metric('app.api.request-abort', 1);
  43. }
  44. }
  45. export type ApiResult<Data = any> = [
  46. data: Data,
  47. statusText: string | undefined,
  48. resp: ResponseMeta | undefined,
  49. ];
  50. export type ResponseMeta<R = any> = {
  51. /**
  52. * Get a header value from the response
  53. */
  54. getResponseHeader: (header: string) => string | null;
  55. /**
  56. * The response body decoded from json
  57. */
  58. responseJSON: R;
  59. /**
  60. * The string value of the response
  61. */
  62. responseText: string;
  63. /**
  64. * The response status code
  65. */
  66. status: Response['status'];
  67. /**
  68. * The response status code text
  69. */
  70. statusText: Response['statusText'];
  71. };
  72. /**
  73. * Check if the requested method does not require CSRF tokens
  74. */
  75. function csrfSafeMethod(method?: string): boolean {
  76. // these HTTP methods do not require CSRF protection
  77. return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method ?? '');
  78. }
  79. /**
  80. * Check if we a request is going to the same or similar origin.
  81. * similar origins are those that share an ancestor. Example `sentry.sentry.io` and `us.sentry.io`
  82. * are similar origins, but sentry.sentry.io and sentry.example.io are not.
  83. */
  84. export function isSimilarOrigin(target: string, origin: string): boolean {
  85. const targetUrl = new URL(target, origin);
  86. const originUrl = new URL(origin);
  87. // If one of the domains is a child of the other.
  88. if (
  89. originUrl.hostname.endsWith(targetUrl.hostname) ||
  90. targetUrl.hostname.endsWith(originUrl.hostname)
  91. ) {
  92. return true;
  93. }
  94. // Check if the target and origin are on sibiling subdomains.
  95. const targetHost = targetUrl.hostname.split('.');
  96. const originHost = originUrl.hostname.split('.');
  97. // Remove the subdomains. If don't have at least 2 segments we aren't subdomains.
  98. targetHost.shift();
  99. originHost.shift();
  100. if (targetHost.length < 2 || originHost.length < 2) {
  101. return false;
  102. }
  103. return targetHost.join('.') === originHost.join('.');
  104. }
  105. // TODO: Need better way of identifying anonymous pages that don't trigger redirect
  106. const ALLOWED_ANON_PAGES = [
  107. /^\/accept\//,
  108. /^\/share\//,
  109. /^\/auth\/login\//,
  110. /^\/join-request\//,
  111. /^\/unsubscribe\//,
  112. ];
  113. /**
  114. * Return true if we should skip calling the normal error handler
  115. */
  116. const globalErrorHandlers: ((resp: ResponseMeta) => boolean)[] = [];
  117. export const initApiClientErrorHandling = () =>
  118. globalErrorHandlers.push((resp: ResponseMeta) => {
  119. const pageAllowsAnon = ALLOWED_ANON_PAGES.find(regex =>
  120. regex.test(window.location.pathname)
  121. );
  122. // Ignore error unless it is a 401
  123. if (!resp || resp.status !== 401 || pageAllowsAnon) {
  124. return false;
  125. }
  126. const code = resp?.responseJSON?.detail?.code;
  127. const extra = resp?.responseJSON?.detail?.extra;
  128. // 401s can also mean sudo is required or it's a request that is allowed to fail
  129. // Ignore if these are the cases
  130. if (
  131. [
  132. 'sudo-required',
  133. 'ignore',
  134. '2fa-required',
  135. 'app-connect-authentication-error',
  136. ].includes(code)
  137. ) {
  138. return false;
  139. }
  140. // If user must login via SSO, redirect to org login page
  141. if (code === 'sso-required') {
  142. window.location.assign(extra.loginUrl);
  143. return true;
  144. }
  145. if (code === 'member-disabled-over-limit') {
  146. browserHistory.replace(extra.next);
  147. return true;
  148. }
  149. // Otherwise, the user has become unauthenticated. Send them to auth
  150. Cookies.set('session_expired', '1');
  151. if (EXPERIMENTAL_SPA) {
  152. browserHistory.replace('/auth/login/');
  153. } else {
  154. window.location.reload();
  155. }
  156. return true;
  157. });
  158. /**
  159. * Construct a full request URL
  160. */
  161. function buildRequestUrl(baseUrl: string, path: string, options: RequestOptions) {
  162. let params: string;
  163. try {
  164. params = qs.stringify(options.query ?? []);
  165. } catch (err) {
  166. Sentry.withScope(scope => {
  167. scope.setExtra('path', path);
  168. scope.setExtra('query', options.query);
  169. Sentry.captureException(err);
  170. });
  171. throw err;
  172. }
  173. // Append the baseUrl if required
  174. let fullUrl = path.includes(baseUrl) ? path : baseUrl + path;
  175. // Apply path and domain transforms for hybrid-cloud
  176. fullUrl = resolveHostname(fullUrl, options.host);
  177. // Append query parameters
  178. if (params) {
  179. fullUrl += fullUrl.includes('?') ? `&${params}` : `?${params}`;
  180. }
  181. return fullUrl;
  182. }
  183. /**
  184. * Check if the API response says project has been renamed. If so, redirect
  185. * user to new project slug
  186. */
  187. // TODO(ts): refine this type later
  188. export function hasProjectBeenRenamed(response: ResponseMeta) {
  189. const code = response?.responseJSON?.detail?.code;
  190. // XXX(billy): This actually will never happen because we can't intercept the 302
  191. // jQuery ajax will follow the redirect by default...
  192. //
  193. // TODO(epurkhiser): We use fetch now, is the above comment still true?
  194. if (code !== PROJECT_MOVED) {
  195. return false;
  196. }
  197. const slug = response?.responseJSON?.detail?.extra?.slug;
  198. redirectToProject(slug);
  199. return true;
  200. }
  201. // TODO(ts): move this somewhere
  202. export type APIRequestMethod = 'POST' | 'GET' | 'DELETE' | 'PUT';
  203. type FunctionCallback<Args extends any[] = any[]> = (...args: Args) => void;
  204. export type RequestCallbacks = {
  205. /**
  206. * Callback for the request completing (success or error)
  207. */
  208. complete?: (resp: ResponseMeta, textStatus: string) => void;
  209. /**
  210. * Callback for the request failing with an error
  211. */
  212. // TODO(ts): Update this when sentry is mostly migrated to TS
  213. error?: FunctionCallback;
  214. /**
  215. * Callback for the request completing successfully
  216. */
  217. success?: (data: any, textStatus?: string, resp?: ResponseMeta) => void;
  218. };
  219. export type RequestOptions = RequestCallbacks & {
  220. /**
  221. * Values to attach to the body of the request.
  222. */
  223. data?: any;
  224. /**
  225. * Headers add to the request.
  226. */
  227. headers?: Record<string, string>;
  228. /**
  229. * The host the request should be made to.
  230. */
  231. host?: string;
  232. /**
  233. * The HTTP method to use when making the API request
  234. */
  235. method?: APIRequestMethod;
  236. /**
  237. * Because of the async nature of API requests, errors will happen outside of
  238. * the stack that initated the request. a preservedError can be passed to
  239. * coalesce the stacks together.
  240. */
  241. preservedError?: Error;
  242. /**
  243. * Query parameters to add to the requested URL.
  244. */
  245. query?: Record<string, any>;
  246. /**
  247. * By default, requests will be aborted anytime api.clear() is called,
  248. * which is commonly used on unmounts. When skipAbort is true, the
  249. * request is opted out of this behavior. Useful for when you still
  250. * want to cache a request on unmount.
  251. */
  252. skipAbort?: boolean;
  253. };
  254. type ClientOptions = {
  255. /**
  256. * The base URL path to prepend to API request URIs.
  257. */
  258. baseUrl?: string;
  259. /**
  260. * Credentials policy to apply to each request
  261. */
  262. credentials?: RequestCredentials;
  263. /**
  264. * Base set of headers to apply to each request
  265. */
  266. headers?: HeadersInit;
  267. };
  268. type HandleRequestErrorOptions = {
  269. id: string;
  270. path: string;
  271. requestOptions: Readonly<RequestOptions>;
  272. };
  273. /**
  274. * The API client is used to make HTTP requests to Sentry's backend.
  275. *
  276. * This is they preferred way to talk to the backend.
  277. */
  278. export class Client {
  279. baseUrl: string;
  280. activeRequests: Record<string, Request>;
  281. headers: HeadersInit;
  282. credentials?: RequestCredentials;
  283. static JSON_HEADERS = {
  284. Accept: 'application/json; charset=utf-8',
  285. 'Content-Type': 'application/json',
  286. };
  287. constructor(options: ClientOptions = {}) {
  288. this.baseUrl = options.baseUrl ?? '/api/0';
  289. this.headers = options.headers ?? Client.JSON_HEADERS;
  290. this.activeRequests = {};
  291. this.credentials = options.credentials ?? 'include';
  292. }
  293. wrapCallback<T extends any[]>(
  294. id: string,
  295. func: FunctionCallback<T> | undefined,
  296. cleanup: boolean = false
  297. ) {
  298. return (...args: T) => {
  299. const req = this.activeRequests[id];
  300. if (cleanup === true) {
  301. delete this.activeRequests[id];
  302. }
  303. if (!req?.alive) {
  304. return undefined;
  305. }
  306. // Check if API response is a 302 -- means project slug was renamed and user
  307. // needs to be redirected
  308. // @ts-expect-error
  309. if (hasProjectBeenRenamed(...args)) {
  310. return undefined;
  311. }
  312. // Call success callback
  313. return func?.apply(req, args);
  314. };
  315. }
  316. /**
  317. * Attempt to cancel all active fetch requests
  318. */
  319. clear() {
  320. Object.values(this.activeRequests).forEach(r => r.cancel());
  321. }
  322. handleRequestError(
  323. {id, path, requestOptions}: HandleRequestErrorOptions,
  324. response: ResponseMeta,
  325. textStatus: string,
  326. errorThrown: string
  327. ) {
  328. const code = response?.responseJSON?.detail?.code;
  329. const isSudoRequired = code === SUDO_REQUIRED || code === SUPERUSER_REQUIRED;
  330. let didSuccessfullyRetry = false;
  331. if (isSudoRequired) {
  332. openSudo({
  333. isSuperuser: code === SUPERUSER_REQUIRED,
  334. sudo: code === SUDO_REQUIRED,
  335. retryRequest: async () => {
  336. try {
  337. const data = await this.requestPromise(path, requestOptions);
  338. requestOptions.success?.(data);
  339. didSuccessfullyRetry = true;
  340. } catch (err) {
  341. requestOptions.error?.(err);
  342. }
  343. },
  344. onClose: () =>
  345. // If modal was closed, then forward the original response
  346. !didSuccessfullyRetry && requestOptions.error?.(response),
  347. });
  348. return;
  349. }
  350. // Call normal error callback
  351. const errorCb = this.wrapCallback<[ResponseMeta, string, string]>(
  352. id,
  353. requestOptions.error
  354. );
  355. errorCb?.(response, textStatus, errorThrown);
  356. }
  357. /**
  358. * Initate a request to the backend API.
  359. *
  360. * Consider using `requestPromise` for the async Promise version of this method.
  361. */
  362. request(path: string, options: Readonly<RequestOptions> = {}): Request {
  363. const method = options.method || (options.data ? 'POST' : 'GET');
  364. let fullUrl = buildRequestUrl(this.baseUrl, path, options);
  365. let data = options.data;
  366. if (data !== undefined && method !== 'GET' && !(data instanceof FormData)) {
  367. data = JSON.stringify(data);
  368. }
  369. // TODO(epurkhiser): Mimicking the old jQuery API, data could be a string /
  370. // object for GET requets. jQuery just sticks it onto the URL as query
  371. // parameters
  372. if (method === 'GET' && data) {
  373. const queryString = typeof data === 'string' ? data : qs.stringify(data);
  374. if (queryString.length > 0) {
  375. fullUrl = fullUrl + (fullUrl.includes('?') ? '&' : '?') + queryString;
  376. }
  377. }
  378. const id = uniqueId();
  379. const startMarker = `api-request-start-${id}`;
  380. metric.mark({name: startMarker});
  381. /**
  382. * Called when the request completes with a 2xx status
  383. */
  384. const successHandler = (
  385. resp: ResponseMeta,
  386. textStatus: string,
  387. responseData: any
  388. ) => {
  389. metric.measure({
  390. name: 'app.api.request-success',
  391. start: startMarker,
  392. data: {status: resp?.status},
  393. });
  394. if (options.success !== undefined) {
  395. this.wrapCallback<[any, string, ResponseMeta]>(id, options.success)(
  396. responseData,
  397. textStatus,
  398. resp
  399. );
  400. }
  401. };
  402. /**
  403. * Called when the request is non-2xx
  404. */
  405. const errorHandler = (
  406. resp: ResponseMeta,
  407. textStatus: string,
  408. errorThrown: string
  409. ) => {
  410. metric.measure({
  411. name: 'app.api.request-error',
  412. start: startMarker,
  413. data: {status: resp?.status},
  414. });
  415. this.handleRequestError(
  416. {id, path, requestOptions: options},
  417. resp,
  418. textStatus,
  419. errorThrown
  420. );
  421. };
  422. /**
  423. * Called when the request completes
  424. */
  425. const completeHandler = (resp: ResponseMeta, textStatus: string) =>
  426. this.wrapCallback<[ResponseMeta, string]>(
  427. id,
  428. options.complete,
  429. true
  430. )(resp, textStatus);
  431. // AbortController is optional, though most browser should support it.
  432. const aborter =
  433. typeof AbortController !== 'undefined' && !options.skipAbort
  434. ? new AbortController()
  435. : undefined;
  436. // GET requests may not have a body
  437. const body = method !== 'GET' ? data : undefined;
  438. const requestHeaders = new Headers({...this.headers, ...options.headers});
  439. // Do not set the X-CSRFToken header when making a request outside of the
  440. // current domain. Because we use subdomains we loosely compare origins
  441. if (!csrfSafeMethod(method) && isSimilarOrigin(fullUrl, window.location.origin)) {
  442. requestHeaders.set('X-CSRFToken', getCsrfToken());
  443. }
  444. const fetchRequest = fetch(fullUrl, {
  445. method,
  446. body,
  447. headers: requestHeaders,
  448. credentials: this.credentials,
  449. signal: aborter?.signal,
  450. });
  451. // XXX(epurkhiser): We migrated off of jquery, so for now we have a
  452. // compatibility layer which mimics that of the jquery response objects.
  453. fetchRequest
  454. .then(
  455. async response => {
  456. // The Response's body can only be resolved/used at most once.
  457. // So we clone the response so we can resolve the body content as text content.
  458. // Response objects need to be cloned before its body can be used.
  459. let responseJSON: any;
  460. let responseText: any;
  461. const {status, statusText} = response;
  462. let {ok} = response;
  463. let errorReason = 'Request not OK'; // the default error reason
  464. let twoHundredErrorReason;
  465. // Try to get text out of the response no matter the status
  466. try {
  467. responseText = await response.text();
  468. } catch (error) {
  469. twoHundredErrorReason = 'Failed awaiting response.text()';
  470. ok = false;
  471. if (error.name === 'AbortError') {
  472. errorReason = 'Request was aborted';
  473. } else {
  474. errorReason = error.toString();
  475. }
  476. }
  477. const responseContentType = response.headers.get('content-type');
  478. const isResponseJSON = responseContentType?.includes('json');
  479. const wasExpectingJson =
  480. requestHeaders.get('Accept') === Client.JSON_HEADERS.Accept;
  481. const isStatus3XX = status >= 300 && status < 400;
  482. if (status !== 204 && !isStatus3XX) {
  483. try {
  484. responseJSON = JSON.parse(responseText);
  485. } catch (error) {
  486. twoHundredErrorReason = 'Failed trying to parse responseText';
  487. if (error.name === 'AbortError') {
  488. ok = false;
  489. errorReason = 'Request was aborted';
  490. } else if (isResponseJSON && error instanceof SyntaxError) {
  491. // If the MIME type is `application/json` but decoding failed,
  492. // this should be an error.
  493. ok = false;
  494. errorReason = 'JSON parse error';
  495. } else if (
  496. // Empty responses from POST 201 requests are valid
  497. responseText?.length > 0 &&
  498. wasExpectingJson &&
  499. error instanceof SyntaxError
  500. ) {
  501. // Was expecting json but was returned something else. Possibly HTML.
  502. // Ideally this would not be a 200, but we should reject the promise
  503. ok = false;
  504. errorReason = 'JSON parse error. Possibly returned HTML';
  505. }
  506. }
  507. }
  508. const responseMeta: ResponseMeta = {
  509. status,
  510. statusText,
  511. responseJSON,
  512. responseText,
  513. getResponseHeader: (header: string) => response.headers.get(header),
  514. };
  515. // Respect the response content-type header
  516. const responseData = isResponseJSON ? responseJSON : responseText;
  517. if (ok) {
  518. successHandler(responseMeta, statusText, responseData);
  519. } else {
  520. // There's no reason we should be here with a 200 response, but we get
  521. // tons of events from this codepath with a 200 status nonetheless.
  522. // Until we know why, let's do what is essentially some very fancy print debugging.
  523. if (status === 200 && responseText) {
  524. const parameterizedPath = sanitizePath(path);
  525. const message = '200 treated as error';
  526. const scope = new Sentry.Scope();
  527. scope.setTags({endpoint: `${method} ${parameterizedPath}`, errorReason});
  528. scope.setExtras({
  529. twoHundredErrorReason,
  530. responseJSON,
  531. responseText,
  532. responseContentType,
  533. errorReason,
  534. });
  535. // Make sure all of these errors group, so we don't produce a bunch of noise
  536. scope.setFingerprint([message]);
  537. Sentry.captureException(
  538. new Error(`${message}: ${method} ${parameterizedPath}`),
  539. scope
  540. );
  541. }
  542. const shouldSkipErrorHandler =
  543. globalErrorHandlers.map(handler => handler(responseMeta)).filter(Boolean)
  544. .length > 0;
  545. if (!shouldSkipErrorHandler) {
  546. errorHandler(responseMeta, statusText, errorReason);
  547. }
  548. }
  549. completeHandler(responseMeta, statusText);
  550. },
  551. () => {
  552. // Ignore failed fetch calls or errors in the fetch request itself (e.g. cancelled requests)
  553. // Not related to errors in responses
  554. }
  555. )
  556. .catch(error => {
  557. // eslint-disable-next-line no-console
  558. console.error(error);
  559. Sentry.captureException(error);
  560. });
  561. const request = new Request(fetchRequest, aborter);
  562. this.activeRequests[id] = request;
  563. return request;
  564. }
  565. requestPromise<IncludeAllArgsType extends boolean>(
  566. path: string,
  567. {
  568. includeAllArgs,
  569. ...options
  570. }: {includeAllArgs?: IncludeAllArgsType} & Readonly<RequestOptions> = {}
  571. ): Promise<IncludeAllArgsType extends true ? ApiResult : any> {
  572. // Create an error object here before we make any async calls so that we
  573. // have a helpful stack trace if it errors
  574. //
  575. // This *should* get logged to Sentry only if the promise rejection is not handled
  576. // (since SDK captures unhandled rejections). Ideally we explicitly ignore rejection
  577. // or handle with a user friendly error message
  578. const preservedError = new Error('API Request Error');
  579. return new Promise((resolve, reject) =>
  580. this.request(path, {
  581. ...options,
  582. preservedError,
  583. success: (data, textStatus, resp) => {
  584. if (includeAllArgs) {
  585. resolve([data, textStatus, resp] as any);
  586. } else {
  587. resolve(data);
  588. }
  589. },
  590. error: (resp: ResponseMeta) => {
  591. const errorObjectToUse = new RequestError(
  592. options.method,
  593. path,
  594. preservedError,
  595. resp
  596. );
  597. // Although `this.request` logs all error responses, this error object can
  598. // potentially be logged by Sentry's unhandled rejection handler
  599. reject(errorObjectToUse);
  600. },
  601. })
  602. );
  603. }
  604. }
  605. export function resolveHostname(path: string, hostname?: string): string {
  606. const storeState = OrganizationStore.get();
  607. const configLinks = ConfigStore.get('links');
  608. hostname = hostname ?? '';
  609. if (!hostname && storeState.organization?.features.includes('frontend-domainsplit')) {
  610. const isControlSilo = detectControlSiloPath(path);
  611. if (!isControlSilo && configLinks.regionUrl) {
  612. hostname = configLinks.regionUrl;
  613. }
  614. if (isControlSilo && configLinks.sentryUrl) {
  615. hostname = configLinks.sentryUrl;
  616. }
  617. }
  618. // If we're making a request to the applications' root
  619. // domain, we can drop the domain as webpack devserver will add one.
  620. // TODO(hybridcloud) This can likely be removed when sentry.types.region.Region.to_url()
  621. // loses the monolith mode condition.
  622. if (window.__SENTRY_DEV_UI && hostname === configLinks.sentryUrl) {
  623. hostname = '';
  624. }
  625. // When running as yarn dev-ui we can't spread requests across domains because
  626. // of CORS. Instead we extract the subdomain from the hostname
  627. // and prepend the URL with `/region/$name` so that webpack-devserver proxy
  628. // can route requests to the regions.
  629. if (hostname && window.__SENTRY_DEV_UI) {
  630. const domainpattern = /https?\:\/\/([^.]*)\.sentry\.io/;
  631. const domainmatch = hostname.match(domainpattern);
  632. if (domainmatch) {
  633. hostname = '';
  634. path = `/region/${domainmatch[1]}${path}`;
  635. }
  636. }
  637. if (hostname) {
  638. path = `${hostname}${path}`;
  639. }
  640. return path;
  641. }
  642. function detectControlSiloPath(path: string): boolean {
  643. // We sometimes include querystrings in paths.
  644. // Using URL() to avoid handrolling URL parsing
  645. const url = new URL(path, 'https://sentry.io');
  646. path = url.pathname;
  647. path = path.startsWith('/') ? path.substring(1) : path;
  648. for (const pattern of controlsilopatterns) {
  649. if (pattern.test(path)) {
  650. return true;
  651. }
  652. }
  653. return false;
  654. }