2 * Copyright (c) 2018 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 import CloudKit_Private
27 import CloudKitCodeProtobuf
31 // TODO: merge into CodeConnection
33 let CuttlefishPushTopicBundleIdentifier = "com.apple.security.cuttlefish"
35 struct CKInternalErrorMatcher {
40 // Match a CKError/CKInternalError
41 func ~= (pattern: CKInternalErrorMatcher, value: Error?) -> Bool {
42 guard let value = value else {
45 let error = value as NSError
46 guard let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError else {
49 return error.domain == CKErrorDomain && error.code == pattern.code &&
50 underlyingError.domain == CKInternalErrorDomain && underlyingError.code == pattern.internalCode
53 struct CKErrorMatcher {
58 func ~= (pattern: CKErrorMatcher, value: Error?) -> Bool {
59 guard let value = value else {
62 let error = value as NSError
63 return error.domain == CKErrorDomain && error.code == pattern.code
66 struct NSURLErrorMatcher {
70 // Match an NSURLError
71 func ~= (pattern: NSURLErrorMatcher, value: Error?) -> Bool {
72 guard let value = value else {
75 let error = value as NSError
76 return error.domain == NSURLErrorDomain && error.code == pattern.code
79 public class RetryingInvocable: CloudKitCode.Invocable {
80 private let underlyingInvocable: CloudKitCode.Invocable
82 internal init(retry: CloudKitCode.Invocable) {
83 self.underlyingInvocable = retry
86 public class func retryableError(error: Error?) -> Bool {
88 case NSURLErrorMatcher(code: NSURLErrorTimedOut):
90 case CKErrorMatcher(code: CKError.networkFailure.rawValue):
92 case CKInternalErrorMatcher(code: CKError.serverRejectedRequest.rawValue, internalCode: CKInternalErrorCode.errorInternalServerInternalError.rawValue):
94 case CuttlefishErrorMatcher(code: CuttlefishErrorCode.retryableServerFailure):
96 case CuttlefishErrorMatcher(code: CuttlefishErrorCode.transactionalFailure):
103 public func invoke<RequestType, ResponseType>(function: String,
104 request: RequestType,
105 completion: @escaping (ResponseType?, Error?) -> Void) where RequestType: Message, ResponseType: Message {
107 let deadline = Date(timeInterval: 30, since: now)
108 let delay = TimeInterval(5)
110 self.invokeRetry(function: function,
114 completion: completion)
117 private func invokeRetry<RequestType: Message, ResponseType: Message>(
119 request: RequestType,
121 minimumDelay: TimeInterval,
122 completion: @escaping (ResponseType?, Error?) -> Void) {
124 self.underlyingInvocable.invoke(function: function,
125 request: request) { (response: ResponseType?, error: Error?) in
126 if let error = error, RetryingInvocable.retryableError(error: error) {
129 // Check cuttlefish and CKError retry afters.
130 let cuttlefishDelay = CuttlefishRetryAfter(error: error)
131 let ckDelay = CKRetryAfterSecondsForError(error)
132 let delay = max(minimumDelay, cuttlefishDelay, ckDelay)
133 let cutoff = Date(timeInterval: delay, since: now)
135 guard cutoff.compare(deadline) == ComparisonResult.orderedDescending else {
136 Thread.sleep(forTimeInterval: delay)
137 os_log("%{public}@ error: %{public}@ (retrying, now=%{public}@, deadline=%{public}@)", log: tplogDebug,
139 "\(String(describing: error))",
140 "\(String(describing: now))",
141 "\(String(describing: deadline))")
142 self.invokeRetry(function: function,
145 minimumDelay: minimumDelay,
146 completion: completion)
150 completion(response, error)
155 public class MyCodeConnection: CloudKitCode.Invocable {
156 private let serviceName: String
157 private let container: CKContainer
158 private let databaseScope: CKDatabase.Scope
159 private let local: Bool
160 private let queue: DispatchQueue
162 internal init(service: String, container: CKContainer, databaseScope: CKDatabase.Scope, local: Bool) {
163 self.serviceName = service
164 self.container = container
165 self.databaseScope = databaseScope
167 self.queue = DispatchQueue(label: "MyCodeConnection", qos: .userInitiated)
170 /// Temporary stand-in until xcinverness moves to a swift-grpc plugin.
171 /// Intended to be used by protoc-generated code only
172 public func invoke<RequestType: Message, ResponseType: Message>(
173 function: String, request: RequestType,
174 completion: @escaping (ResponseType?, Error?) -> Void) {
176 // Hack to fool CloudKit, real solution is tracked in <rdar://problem/49086080>
179 let operation = CodeOperation<RequestType, ResponseType>(
180 service: self.serviceName,
181 functionName: function,
183 destinationServer: self.local ? .local : .default)
185 // As each UUID finishes, log it.
186 let requestCompletion = { (requestInfo: CKRequestInfo?) -> Void in
187 if let requestUUID = requestInfo?.requestUUID {
188 os_log("ckoperation request finished: %{public}@ %{public}@", log: tplogDebug, function, requestUUID)
191 operation.requestCompletedBlock = requestCompletion
193 let loggingCompletion = { (response: ResponseType?, error: Error?) -> Void in
194 os_log("%{public}@(%{public}@): %{public}@, error: %{public}@",
197 "\(String(describing: request))",
198 "\(String(describing: response))",
199 "\(String(describing: error))")
200 completion(response, error)
202 operation.codeOperationCompletionBlock = loggingCompletion
204 /* Same convenience API properties that we specify in CKContainer / CKDatabase */
205 operation.queuePriority = .low
207 // One alternative here would be to not set any QoS and trust the
208 // QoS propagation to do what's right. But there is also some benefit in
209 // just using a lower CPU QoS because it should be hard to measure for the
211 operation.qualityOfService = .userInitiated
213 operation.configuration.discretionaryNetworkBehavior = .nonDiscretionary
214 operation.configuration.automaticallyRetryNetworkFailures = false
215 operation.configuration.isCloudKitSupportOperation = true
217 operation.configuration.sourceApplicationBundleIdentifier = CuttlefishPushTopicBundleIdentifier
219 let database = self.container.database(with: self.databaseScope)
221 database.add(operation)
226 protocol ContainerNameToCuttlefishInvocable {
227 func client(container: String) -> CloudKitCode.Invocable
230 class CKCodeCuttlefishInvocableCreator: ContainerNameToCuttlefishInvocable {
231 func client(container: String) -> CloudKitCode.Invocable {
232 // Set up Cuttlefish client connection
233 let ckContainer = CKContainer(identifier: container)
235 // Cuttlefish is using its own push topic.
236 // To register for this push topic, we need to issue CK operations with a specific bundle identifier
237 ckContainer.sourceApplicationBundleIdentifier = CuttlefishPushTopicBundleIdentifier
239 let ckDatabase = ckContainer.privateCloudDatabase
240 return MyCodeConnection(service: "Cuttlefish", container: ckContainer,
241 databaseScope: ckDatabase.databaseScope, local: false)
245 // A collection of Containers.
246 // When a Container of a given name is requested, it is created if it did not already exist.
247 // Methods may be invoked concurrently.
249 private let queue = DispatchQueue(label: "com.apple.security.TrustedPeersHelper.ContainerMap")
251 let invocableCreator: ContainerNameToCuttlefishInvocable
253 init(invocableCreator: ContainerNameToCuttlefishInvocable) {
254 self.invocableCreator = invocableCreator
257 // Only access containers while executing on queue
258 private var containers: [ContainerName: Container] = [:]
260 func findOrCreate(name: ContainerName) throws -> Container {
261 return try queue.sync {
262 if let container = self.containers[name] {
266 // Set up Core Data stack
267 let persistentStoreURL = ContainerMap.urlForPersistentStore(name: name)
268 let description = NSPersistentStoreDescription(url: persistentStoreURL)
270 // Wrap whatever we're given in a magically-retrying layer
271 let cuttlefishInvocable = self.invocableCreator.client(container: name.container)
272 let retryingInvocable = RetryingInvocable(retry: cuttlefishInvocable)
273 let cuttlefish = CuttlefishAPIAsyncClient(invocable: retryingInvocable)
275 let container = try Container(name: name, persistentStoreDescription: description,
276 cuttlefish: cuttlefish)
277 self.containers[name] = container
283 static func urlForPersistentStore(name: ContainerName) -> URL {
284 let filename = name.container + "-" + name.context + ".TrustedPeersHelper.db"
285 return SecCopyURLForFileInKeychainDirectory(filename as CFString) as URL
288 // To be called via test only
289 func removeAllContainers() {
291 self.containers.removeAll()