Skip to content

Conversation

MustafaHaddara
Copy link
Contributor

Fixes #744

Majority of the changes are in test/example code. The actual fix is quite small, but relies on calling task.value(forKey: "session") as? URLSession to get the associated session on a task.

Alternatives

Intercept Task Creation

One other approach we discussed in the sig was to intercept the task creation and call objc_setAssociatedObject on the task, if the session had an active delegate. We already do this here:

if session.configuration.identifier == nil {
objc_setAssociatedObject(task, "IsBackground", true, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return task

However, that blog of code isn't swizzling the URLSession.data(for:) or URLSession.data(from:) functions, which are used to create asynchronous tasks. We could start swizzling those functions as well, if we wanted to, but that felt like a riskier change.

Swizzle UISession

Honeycomb has an alternate URL instrumentation implementation that swizzles the URLSession and URLSessionTask constructors directly. This lets us get a much stronger handle on the sessions and tasks in a wider variety of cases. Switching to that approach would be more costly and time consuming, but may serve us in the long run since the implementation is simpler.

@ArielDemarco
Copy link
Contributor

The PR looks good to me!

The only thing I’d recommend is adding a few tests to cover the different NSURLSessionTask types that can be created (at least the ones this instrumentation handles). I think it’s especially worth testing because the solution relies on KVO of a variable that should exist across the many different NSURLSessionTask subclasses, and the test will help ensure nothing breaks across OS versions as time goes by.

That said, the PR is failing due to the examples added. It seems like there's a simple fix needed to wrap some API usages with @available

@MustafaHaddara MustafaHaddara force-pushed the experimental-proxy-delegate branch from 97b9221 to fc107b0 Compare April 22, 2025 14:17
@MustafaHaddara MustafaHaddara force-pushed the experimental-proxy-delegate branch from fc107b0 to f3f4732 Compare April 29, 2025 14:10
@MustafaHaddara MustafaHaddara force-pushed the experimental-proxy-delegate branch from cfb2fc2 to 51a57b4 Compare April 29, 2025 15:31
@MustafaHaddara
Copy link
Contributor Author

@ArielDemarco thanks for taking a look! I've fixed the tests for tvOS and watchOS, and added some tests for async upload and download tasks with a delegate.

@nachoBonafonte nachoBonafonte merged commit 5999e62 into open-telemetry:main Apr 30, 2025
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

URL Instrumentation prevents Session Delegates from being called in async contexts
3 participants