sentry-javascript
sentry-javascript copied to clipboard
Better scope management for async code
Currently, the @sentry/browser SDK has no mechanism to automatically clone the Hub (and, consequently, Scope), unlike @sentry/node that automatically clones a new hub per Node Domain -- and we use that to isolate state for Node server handling concurrent requests.
This means that, in particular for @sentry/browser, any kind of async code may end up accidentally mixing up state unless hubs are manually cloned and used per unit of concurrency.
This issue tracks improving automatic hub/scope management/propagation in @sentry/browser. As a possible solution we may use (an optional support for) Zone.js.
For example:
setTag('a', 'tag');
withScope((scope) => {
setTimeout(() => {
captureMessage('test'); // no tags
}, 0);
});
getCurrentHub().getScope().clear();
hub.withScope(async scope => {
console.log('scope1', scope);
scope.setTag('me', 'you');
hub.withScope(async scope => {
// will have tag me: you
console.log('scope2', scope);
await asyncOperation();
hub.withScope(async scope => {
// won't have tag me: you
console.log('scope3', scope);
await asyncOperation();
});
});
});
The problem is apparent when some code needs to get something from the current scope, for example here is our fetch instrumentation:
https://github.com/getsentry/sentry-javascript/blob/61eda62ed5df5654f93e34a4848fc9ae3fcac0f7/packages/tracing/src/browser/request.ts#L169-L178 https://github.com/getsentry/sentry-javascript/blob/61eda62ed5df5654f93e34a4848fc9ae3fcac0f7/packages/tracing/src/utils.ts#L54-L56
Because fetch is async, the "current scope" is not necessarily in the state that one would expect. In the example above, when we call getActiveTransaction(), the current hub/scope may have changed and lost reference to the current transaction.
This issue has gone three weeks without activity. In another week, I will close it.
But! If you comment or otherwise update it, I will reset the clock, and if you label it Status: Backlog or Status: In Progress, I will leave it alone ... forever!
"A weed is but an unloved flower." ― Ella Wheeler Wilcox 🥀
hope this can get some attention
More details of the scope propagation issues are documented here.
For anybody that had issues with this and is looking for a solution with a decent explanation look at my rabbit hole exploration. I don't understand these things are not properly mentioned or explained in the docs. I've been setting up Sentry for about 30 hours now and the docs have often been poor if you are not having a vanilla express setup 😢.
Are there any plans on addressing this? Out of the box my lambdas events are highly polluted by other events.
Hey @ccarse can you elaborate a bit more on how your events are polluted? Maybe there's something we can improve.
Turns out I was missing an await on an event handler and that was causing the issue. Once I fixed that it looks good now. Thanks!