Fix race condition of reporting finished download

This commit is contained in:
ronaldheft
2022-08-08 12:39:55 -04:00
parent 30ae98c3de
commit 162eb9afad
+15 -4
View File
@@ -19,6 +19,11 @@ public class AbsDownloader: CAPPlugin, URLSessionDownloadDelegate {
queue.maxConcurrentOperationCount = 5 queue.maxConcurrentOperationCount = 5
return URLSession(configuration: .default, delegate: self, delegateQueue: queue) return URLSession(configuration: .default, delegate: self, delegateQueue: queue)
}() }()
private let progressStatusQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}()
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
handleDownloadTaskUpdate(downloadTask: downloadTask) { downloadItem, downloadItemPart in handleDownloadTaskUpdate(downloadTask: downloadTask) { downloadItem, downloadItemPart in
@@ -87,9 +92,16 @@ public class AbsDownloader: CAPPlugin, URLSessionDownloadDelegate {
// Handle a completed download // Handle a completed download
if ( downloadItem.isDoneDownloading() ) { if ( downloadItem.isDoneDownloading() ) {
// TODO: Prevent this block from firing multiple times // Prevent race condition when multiple parts finish downloading at the same time by using a queue
defer { Database.shared.removeDownloadItem(downloadItem) } self.progressStatusQueue.addOperation {
handleDownloadTaskCompleteFromDownloadItem(downloadItem) // Remove the download item after the operation completes
defer { Database.shared.removeDownloadItem(downloadItem) }
// Fetch the latest download item, so we know if it was removed in another thread
let downloadItem = Database.shared.getDownloadItem(downloadItemId: downloadItem.id!)
// We already processed this download item on another thread, skip it
guard let downloadItem = downloadItem else { return }
self.handleDownloadTaskCompleteFromDownloadItem(downloadItem)
}
} }
} catch { } catch {
NSLog("DownloadItemError") NSLog("DownloadItemError")
@@ -136,7 +148,6 @@ public class AbsDownloader: CAPPlugin, URLSessionDownloadDelegate {
self.notifyListeners("onItemDownloadComplete", data: statusNotification) self.notifyListeners("onItemDownloadComplete", data: statusNotification)
} }
} }
} }