From b22dd411f9381ae1ea6f3d750784b8c03a8d7810 Mon Sep 17 00:00:00 2001 From: Ignacio Bonafonte Date: Wed, 18 Sep 2024 21:43:51 +0200 Subject: [PATCH] Avoid instrumenting background async tasks (#597) --- .../URLSession/URLSessionInstrumentation.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Sources/Instrumentation/URLSession/URLSessionInstrumentation.swift b/Sources/Instrumentation/URLSession/URLSessionInstrumentation.swift index 21db9360..a67920eb 100644 --- a/Sources/Instrumentation/URLSession/URLSessionInstrumentation.swift +++ b/Sources/Instrumentation/URLSession/URLSessionInstrumentation.swift @@ -7,7 +7,7 @@ import Foundation import OpenTelemetryApi import OpenTelemetrySdk #if canImport(FoundationNetworking) -import FoundationNetworking + import FoundationNetworking #endif struct NetworkRequestState { @@ -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)) @@ -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 {