Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(TaskOperation): switch to using AsyncChannel from continuations #16

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions AsyncObjects.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Pod::Spec.new do |s|
}

s.dependency 'OrderedCollections', '~> 1.0.0'
s.dependency 'AsyncAlgorithms', '~> 0.1.0'
s.default_subspecs = :none

s.subspec 'Checked' do |ss|
Expand Down
26 changes: 26 additions & 0 deletions AsyncObjects.xcodeproj/AsyncAlgorithms_Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string/>
</dict>
</plist>
26 changes: 26 additions & 0 deletions AsyncObjects.xcodeproj/Collections_Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string/>
</dict>
</plist>
26 changes: 26 additions & 0 deletions AsyncObjects.xcodeproj/DequeModule_Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string/>
</dict>
</plist>
1,721 changes: 1,264 additions & 457 deletions AsyncObjects.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,33 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme LastUpgradeVersion = "9999" version = "1.3">
<BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BuildableName = "'lib$(TARGET_NAME)'"
BlueprintName = "AsyncObjects"
ReferencedContainer = "container:AsyncObjects.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "NO">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BuildableName = "'$(TARGET_NAME)'"
BlueprintName = "AsyncObjectsTests"
ReferencedContainer = "container:AsyncObjects.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<Scheme
LastUpgradeVersion = "9999"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "asyncobjects::AsyncObjects"
BuildableName = "AsyncObjects.framework"
BlueprintName = "AsyncObjects"
ReferencedContainer = "container:AsyncObjects.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "asyncobjects::AsyncObjectsTests"
BuildableName = "AsyncObjectsTests.xctest"
BlueprintName = "AsyncObjectsTests"
ReferencedContainer = "container:AsyncObjects.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
4 changes: 3 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import class Foundation.ProcessInfo

var dependencies: [Target.Dependency] = {
var dependencies: [Target.Dependency] = [
.product(name: "OrderedCollections", package: "swift-collections")
.product(name: "OrderedCollections", package: "swift-collections"),
.product(name: "AsyncAlgorithms", package: "swift-async-algorithms"),
]

if ProcessInfo.processInfo.environment["ASYNCOBJECTS_ENABLE_LOGGING_LEVEL"] != nil {
Expand Down Expand Up @@ -64,6 +65,7 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/apple/swift-collections.git", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-async-algorithms", from: "0.1.0"),
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-format", from: "0.50700.0"),
.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),
Expand Down
129 changes: 19 additions & 110 deletions Sources/AsyncObjects/TaskOperation.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Foundation
import Dispatch
import AsyncAlgorithms

/// An object that bridges asynchronous work under structured concurrency
/// to Grand Central Dispatch (GCD or `libdispatch`) as `Operation`.
Expand Down Expand Up @@ -28,8 +29,8 @@ import Dispatch
/// // or wait synchronously for completion
/// operation.waitUntilFinished()
/// ```
public final class TaskOperation<R: Sendable>: Operation, AsyncObject,
ContinuableCollection, Loggable, @unchecked Sendable
public final class TaskOperation<R: Sendable>: Operation, AsyncObject, Loggable,
@unchecked Sendable
{
/// The asynchronous action to perform as part of the operation..
private let underlyingAction: @Sendable () async throws -> R
Expand All @@ -40,6 +41,9 @@ public final class TaskOperation<R: Sendable>: Operation, AsyncObject,
/// synchronize data access and modifications.
@usableFromInline
internal let locker: Locker
/// The channel that controls the asynchronous wait
/// for operation completion.
internal let waiter = AsyncChannel<Void>()

/// A type representing a set of behaviors for the executed
/// task type and task completion behavior.
Expand Down Expand Up @@ -116,9 +120,8 @@ public final class TaskOperation<R: Sendable>: Operation, AsyncObject,
willChangeValue(forKey: "isFinished")
locker.perform {
_isFinished = newValue
guard newValue, !continuations.isEmpty else { return }
continuations.forEach { $1.resume() }
continuations = [:]
guard newValue else { return }
waiter.finish()
}
didChangeValue(forKey: "isFinished")
}
Expand Down Expand Up @@ -170,7 +173,7 @@ public final class TaskOperation<R: Sendable>: Operation, AsyncObject,

