├── .editorconfig ├── .github └── FUNDING.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── Package.swift ├── README.md ├── Sources └── XPCConnectionSession │ ├── XPCConnectionSession.swift │ ├── XPCReceivedConnectionMessage.swift │ └── XPCSession+Async.swift └── Tests └── XPCConnectionSessionTests └── XPCConnectionSessionTests.swift /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | indent_size = 4 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [mattmassicotte] 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, caste, color, religion, or sexual 11 | identity and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the overall 27 | community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or advances of 32 | any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email address, 36 | without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official e-mail address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | ## Enforcement 61 | 62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 63 | reported to the community leaders responsible for enforcement at 64 | support@chimehq.com. 65 | All complaints will be reviewed and investigated promptly and fairly. 66 | 67 | All community leaders are obligated to respect the privacy and security of the 68 | reporter of any incident. 69 | 70 | ## Enforcement Guidelines 71 | 72 | Community leaders will follow these Community Impact Guidelines in determining 73 | the consequences for any action they deem in violation of this Code of Conduct: 74 | 75 | ### 1. Correction 76 | 77 | **Community Impact**: Use of inappropriate language or other behavior deemed 78 | unprofessional or unwelcome in the community. 79 | 80 | **Consequence**: A private, written warning from community leaders, providing 81 | clarity around the nature of the violation and an explanation of why the 82 | behavior was inappropriate. A public apology may be requested. 83 | 84 | ### 2. Warning 85 | 86 | **Community Impact**: A violation through a single incident or series of 87 | actions. 88 | 89 | **Consequence**: A warning with consequences for continued behavior. No 90 | interaction with the people involved, including unsolicited interaction with 91 | those enforcing the Code of Conduct, for a specified period of time. This 92 | includes avoiding interactions in community spaces as well as external channels 93 | like social media. Violating these terms may lead to a temporary or permanent 94 | ban. 95 | 96 | ### 3. Temporary Ban 97 | 98 | **Community Impact**: A serious violation of community standards, including 99 | sustained inappropriate behavior. 100 | 101 | **Consequence**: A temporary ban from any sort of interaction or public 102 | communication with the community for a specified period of time. No public or 103 | private interaction with the people involved, including unsolicited interaction 104 | with those enforcing the Code of Conduct, is allowed during this period. 105 | Violating these terms may lead to a permanent ban. 106 | 107 | ### 4. Permanent Ban 108 | 109 | **Community Impact**: Demonstrating a pattern of violation of community 110 | standards, including sustained inappropriate behavior, harassment of an 111 | individual, or aggression toward or disparagement of classes of individuals. 112 | 113 | **Consequence**: A permanent ban from any sort of public interaction within the 114 | community. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 2.1, available at 120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 121 | 122 | Community Impact Guidelines were inspired by 123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 124 | 125 | For answers to common questions about this code of conduct, see the FAQ at 126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 127 | [https://www.contributor-covenant.org/translations][translations]. 128 | 129 | [homepage]: https://www.contributor-covenant.org 130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 131 | [Mozilla CoC]: https://github.com/mozilla/diversity 132 | [FAQ]: https://www.contributor-covenant.org/faq 133 | [translations]: https://www.contributor-covenant.org/translations 134 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2023, Chime 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | 3. Neither the name of the copyright holder nor the names of its 16 | contributors may be used to endorse or promote products derived from 17 | this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.6 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "XPCConnectionSession", 7 | platforms: [.macOS(.v11), .iOS(.v14)], 8 | products: [ 9 | .library(name: "XPCConnectionSession", targets: ["XPCConnectionSession"]), 10 | ], 11 | targets: [ 12 | .target( 13 | name: "XPCConnectionSession"), 14 | .testTarget( 15 | name: "XPCConnectionSessionTests", 16 | dependencies: ["XPCConnectionSession"]), 17 | ] 18 | ) 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # XPCConnectionSession 2 | Backwards-compatible implementation of XPCSession 3 | 4 | The idea here is to make a version of the new [XPCSession][xpcsession] class that can be used on older OSes. With this you can migrate your code to new structure without needing to bump your minimum OS version. When that time finally does come, minimal code changes should be required to move over to the real `XPCSession`. 5 | 6 | This thing is still pretty young, and is missing a lot of features. Plus, `XPCSession` is still in beta, and the API could change. But, I figured why not. 7 | 8 | Features: 9 | 10 | - Compatible with existing `NSXPCConnection` instances 11 | - Swift concurrency support 12 | - `XPCSession` extensions to add Swift concurrency support where possible 13 | 14 | Note: 15 | 16 | The wire protocol used here is not compatible with `XPCSession`. This means you cannot mix the two. 17 | 18 | ## Usage 19 | 20 | ```swift 21 | let connection = NSXPCConnection(serviceName: "com.yourcompany.YourService") 22 | let session = XPCConnectionSession(connection: connection) 23 | 24 | Task { 25 | let reply: String? = try? await session.send("hello") 26 | 27 | print("got back: \(reply)") 28 | } 29 | ``` 30 | 31 | ## Suggestions or Feedback 32 | 33 | We'd love to hear from you! Get in touch via an issue or pull request. 34 | 35 | Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. 36 | 37 | [xpcsession]: https://developer.apple.com/documentation/xpc/xpcsession 38 | -------------------------------------------------------------------------------- /Sources/XPCConnectionSession/XPCConnectionSession.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// The raw communication protocol used to transfer data over an NSXPCConnection. 4 | /// 5 | /// Both the remote and local systems must use this protocol. 6 | @objc public protocol XPCConnectionSessionCommunicationProtocol { 7 | typealias Reply = @Sendable (Data) -> Void 8 | 9 | func processMessage(_ data: Data) 10 | func processMessage(_ data: Data, reply: @escaping Reply) 11 | } 12 | 13 | enum XPCConnectionSessionError: Error { 14 | case serviceTypeMismatch 15 | case replyDecodeFailure(Error) 16 | } 17 | 18 | private final class IncomingHandler { 19 | var messageHandler: (XPCReceivedConnectionMessage) -> (Encodable)? 20 | 21 | init() { 22 | self.messageHandler = { _ in return nil } 23 | } 24 | } 25 | 26 | extension IncomingHandler: XPCConnectionSessionCommunicationProtocol { 27 | func processMessage(_ data: Data) { 28 | let message = XPCReceivedConnectionMessage(data: data, replyHandler: { _ in 29 | print("warning: dropping unexpected reply") 30 | }) 31 | 32 | let value = messageHandler(message) 33 | 34 | if value != nil { 35 | print("warning: returning non-nil from a message that does not expect a reply") 36 | } 37 | } 38 | 39 | func processMessage(_ data: Data, reply: @escaping XPCConnectionSessionCommunicationProtocol.Reply) { 40 | let message = XPCReceivedConnectionMessage(data: data, replyHandler: reply) 41 | 42 | let value = messageHandler(message) 43 | 44 | if value != nil { 45 | print("warning: returning non-nil from a message that does not expect a reply") 46 | } 47 | } 48 | } 49 | 50 | /// A type that emulates the behavior and API of `XPCSession`. 51 | public final class XPCConnectionSession: @unchecked Sendable { 52 | private let connection: NSXPCConnection 53 | private let queue = DispatchQueue(label: "com.chimehq.XPCConnectionSession") 54 | private let channelHandler = IncomingHandler() 55 | 56 | /// Initialize the session with an existing NSXPCConnection instance. 57 | /// 58 | /// The initializing session **must** never be used once this is done. Effectively, this is a consuming operation, but that is currently not possible to express. 59 | public init(connection: NSXPCConnection) { 60 | self.connection = connection 61 | 62 | precondition(connection.exportedInterface == nil) 63 | precondition(connection.exportedObject == nil) 64 | precondition(connection.remoteObjectInterface == nil) 65 | 66 | queue.async { 67 | let interface = NSXPCInterface(with: XPCConnectionSessionCommunicationProtocol.self) 68 | 69 | self.connection.exportedInterface = interface 70 | self.connection.exportedObject = self.channelHandler 71 | self.connection.remoteObjectInterface = interface 72 | 73 | self.connection.interruptionHandler = { 74 | print("interruped?") 75 | } 76 | 77 | self.connection.activate() 78 | } 79 | } 80 | 81 | public convenience init(serviceName: String) { 82 | self.init(connection: NSXPCConnection(serviceName: serviceName)) 83 | } 84 | 85 | public func activate() throws { 86 | connection.activate() 87 | } 88 | 89 | public func cancel() { 90 | connection.invalidate() 91 | } 92 | } 93 | 94 | extension XPCConnectionSession { 95 | public func send(_ message: Message) throws where Message : Encodable { 96 | let messageData = try JSONEncoder().encode(message) 97 | 98 | queue.async { 99 | guard let channel = self.connection.remoteObjectProxy as? XPCConnectionSessionCommunicationProtocol else { 100 | return 101 | } 102 | 103 | channel.processMessage(messageData) 104 | } 105 | } 106 | 107 | public func send(_ message: Message, replyHandler: @Sendable @escaping (Result) -> Void) throws where Message : Encodable, Reply : Decodable { 108 | let messageData = try JSONEncoder().encode(message) 109 | 110 | queue.async { 111 | let proxy = self.connection.remoteObjectProxyWithErrorHandler { error in 112 | replyHandler(.failure(error)) 113 | } 114 | 115 | guard let channel = proxy as? XPCConnectionSessionCommunicationProtocol else { 116 | replyHandler(.failure(XPCConnectionSessionError.serviceTypeMismatch)) 117 | return 118 | } 119 | 120 | channel.processMessage(messageData) { data in 121 | do { 122 | let reply = try JSONDecoder().decode(Reply.self, from: data) 123 | 124 | replyHandler(.success(reply)) 125 | } catch { 126 | replyHandler(.failure(XPCConnectionSessionError.replyDecodeFailure(error))) 127 | } 128 | } 129 | } 130 | } 131 | } 132 | 133 | extension XPCConnectionSession { 134 | public func setIncomingMessageHandler(_ incomingMessageHandler: @escaping (XPCReceivedConnectionMessage) -> (Encodable)?) { 135 | queue.async { 136 | // I'm not sure how, or even if it is possible to get rid of this warning and also maintain backwards compatibility 137 | self.channelHandler.messageHandler = incomingMessageHandler 138 | } 139 | } 140 | } 141 | 142 | extension XPCConnectionSession { 143 | /// Sends a message to the remote service. 144 | @_unsafeInheritExecutor 145 | public func send(_ message: Message) async throws -> Reply { 146 | try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in 147 | do { 148 | try send(message) { continuation.resume(with: $0) } 149 | } catch { 150 | continuation.resume(throwing: error) 151 | } 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /Sources/XPCConnectionSession/XPCReceivedConnectionMessage.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// Emulates the behavior of `XPCReceivedMessage`. 4 | public struct XPCReceivedConnectionMessage { 5 | private let data: Data 6 | private let replyHandler: XPCConnectionSessionCommunicationProtocol.Reply 7 | public let expectsReply: Bool 8 | public let isSync: Bool 9 | 10 | init(data: Data, replyHandler: @escaping XPCConnectionSessionCommunicationProtocol.Reply, expectsReply: Bool = true, isSync: Bool = false) { 11 | self.data = data 12 | self.replyHandler = replyHandler 13 | self.expectsReply = expectsReply 14 | self.isSync = isSync 15 | } 16 | 17 | public func decode(as type: T.Type = T.self) throws -> T where T : Decodable { 18 | return try JSONDecoder().decode(type, from: data) 19 | } 20 | 21 | public func reply(_ object: Message) where Message : Encodable { 22 | do { 23 | let content = try JSONEncoder().encode(object) 24 | 25 | replyHandler(content) 26 | } catch { 27 | print("failed to encode \(object): \(error)") 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Sources/XPCConnectionSession/XPCSession+Async.swift: -------------------------------------------------------------------------------- 1 | #if canImport(XPC) 2 | import XPC 3 | 4 | #if compiler(>=5.9) 5 | @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *) 6 | extension XPCSession { 7 | /// Sends a message over the session to the destination service asynchronously and returns the reply. 8 | @_unsafeInheritExecutor 9 | public func send(_ message: Message) async throws -> Reply { 10 | try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in 11 | do { 12 | try send(message) { continuation.resume(with: $0) } 13 | } catch { 14 | continuation.resume(throwing: error) 15 | } 16 | } 17 | } 18 | } 19 | #endif 20 | #endif 21 | -------------------------------------------------------------------------------- /Tests/XPCConnectionSessionTests/XPCConnectionSessionTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | import XPCConnectionSession 3 | 4 | final class TestService: XPCConnectionSessionCommunicationProtocol { 5 | func processMessage(_ data: Data) { 6 | fatalError() 7 | } 8 | 9 | func processMessage(_ data: Data, reply: @escaping Reply) { 10 | let value = try? JSONDecoder().decode(String.self, from: data) 11 | 12 | if value == "hello" { 13 | reply(try! JSONEncoder().encode("world")) 14 | } else { 15 | reply(Data()) 16 | } 17 | } 18 | } 19 | 20 | final class ServiceDelegate: NSObject, NSXPCListenerDelegate { 21 | func listener(_ listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool { 22 | newConnection.exportedInterface = NSXPCInterface(with: XPCConnectionSessionCommunicationProtocol.self) 23 | 24 | let exportedObject = TestService() 25 | newConnection.exportedObject = exportedObject 26 | 27 | newConnection.resume() 28 | 29 | return true 30 | } 31 | } 32 | 33 | final class XPCConnectionSessionTests: XCTestCase { 34 | func testSendMessage() async throws { 35 | let lister = NSXPCListener.anonymous() 36 | let delegate = ServiceDelegate() 37 | 38 | lister.delegate = delegate 39 | lister.activate() 40 | 41 | let connection = NSXPCConnection(listenerEndpoint: lister.endpoint) 42 | 43 | let session = XPCConnectionSession(connection: connection) 44 | 45 | throw XCTSkip("This is a cool idea, but I cannot get it work") 46 | let value: String = try await session.send("hello") 47 | 48 | XCTAssertEqual(value, "world") 49 | } 50 | } 51 | --------------------------------------------------------------------------------