Skip to content
This repository has been archived by the owner on Aug 29, 2022. It is now read-only.

Improves progress percent calculation #259

Merged
merged 3 commits into from
Oct 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Deferred.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,9 @@
DBABD0BC203F2E3E00C50896 /* Atomics.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBABD0BA203F2E3E00C50896 /* Atomics.swift */; };
DBABD0BD203F2E3E00C50896 /* Atomics.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBABD0BA203F2E3E00C50896 /* Atomics.swift */; };
DBABD0BE203F2E3E00C50896 /* Atomics.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBABD0BA203F2E3E00C50896 /* Atomics.swift */; };
DBEC962B216FF229004CF0FC /* TaskProgressTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBEC962A216FF229004CF0FC /* TaskProgressTests.swift */; };
DBEC962C216FF229004CF0FC /* TaskProgressTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBEC962A216FF229004CF0FC /* TaskProgressTests.swift */; };
DBEC962D216FF229004CF0FC /* TaskProgressTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBEC962A216FF229004CF0FC /* TaskProgressTests.swift */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -311,6 +314,7 @@
DBA01B0C2071E6FF00083CD0 /* FuturePeek.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FuturePeek.swift; sourceTree = "<group>"; };
DBABD0BA203F2E3E00C50896 /* Atomics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Atomics.swift; sourceTree = "<group>"; };
DBC742631DC2F6D4002FB30D /* FutureEveryMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FutureEveryMap.swift; sourceTree = "<group>"; };
DBEC962A216FF229004CF0FC /* TaskProgressTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TaskProgressTests.swift; sourceTree = "<group>"; };
EBEB828C1DC4A79A00B7E089 /* TaskComprehensiveTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TaskComprehensiveTests.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

Expand Down Expand Up @@ -483,6 +487,7 @@
DB55F1F71D96968E00FC1439 /* ResultRecoveryTests.swift */,
DB55F1FD1D96968E00FC1439 /* TaskAsyncTests.swift */,
EBEB828C1DC4A79A00B7E089 /* TaskComprehensiveTests.swift */,
DBEC962A216FF229004CF0FC /* TaskProgressTests.swift */,
DB78F5EB215C4C5700D07CC6 /* TaskProtocolTests.swift */,
DB55F1F81D96968E00FC1439 /* TaskResultTests.swift */,
DB55F1FC1D96968E00FC1439 /* TaskTests.swift */,
Expand Down Expand Up @@ -804,6 +809,7 @@
DB126D641E5368B900054E95 /* FutureTests.swift in Sources */,
DB126D661E5368B900054E95 /* ProtectedTests.swift in Sources */,
DB126D6E1E5368B900054E95 /* TaskAsyncTests.swift in Sources */,
DBEC962B216FF229004CF0FC /* TaskProgressTests.swift in Sources */,
DB34FC942096DCE1005D5B82 /* FilledDeferredTests.swift in Sources */,
DB126D6D1E5368B900054E95 /* TaskTests.swift in Sources */,
DB126D621E5368B900054E95 /* FutureCustomExecutorTests.swift in Sources */,
Expand Down Expand Up @@ -872,6 +878,7 @@
DB126D741E5368B900054E95 /* FutureTests.swift in Sources */,
DB126D761E5368B900054E95 /* ProtectedTests.swift in Sources */,
DB126D7E1E5368B900054E95 /* TaskAsyncTests.swift in Sources */,
DBEC962C216FF229004CF0FC /* TaskProgressTests.swift in Sources */,
DB34FC952096DCE1005D5B82 /* FilledDeferredTests.swift in Sources */,
DB126D7D1E5368B900054E95 /* TaskTests.swift in Sources */,
DB126D721E5368B900054E95 /* FutureCustomExecutorTests.swift in Sources */,
Expand Down Expand Up @@ -940,6 +947,7 @@
DB126D841E5368BA00054E95 /* FutureTests.swift in Sources */,
DB126D861E5368BA00054E95 /* ProtectedTests.swift in Sources */,
DB126D8E1E5368BA00054E95 /* TaskAsyncTests.swift in Sources */,
DBEC962D216FF229004CF0FC /* TaskProgressTests.swift in Sources */,
DB34FC962096DCE1005D5B82 /* FilledDeferredTests.swift in Sources */,
DB126D8D1E5368BA00054E95 /* TaskTests.swift in Sources */,
DB126D821E5368BA00054E95 /* FutureCustomExecutorTests.swift in Sources */,
Expand Down
136 changes: 77 additions & 59 deletions Sources/Task/TaskProgress.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,36 +21,18 @@ import Deferred.Atomics
/// tree.
private final class ProxyProgress: Progress {

@objc dynamic private let observee: Progress
private var token: Observation?
@objc dynamic let observee: Progress
lazy var token = Observation(forUpdating: self)

init(attachingTo observee: Progress) {
self.observee = observee
super.init(parent: .current(), userInfo: nil)
token = Observation(observing: observee, observer: self)
super.init(parent: .current())
totalUnitCount = 100
token.activate(observing: observee)
}

deinit {
token?.invalidate(observing: observee)
}

private func inheritCancelled() {
if observee.isCancelled {
super.cancel()
}
}

private func inheritPaused() {
if observee.isPaused {
super.pause()
} else if #available(macOS 10.11, iOS 9.0, watchOS 2.0, tvOS 9.0, *) {
super.resume()
}
}

