Skip to content

Commit

Permalink
Avoid instrumenting background async tasks (#597)
Browse files Browse the repository at this point in the history
  • Loading branch information
nachoBonafonte authored Sep 18, 2024
1 parent ceeae94 commit b22dd41
Showing 1 changed file with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Foundation
import OpenTelemetryApi
import OpenTelemetrySdk
#if canImport(FoundationNetworking)
import FoundationNetworking
import FoundationNetworking
#endif

struct NetworkRequestState {
Expand Down Expand Up @@ -162,6 +162,11 @@ public class URLSessionInstrumentation {
}
}
self.setIdKey(value: sessionTaskId, for: task)

// We want to identify background tasks
if session.configuration.identifier == nil {
objc_setAssociatedObject(task, "IsBackground", true, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return task
}
let swizzledIMP = imp_implementationWithBlock(unsafeBitCast(block, to: AnyObject.self))
Expand Down Expand Up @@ -592,6 +597,15 @@ public class URLSessionInstrumentation {
return
}

// We cannot instrument async background tasks because they crash if you assign a delegate
if #available(OSX 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
if objc_getAssociatedObject(task, "IsBackground") is Bool {
guard Task.basePriority == nil else {
return
}
}
}

let taskId = idKeyForTask(task)
if let request = task.currentRequest {
queue.sync {
Expand Down

0 comments on commit b22dd41

Please sign in to comment.