async.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { _optionalChain } from '@sentry/utils';
  2. import { setAsyncContextStrategy, ensureHubOnCarrier, getHubFromCarrier } from '@sentry/core';
  3. import { GLOBAL_OBJ, logger } from '@sentry/utils';
  4. import { DEBUG_BUILD } from './debug-build.js';
  5. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
  6. const MaybeGlobalAsyncLocalStorage = (GLOBAL_OBJ ).AsyncLocalStorage;
  7. let asyncStorage;
  8. /**
  9. * Sets the async context strategy to use AsyncLocalStorage which should be available in the edge runtime.
  10. */
  11. function setAsyncLocalStorageAsyncContextStrategy() {
  12. if (!MaybeGlobalAsyncLocalStorage) {
  13. DEBUG_BUILD &&
  14. logger.warn(
  15. "Tried to register AsyncLocalStorage async context strategy in a runtime that doesn't support AsyncLocalStorage.",
  16. );
  17. return;
  18. }
  19. if (!asyncStorage) {
  20. asyncStorage = new MaybeGlobalAsyncLocalStorage();
  21. }
  22. function getCurrentHub() {
  23. return asyncStorage.getStore();
  24. }
  25. function createNewHub(parent) {
  26. const carrier = {};
  27. ensureHubOnCarrier(carrier, parent);
  28. return getHubFromCarrier(carrier);
  29. }
  30. function runWithAsyncContext(callback, options) {
  31. const existingHub = getCurrentHub();
  32. if (existingHub && _optionalChain([options, 'optionalAccess', _ => _.reuseExisting])) {
  33. // We're already in an async context, so we don't need to create a new one
  34. // just call the callback with the current hub
  35. return callback();
  36. }
  37. const newHub = createNewHub(existingHub);
  38. return asyncStorage.run(newHub, () => {
  39. return callback();
  40. });
  41. }
  42. setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext });
  43. }
  44. export { setAsyncLocalStorageAsyncContextStrategy };
  45. //# sourceMappingURL=async.js.map