domain.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { _optionalChain } from '@sentry/utils';
  2. import * as domain from 'domain';
  3. import { setAsyncContextStrategy, ensureHubOnCarrier, getHubFromCarrier, setHubOnCarrier } from '@sentry/core';
  4. function getActiveDomain() {
  5. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
  6. return (domain ).active ;
  7. }
  8. function getCurrentHub() {
  9. const activeDomain = getActiveDomain();
  10. // If there's no active domain, just return undefined and the global hub will be used
  11. if (!activeDomain) {
  12. return undefined;
  13. }
  14. ensureHubOnCarrier(activeDomain);
  15. return getHubFromCarrier(activeDomain);
  16. }
  17. function createNewHub(parent) {
  18. const carrier = {};
  19. ensureHubOnCarrier(carrier, parent);
  20. return getHubFromCarrier(carrier);
  21. }
  22. function runWithAsyncContext(callback, options) {
  23. const activeDomain = getActiveDomain();
  24. if (activeDomain && _optionalChain([options, 'optionalAccess', _ => _.reuseExisting])) {
  25. // We're already in a domain, so we don't need to create a new one, just call the callback with the current hub
  26. return callback();
  27. }
  28. const local = domain.create() ;
  29. const parentHub = activeDomain ? getHubFromCarrier(activeDomain) : undefined;
  30. const newHub = createNewHub(parentHub);
  31. setHubOnCarrier(local, newHub);
  32. return local.bind(() => {
  33. return callback();
  34. })();
  35. }
  36. /**
  37. * Sets the async context strategy to use Node.js domains.
  38. */
  39. function setDomainAsyncContextStrategy() {
  40. setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext });
  41. }
  42. export { setDomainAsyncContextStrategy };
  43. //# sourceMappingURL=domain.js.map