deinit {
execTask?.cancel()
locker.perform { self.continuations.forEach { $1.cancel() } }
waiter.finish()
}

/// Begins the execution of the operation.
Expand Down Expand Up @@ -222,99 +225,6 @@ public final class TaskOperation<R: Sendable>: Operation, AsyncObject,
}

// MARK: AsyncObject
/// The suspended tasks continuation type.
@usableFromInline
internal typealias Continuation = TrackedContinuation<
GlobalContinuation<Void, Error>
>
/// The continuations stored with an associated key for all the suspended task that are waiting for operation completion.
@usableFromInline
internal private(set) var continuations: [UUID: Continuation] = [:]

/// Add continuation with the provided key in `continuations` map.
///
/// - Parameters:
/// - continuation: The `continuation` to add.
/// - key: The key in the map.
/// - file: The file add request originates from (there's usually no need to pass it
/// explicitly as it defaults to `#fileID`).
/// - function: The function add request originates from (there's usually no need to
/// pass it explicitly as it defaults to `#function`).
/// - line: The line add request originates from (there's usually no need to pass it
/// explicitly as it defaults to `#line`).
/// - preinit: The pre-initialization handler to run
/// in the beginning of this method.
///
/// - Important: The pre-initialization handler must run
/// before any logic in this method.
@inlinable
internal func addContinuation(
_ continuation: Continuation,
withKey key: UUID,
file: String, function: String, line: UInt,
preinit: @Sendable () -> Void
) {
locker.perform {
preinit()
log("Adding", id: key, file: file, function: function, line: line)
guard !continuation.resumed else {
log(
"Already resumed, not tracking", id: key,
file: file, function: function, line: line
)
return
}

guard !isFinished else {
continuation.resume()
log(
"Resumed", id: key,
file: file, function: function, line: line
)
return
}

continuations[key] = continuation
log("Tracking", id: key, file: file, function: function, line: line)
}
}

/// Remove continuation associated with provided key
/// from `continuations` map.
///
/// - Parameters:
/// - continuation: The continuation to remove and cancel.
/// - key: The key in the map.
/// - file: The file remove request originates from (there's usually no need to pass it
/// explicitly as it defaults to `#fileID`).
/// - function: The function remove request originates from (there's usually no need to
/// pass it explicitly as it defaults to `#function`).
/// - line: The line remove request originates from (there's usually no need to pass it
/// explicitly as it defaults to `#line`).
@inlinable
internal func removeContinuation(
_ continuation: Continuation,
withKey key: UUID,
file: String, function: String, line: UInt
) {
locker.perform {
log("Removing", id: key, file: file, function: function, line: line)
continuations.removeValue(forKey: key)
guard !continuation.resumed else {
log(
"Already resumed, not cancelling", id: key,
file: file, function: function, line: line
)
return
}

continuation.cancel()
log(
"Cancelled", id: key,
file: file, function: function, line: line
)
}
}

/// Starts operation asynchronously
/// as part of a new top-level task on behalf of the current actor.
Expand Down Expand Up @@ -356,18 +266,17 @@ public final class TaskOperation<R: Sendable>: Operation, AsyncObject,
function: String = #function,
line: UInt = #line
) async throws {
guard !isFinished else {
log("Finished", file: file, function: function, line: line)
return
}
let id = UUID()
log("Waiting", id: id, file: file, function: function, line: line)
await waiter.send(())

let key = UUID()
log("Waiting", id: key, file: file, function: function, line: line)
try await withPromisedContinuation(
withKey: key,
file: file, function: function, line: line
)
log("Finished", id: key, file: file, function: function, line: line)
do {
try Task.checkCancellation()
log("Finished", id: id, file: file, function: function, line: line)
} catch {
log("Cancelled", id: id, file: file, function: function, line: line)
throw error
}
}
}

Expand Down