-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
fix(core): Return same value from startSpan as callback returns
#19300
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
s1gr1d
wants to merge
7
commits into
develop
Choose a base branch
from
sig/promise-startspan-types
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
d972fd1
handleCallbackErrors return type fix
s1gr1d 99ec5a2
with `has` object trap
s1gr1d 30a3131
remove proxy wrapping
s1gr1d 6ace6af
add tracing unit tests
s1gr1d 6915880
clean up test cases
s1gr1d cc40872
remove throw error
s1gr1d a729eb8
wip: Copy properties onto chained promises
isaacs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
79 changes: 79 additions & 0 deletions
79
...wser-integration-tests/suites/public-api/startSpan/thenable-with-extra-methods/subject.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| /** | ||
| * Test that verifies thenable objects with extra methods (like jQuery's jqXHR) | ||
| * preserve those methods when returned from Sentry.startSpan(). | ||
| * | ||
| * Example case: | ||
| * const jqXHR = Sentry.startSpan({ name: "test" }, () => $.ajax(...)); | ||
| * jqXHR.abort(); // Should work and not throw an error because of missing abort() method | ||
| */ | ||
|
|
||
| // Load jQuery from CDN | ||
| const script = document.createElement('script'); | ||
| script.src = 'https://code.jquery.com/jquery-3.7.1.min.js'; | ||
| script.integrity = 'sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo='; | ||
| script.crossOrigin = 'anonymous'; | ||
|
|
||
| script.onload = function () { | ||
| runTest(); | ||
| }; | ||
|
|
||
| script.onerror = function () { | ||
| window.jqXHRTestError = 'Failed to load jQuery'; | ||
| window.jqXHRMethodsPreserved = false; | ||
| }; | ||
|
|
||
| document.head.appendChild(script); | ||
|
|
||
| async function runTest() { | ||
| window.jqXHRAbortCalled = false; | ||
| window.jqXHRAbortResult = null; | ||
| window.jqXHRTestError = null; | ||
|
|
||
| try { | ||
| if (!window.jQuery) { | ||
| throw new Error('jQuery not loaded'); | ||
| } | ||
|
|
||
| const result = Sentry.startSpan({ name: 'test-jqxhr', op: 'http.client' }, () => { | ||
| // Make a real AJAX request with jQuery | ||
| return window.jQuery.ajax({ | ||
| url: 'https://httpbin.org/status/200', | ||
| method: 'GET', | ||
| timeout: 5000, | ||
| }); | ||
| }); | ||
|
|
||
| const hasAbort = typeof result.abort === 'function'; | ||
| const hasReadyState = 'readyState' in result; | ||
|
|
||
| if (hasAbort && hasReadyState) { | ||
| try { | ||
| result.abort(); | ||
| window.jqXHRAbortCalled = true; | ||
| window.jqXHRAbortResult = 'abort-successful'; | ||
| window.jqXHRMethodsPreserved = true; | ||
| } catch (e) { | ||
| console.log('abort() threw an error:', e); | ||
| window.jqXHRTestError = `abort() failed: ${e.message}`; | ||
| window.jqXHRMethodsPreserved = false; | ||
| } | ||
| } else { | ||
| window.jqXHRMethodsPreserved = false; | ||
| window.jqXHRTestError = 'jqXHR methods not preserved'; | ||
| } | ||
|
|
||
| // Since we aborted the request, it should be rejected | ||
| try { | ||
| await result; | ||
| window.jqXHRPromiseResolved = true; // Unexpected | ||
| } catch (err) { | ||
| // Expected: aborted request rejects | ||
| window.jqXHRPromiseResolved = false; | ||
| window.jqXHRPromiseRejected = true; | ||
| } | ||
| } catch (error) { | ||
| console.error('Test error:', error); | ||
| window.jqXHRTestError = error.message; | ||
| window.jqXHRMethodsPreserved = false; | ||
| } | ||
| } |
51 changes: 51 additions & 0 deletions
51
...browser-integration-tests/suites/public-api/startSpan/thenable-with-extra-methods/test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import { expect } from '@playwright/test'; | ||
| import { sentryTest } from '../../../../utils/fixtures'; | ||
| import { envelopeRequestParser, shouldSkipTracingTest, waitForTransactionRequest } from '../../../../utils/helpers'; | ||
|
|
||
| sentryTest('preserves extra methods on real jQuery jqXHR objects', async ({ getLocalTestUrl, page }) => { | ||
| if (shouldSkipTracingTest()) { | ||
| sentryTest.skip(); | ||
| } | ||
|
|
||
| const url = await getLocalTestUrl({ testDir: __dirname }); | ||
| const transactionPromise = waitForTransactionRequest(page); | ||
|
|
||
| await page.goto(url); | ||
|
|
||
| // Wait for jQuery to load | ||
| await page.waitForTimeout(1000); | ||
|
|
||
| const methodsPreserved = await page.evaluate(() => (window as any).jqXHRMethodsPreserved); | ||
| expect(methodsPreserved).toBe(true); | ||
|
|
||
| const abortCalled = await page.evaluate(() => (window as any).jqXHRAbortCalled); | ||
| expect(abortCalled).toBe(true); | ||
|
|
||
| const abortReturnValue = await page.evaluate(() => (window as any).jqXHRAbortResult); | ||
| expect(abortReturnValue).toBe('abort-successful'); | ||
|
|
||
| const testError = await page.evaluate(() => (window as any).jqXHRTestError); | ||
| expect(testError).toBeNull(); | ||
|
|
||
| const transaction = envelopeRequestParser(await transactionPromise); | ||
| expect(transaction.transaction).toBe('test-jqxhr'); | ||
| expect(transaction.spans).toBeDefined(); | ||
| }); | ||
|
|
||
| sentryTest('aborted request rejects promise correctly', async ({ getLocalTestUrl, page }) => { | ||
| if (shouldSkipTracingTest()) { | ||
| sentryTest.skip(); | ||
| } | ||
|
|
||
| const url = await getLocalTestUrl({ testDir: __dirname }); | ||
| await page.goto(url); | ||
|
|
||
| // Wait for jQuery to load | ||
| await page.waitForTimeout(1000); | ||
|
|
||
| const promiseRejected = await page.evaluate(() => (window as any).jqXHRPromiseRejected); | ||
| expect(promiseRejected).toBe(true); | ||
|
|
||
| const promiseResolved = await page.evaluate(() => (window as any).jqXHRPromiseResolved); | ||
| expect(promiseResolved).toBe(false); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| /** | ||
| * Copy the properties from a decorated promiselike object onto its chained | ||
| * actual promise. | ||
| */ | ||
| export const chainAndCopyPromiseLike = <V, T extends PromiseLike<V> & Record<string, unknown>>( | ||
| original: T, | ||
| onSuccess: (value: V) => void, | ||
| onError: (e: unknown) => void, | ||
| ): T => { | ||
| return copyProps( | ||
| original, | ||
| original.then( | ||
| value => { | ||
| onSuccess(value); | ||
| return value; | ||
| }, | ||
| err => { | ||
| onError(err); | ||
| throw err; | ||
| }, | ||
| ), | ||
| ) as T; | ||
| }; | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| const copyProps = <T extends Record<string, any>>(original: T, chained: T): T => { | ||
| for (const key in original) { | ||
| if (key in chained) continue; | ||
| const value = original[key]; | ||
| if (typeof value === 'function') { | ||
| Object.defineProperty(chained, key, { | ||
| value: (...args: unknown[]) => value.apply(original, args), | ||
| enumerable: true, | ||
| configurable: true, | ||
| writable: true, | ||
| }); | ||
| } else { | ||
| (chained as Record<string, unknown>)[key] = value; | ||
| } | ||
| } | ||
|
|
||
| return chained; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| import { chainAndCopyPromiseLike } from '../utils/chain-and-copy-promiselike'; | ||
| import { isThenable } from '../utils/is'; | ||
|
|
||
| /* eslint-disable */ | ||
|
|
@@ -62,7 +63,12 @@ export function handleCallbackErrors< | |
| * Maybe handle a promise rejection. | ||
| * This expects to be given a value that _may_ be a promise, or any other value. | ||
| * If it is a promise, and it rejects, it will call the `onError` callback. | ||
| * Other than this, it will generally return the given value as-is. | ||
| * | ||
| * For thenable objects with extra methods (like jQuery's jqXHR), | ||
| * this function preserves those methods by wrapping the original thenable in a Proxy | ||
| * that intercepts .then() calls to apply error handling while forwarding all other | ||
| * properties to the original object. | ||
| * This allows code like `startSpan(() => $.ajax(...)).abort()` to work correctly. | ||
| */ | ||
| function maybeHandlePromiseRejection<MaybePromise>( | ||
| value: MaybePromise, | ||
|
|
@@ -71,22 +77,21 @@ function maybeHandlePromiseRejection<MaybePromise>( | |
| onSuccess: (result: MaybePromise | AwaitedPromise<MaybePromise>) => void, | ||
| ): MaybePromise { | ||
| if (isThenable(value)) { | ||
| // @ts-expect-error - the isThenable check returns the "wrong" type here | ||
| return value.then( | ||
| res => { | ||
| return chainAndCopyPromiseLike( | ||
| value as MaybePromise & PromiseLike<Awaited<typeof value>> & Record<string, unknown>, | ||
| result => { | ||
| onFinally(); | ||
| onSuccess(res); | ||
| return res; | ||
| onSuccess(result as Awaited<MaybePromise>); | ||
| }, | ||
| e => { | ||
| onError(e); | ||
| err => { | ||
| onError(err); | ||
| onFinally(); | ||
| throw e; | ||
| }, | ||
| ); | ||
| ) as MaybePromise; | ||
| } else { | ||
| // Non-thenable value - call callbacks immediately and return as-is | ||
| onFinally(); | ||
| onSuccess(value); | ||
| } | ||
|
Comment on lines
+91
to
95
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As the |
||
|
|
||
| onFinally(); | ||
| onSuccess(value); | ||
| return value; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In this function we would always loop through the promise, even if it's not needed (it's an edge case that probably only jQuery has). Maybe we could guard calling this edge-case behavior by checking if it's a
jqXHRobject (by checking if it contains the properties and functions) 🤔https://api.jquery.com/jQuery.ajax/#jqXHR