<commit_before>//
//  URLSessionManager.swift
//  Stage1st
//
//  Created by <NAME> on 24/08/2017.
//  Copyright © 2017 Renaissance. All rights reserved.
//

import WebKit
import CocoaLumberjack

class WebKitImageDownloader: NSObject, URLSessionDataDelegate {
    static let shared = WebKitImageDownloader()
    lazy var session = {
        URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
    }()

    var taskMap = [URLSessionDataTask: Any]()

    private override init() {
        super.init()
    }

    @available(iOS 11.0, *)
    func start(schemeTask: WKURLSchemeTask, with request: URLRequest) {
        let dataTask = session.dataTask(with: request)
        taskMap[dataTask] = schemeTask as Any
        dataTask.resume()
    }

    @available(iOS 11.0, *)
    func stop(schemeTask: WKURLSchemeTask) {
        for (theDataTask, theSchemeTask) in taskMap where (theSchemeTask as! WKURLSchemeTask) === schemeTask {
            taskMap.removeValue(forKey: theDataTask)
            theDataTask.cancel()
            break
        }
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        if #available(iOS 11.0, *) {
            if let schemeTask = taskMap[dataTask] as? WKURLSchemeTask, dataTask.state == .running {
                schemeTask.didReceive(response)
            }

        }
        completionHandler(.allow)
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        if #available(iOS 11.0, *) {
            if let schemeTask = taskMap[dataTask] as? WKURLSchemeTask, dataTask.state == .running {
                schemeTask.didReceive(data)
            }
        }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if #available(iOS 11.0, *) {
            if let schemeTask = taskMap[task as! URLSessionDataTask] as? WKURLSchemeTask {
                if let error = error {
                    schemeTask.didFailWithError(error)
                } else {
                    schemeTask.didFinish()
                }
            }

            taskMap.removeValue(forKey: task as! URLSessionDataTask)
        }
    }
}<commit_msg>Fix race condition in `WebKitImageDownloader`.<commit_after>//
//  URLSessionManager.swift
//  Stage1st
//
//  Created by <NAME> on 24/08/2017.
//  Copyright © 2017 Renaissance. All rights reserved.
//

import WebKit
import CocoaLumberjack

class WebKitImageDownloader: NSObject, URLSessionDataDelegate {
    static let shared = WebKitImageDownloader()
    lazy var session = {
        URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
    }()

    var taskMap = [URLSessionDataTask: Any]()

    private override init() {
        super.init()
    }

    @available(iOS 11.0, *)
    func start(schemeTask: WKURLSchemeTask, with request: URLRequest) {
        let dataTask = session.dataTask(with: request)
        taskMap[dataTask] = schemeTask as Any
        dataTask.resume()
    }

    @available(iOS 11.0, *)
    func stop(schemeTask: WKURLSchemeTask) {
        for (theDataTask, theSchemeTask) in taskMap where (theSchemeTask as! WKURLSchemeTask) === schemeTask {
            taskMap.removeValue(forKey: theDataTask)
            theDataTask.cancel()
            break
        }
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        if #available(iOS 11.0, *) {
            DispatchQueue.main.async { [weak self] in
                guard let strongSelf = self else { return }
                if let schemeTask = strongSelf.taskMap[dataTask] as? WKURLSchemeTask {
                    DDLogInfo("Task Receive Response \(schemeTask.request) \(dataTask.state == .running)")
                    schemeTask.didReceive(response)
                }
            }
        }
        completionHandler(.allow)
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        if #available(iOS 11.0, *) {
            DispatchQueue.main.async { [weak self] in
                guard let strongSelf = self else { return }
                if let schemeTask = strongSelf.taskMap[dataTask] as? WKURLSchemeTask {
                    DDLogInfo("Task Receive Data \(schemeTask.request) \(dataTask.state == .running)")
                    schemeTask.didReceive(data)
                }
            }
        }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if #available(iOS 11.0, *) {
            DispatchQueue.main.async { [weak self] in
                guard let strongSelf = self else { return }
                if let schemeTask = strongSelf.taskMap[task as! URLSessionDataTask] as? WKURLSchemeTask {
                    if let error = error {
                        DDLogInfo("Task Fail \(schemeTask.request) \(error)")
                        schemeTask.didFailWithError(error)
                    } else {
                        DDLogInfo("Task Finish \(schemeTask.request)")
                        schemeTask.didFinish()
                    }

                    strongSelf.taskMap.removeValue(forKey: task as! URLSessionDataTask)
                }
            }
        }
    }
}
{'fraction_non_alphanumeric': 0.09491954438618695, 'fraction_numerical': 0.010124751401193274, 'mean_word_length': 2.1647597254004576, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7469300', 'n_tokens_mistral': 1602, 'n_tokens_neox': 1517, 'n_words': 365}