private func inheritValue(forKeyPath keyPath: String?) {
guard let keyPath = keyPath else { return }
setValue(observee.value(forKeyPath: keyPath), forKeyPath: keyPath)
token.invalidate(observing: observee)
}

// MARK: - Derived values
Expand All @@ -68,9 +50,9 @@ private final class ProxyProgress: Progress {
observee.resume()
}

@objc static var keyPathsForValuesAffectingUserInfo: Set<String> {
return [ #keyPath(observee.userInfo) ]
}
@objc static let keyPathsForValuesAffectingUserInfo: Set<String> = [
#keyPath(observee.userInfo)
]

override var userInfo: [ProgressUserInfoKey: Any] {
return observee.userInfo
Expand All @@ -82,43 +64,73 @@ private final class ProxyProgress: Progress {

// MARK: - KVO babysitting

func inheritFraction() {
completedUnitCount = observee.isIndeterminate ? -1 : Int64(observee.fractionCompleted * Double(totalUnitCount))
}

func inheritAttribute(_ value: Any?, forKeyPath keyPath: String) {
setValue(value, forKeyPath: keyPath)
}

func inheritCancelled() {
if observee.isCancelled {
super.cancel()
}
}

func inheritPaused() {
if observee.isPaused {
super.pause()
} else if #available(macOS 10.11, iOS 9.0, watchOS 2.0, tvOS 9.0, *) {
super.resume()
}
}

/// A side-table object to weakify the progress observer and prevent
/// delivery of notifications after deinit.
private final class Observation: NSObject {
private static var cancelledContext = false
private static var pausedContext = false
private static var attributesContext = false
private static let attributes = [
#keyPath(Progress.completedUnitCount),
#keyPath(Progress.totalUnitCount),
final class Observation: NSObject {
static var fractionContext = false
static var attributesContext = false
static var cancelledContext = false
static var pausedContext = false

static let fractionKeyPaths = [
#keyPath(Progress.fractionCompleted),
#keyPath(Progress.isIndeterminate)
]

static let attributesKeyPaths = [
#keyPath(Progress.localizedDescription),
#keyPath(Progress.localizedAdditionalDescription),
#keyPath(Progress.cancellable),
#keyPath(Progress.pausable),
#keyPath(Progress.kind)
]

private struct State: OptionSet {
struct State: OptionSet {
let rawValue: UInt8
static let ready = State(rawValue: 1 << 0)
static let observing = State(rawValue: 1 << 1)
static let cancellable: State = [.ready, .observing]
static let cancelled = State(rawValue: 1 << 2)
}

private var state = UInt8() // see State
private weak var observer: ProxyProgress?
var state = UInt8() // see State
weak var observer: ProxyProgress?

init(observing observee: Progress, observer: ProxyProgress) {
init(forUpdating observer: ProxyProgress) {
self.observer = observer
bnr_atomic_init(&state, State.ready.rawValue)
super.init()
activate(observing: observee)
}

func activate(observing observee: Progress) {
for key in Observation.attributes {
observee.addObserver(self, forKeyPath: key, options: .initial, context: &Observation.attributesContext)
for key in Observation.fractionKeyPaths {
observee.addObserver(self, forKeyPath: key, options: .initial, context: &Observation.fractionContext)
}

for key in Observation.attributesKeyPaths {
observee.addObserver(self, forKeyPath: key, options: [ .initial, .new ], context: &Observation.attributesContext)
}
observee.addObserver(self, forKeyPath: #keyPath(Progress.cancelled), options: .initial, context: &Observation.cancelledContext)
observee.addObserver(self, forKeyPath: #keyPath(Progress.paused), options: .initial, context: &Observation.pausedContext)
Expand All @@ -131,24 +143,30 @@ private final class ProxyProgress: Progress {
guard !oldState.isStrictSuperset(of: .cancellable) else { return }
bnr_atomic_fetch_or(&state, State.cancelled.rawValue, .relaxed)

for key in Observation.attributes {
for key in Observation.fractionKeyPaths {
observee.removeObserver(self, forKeyPath: key, context: &Observation.fractionContext)
}

for key in Observation.attributesKeyPaths {
observee.removeObserver(self, forKeyPath: key, context: &Observation.attributesContext)
}
observee.removeObserver(self, forKeyPath: #keyPath(Progress.cancelled), context: &Observation.cancelledContext)
observee.removeObserver(self, forKeyPath: #keyPath(Progress.paused), context: &Observation.pausedContext)
}

override func observeValue(forKeyPath keyPath: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
let state = State(rawValue: bnr_atomic_load(&self.state, .relaxed))
guard state.contains(.ready), let observer = observer else { return }
// This would be prettier as a switch.
// https://bugs.swift.org/browse/SR-7877
if context == &Observation.cancelledContext {
if context == &Observation.fractionContext {
observer.inheritFraction()
} else if context == &Observation.attributesContext, let keyPath = keyPath {
observer.inheritAttribute(change?[.newKey], forKeyPath: keyPath)
} else if context == &Observation.cancelledContext {
observer.inheritCancelled()
} else if context == &Observation.pausedContext {
observer.inheritPaused()
} else if context == &Observation.attributesContext {
observer.inheritValue(forKeyPath: keyPath)
}
}
}
Expand Down Expand Up @@ -250,25 +268,24 @@ extension Progress {
creating a root node implicitly used by chaining calls.
**/

private extension ProgressUserInfoKey {
static let taskRootLock = ProgressUserInfoKey(rawValue: "com_bignerdranch_Deferred_taskRootLock")
}
private let taskRootLock = ProgressUserInfoKey(rawValue: "_DeferredTaskRootLock")
private let taskRootUnitCount = Int64(16)

extension Progress {
/// Wrap or re-wrap `progress` if necessary, suitable for becoming the
/// progress of a Task node.
static func taskRoot(for inner: Progress) -> Progress {
let current = Progress.current()
if inner == current || inner.userInfo[.taskRootLock] != nil {
if inner == current || inner.userInfo[taskRootLock] != nil {
// Task<Value> has already taken care of this at a deeper level.
return inner
} else if let root = current, root.userInfo[.taskRootLock] != nil {
} else if let root = current, root.userInfo[taskRootLock] != nil {
return root
} else {
// Otherwise, wrap it up as a Task<Value>-marked progress.
let outer = Progress(totalUnitCount: 1)
outer.setUserInfoObject(NSLock(), forKey: .taskRootLock)
outer.adoptChild(inner, orphaned: true, pendingUnitCount: 1)
let outer = Progress(totalUnitCount: taskRootUnitCount)
outer.setUserInfoObject(NSLock(), forKey: taskRootLock)
outer.adoptChild(inner, orphaned: true, pendingUnitCount: taskRootUnitCount)
return outer
}
}
Expand All @@ -281,16 +298,17 @@ extension TaskProtocol {
/// to not interfere with simultaneous mapping operations.
func preparedProgressForContinuedWork() -> Progress {
let inner = Progress.wrappingSuccess(of: self)
if let lock = inner.userInfo[.taskRootLock] as? NSLock {
let continuedWorkUnitCount = Int64(1)
if let lock = inner.userInfo[taskRootLock] as? NSLock {
lock.lock()
defer { lock.unlock() }

inner.totalUnitCount += 1
inner.totalUnitCount += continuedWorkUnitCount
return inner
} else {
let outer = Progress(totalUnitCount: 2)
outer.setUserInfoObject(NSLock(), forKey: .taskRootLock)
outer.adoptChild(inner, orphaned: false, pendingUnitCount: 1)
let outer = Progress(totalUnitCount: taskRootUnitCount + continuedWorkUnitCount)
outer.setUserInfoObject(NSLock(), forKey: taskRootLock)
outer.adoptChild(inner, orphaned: false, pendingUnitCount: taskRootUnitCount)
return outer
}
}
Expand Down
Loading