hooks.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { _optionalChain } from '@sentry/utils';
  2. import { setAsyncContextStrategy, ensureHubOnCarrier, getHubFromCarrier } from '@sentry/core';
  3. import * as async_hooks from 'async_hooks';
  4. let asyncStorage;
  5. /**
  6. * Sets the async context strategy to use AsyncLocalStorage which requires Node v12.17.0 or v13.10.0.
  7. */
  8. function setHooksAsyncContextStrategy() {
  9. if (!asyncStorage) {
  10. asyncStorage = new (async_hooks ).AsyncLocalStorage();
  11. }
  12. function getCurrentHub() {
  13. return asyncStorage.getStore();
  14. }
  15. function createNewHub(parent) {
  16. const carrier = {};
  17. ensureHubOnCarrier(carrier, parent);
  18. return getHubFromCarrier(carrier);
  19. }
  20. function runWithAsyncContext(callback, options) {
  21. const existingHub = getCurrentHub();
  22. if (existingHub && _optionalChain([options, 'optionalAccess', _ => _.reuseExisting])) {
  23. // We're already in an async context, so we don't need to create a new one
  24. // just call the callback with the current hub
  25. return callback();
  26. }
  27. const newHub = createNewHub(existingHub);
  28. return asyncStorage.run(newHub, () => {
  29. return callback();
  30. });
  31. }
  32. setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext });
  33. }
  34. export { setHooksAsyncContextStrategy };
  35. //# sourceMappingURL=hooks.js.map