apple / swift-corelibs-foundation

The Foundation Project, providing core utilities, internationalization, and OS independence
swift.org
Apache License 2.0
5.23k stars 1.12k forks source link

URLSession delegate method urlSession(_:task:didFinishCollecting:) is not invoked on Linux #4988

Open johnnzhou opened 1 week ago

johnnzhou commented 1 week ago

URLSession delegate method urlSession(_:task:didFinishCollecting:) is not invoked on Linux platform.

Steps to reproduce:

Given the following code snippet, the program will hang forever, since the didFinishCollecting delegate method is not called.

import Foundation
import FoundationNetworking

let group = DispatchGroup()
group.enter()

class URLSessionClient: NSObject {
    private lazy var session: URLSession = {
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
        return session
    }() 

    func start() {
        let url = URL(string: "https://www.apple.com")
        var request = URLRequest(url: url!)
        request.httpMethod = "GET"
        let dataTask = session.downloadTask(with: request)
        dataTask.resume()
    }
}

extension URLSessionClient: URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate {
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) {
        print("Complete")
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
        guard let metric = metrics.transactionMetrics.last else {
            print("No metric collected. Exit")
            return
        }
        group.leave()
        print("Metric: \(metric)")
    }
}

DispatchQueue.global().async {
    let client = URLSessionClient()
    client.start()
}
group.wait()

Platform

Ubuntu 22.04.4 LTS

Swift version

Swift version 5.10.1 (swift-5.10.1-RELEASE) Target: x86_64-unknown-linux-gnu