Skip to content
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
7 changes: 5 additions & 2 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ on:

jobs:
build:
runs-on: macos-latest
# Build with the runner's default Xcode rather than a separately installed
# toolchain. The image must ship the macOS 26 SDK or later: ErrorMiddleware
# switches over CKError.Code.participantAlreadyInvited, which does not
# exist in earlier SDKs, so macos-15 (Xcode 16) fails to compile.
runs-on: macos-26
steps:
- uses: actions/checkout@v4
- uses: swift-actions/setup-swift@v1
- name: Build
run: swift build -v
- name: Run tests
Expand Down
11 changes: 9 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// swift-tools-version: 5.9
// swift-tools-version: 6.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription
Expand Down Expand Up @@ -29,11 +29,18 @@ let package = Package(
dependencies: [
.product(name: "PID", package: "swift-pid"),
.product(name: "Logging", package: "swift-log"),
],
swiftSettings: [
.swiftLanguageMode(.v5),
.enableUpcomingFeature("StrictConcurrency"),
]
),
.testTarget(
name: "CloudSyncSessionTests",
dependencies: ["CloudSyncSession"]
dependencies: ["CloudSyncSession"],
swiftSettings: [
.swiftLanguageMode(.v5),
]
),
]
)
38 changes: 26 additions & 12 deletions Sources/CloudSyncSession/CloudKitOperationHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ public class CloudKitOperationHandler: OperationHandler {
let subscriptionID: String
let savePolicy: CKModifyRecordsOperation.RecordSavePolicy = .ifServerRecordUnchanged
let qos: QualityOfService = .userInitiated
var rateLimitController = RateLimitPIDController(
/// Guards rateLimitController, throttleDuration, and nextOperationDeadline,
/// which are mutated from CloudKit callback threads and read when queueing.
private let throttleLock = NSLock()

private var rateLimitController = RateLimitPIDController(
kp: 2,
ki: 0.05,
kd: 0.02,
Expand All @@ -51,7 +55,7 @@ public class CloudKitOperationHandler: OperationHandler {
return queue
}()

var throttleDuration: TimeInterval {
private var throttleDuration: TimeInterval {
didSet {
nextOperationDeadline = DispatchTime.now() + throttleDuration

Expand All @@ -63,7 +67,7 @@ public class CloudKitOperationHandler: OperationHandler {
}
}

var nextOperationDeadline: DispatchTime?
private var nextOperationDeadline: DispatchTime?

public init(database: CKDatabase, zoneID: CKRecordZone.ID, subscriptionID: String) {
self.database = database
Expand All @@ -73,30 +77,40 @@ public class CloudKitOperationHandler: OperationHandler {
}

private func queueOperation(_ operation: Operation) {
throttleLock.lock()
let deadline: DispatchTime = nextOperationDeadline ?? DispatchTime.now()
throttleLock.unlock()

DispatchQueue.main.asyncAfter(deadline: deadline) {
self.operationQueue.addOperation(operation)
}
}

private func onOperationSuccess() {
throttleLock.lock()
defer { throttleLock.unlock() }

rateLimitController.record(outcome: .success)
throttleDuration = min(Self.maxThrottleDuration, max(Self.minThrottleDuration, rateLimitController.rateLimit))
}

private func onOperationError(_ error: Error) {
if let ckError = error as? CKError {
rateLimitController.record(outcome: ckError.indicatesShouldBackoff ? .failure : .success)
guard let ckError = error as? CKError else {
return
}

if let suggestedBackoffSeconds = ckError.suggestedBackoffSeconds {
Log.operations.info("CloudKit error suggests retrying after \(suggestedBackoffSeconds) seconds")
throttleLock.lock()
defer { throttleLock.unlock() }

// Respect the amount suggested for the next operation
throttleDuration = suggestedBackoffSeconds
} else {
throttleDuration = min(Self.maxThrottleDuration, max(Self.minThrottleDuration, rateLimitController.rateLimit))
}
rateLimitController.record(outcome: ckError.indicatesShouldBackoff ? .failure : .success)

if let suggestedBackoffSeconds = ckError.suggestedBackoffSeconds {
Log.operations.info("CloudKit error suggests retrying after \(suggestedBackoffSeconds) seconds")

// Respect the amount suggested for the next operation
throttleDuration = suggestedBackoffSeconds
} else {
throttleDuration = min(Self.maxThrottleDuration, max(Self.minThrottleDuration, rateLimitController.rateLimit))
}
}

Expand Down
24 changes: 22 additions & 2 deletions Sources/CloudSyncSession/SyncWork.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,28 @@ public struct ModifyOperation: Identifiable, SyncOperation {
let splitRecords: [[CKRecord]] = records.chunked(into: maxRecommendedRecordsPerOperation)
let splitRecordIDsToDelete: [[CKRecord.ID]] = recordIDsToDelete.chunked(into: maxRecommendedRecordsPerOperation)

return splitRecords.map { ModifyOperation(records: $0, recordIDsToDelete: [], checkpointID: nil, userInfo: userInfo) } +
splitRecordIDsToDelete.enumerated().map { ModifyOperation(records: [], recordIDsToDelete: $0.element, checkpointID: $0.offset == splitRecordIDsToDelete.count - 1 ? checkpointID : nil, userInfo: userInfo) }
let recordChunks = splitRecords.map {
ModifyOperation(records: $0, recordIDsToDelete: [], checkpointID: nil, userInfo: userInfo)
}
let deletionChunks = splitRecordIDsToDelete.map {
ModifyOperation(records: [], recordIDsToDelete: $0, checkpointID: nil, userInfo: userInfo)
}

var chunks = recordChunks + deletionChunks

// The checkpoint must ride the final chunk so checkpoint-correlated
// waiters resolve only after every piece of the original operation
// has completed.
if let lastChunk = chunks.last {
chunks[chunks.count - 1] = ModifyOperation(
records: lastChunk.records,
recordIDsToDelete: lastChunk.recordIDsToDelete,
checkpointID: checkpointID,
userInfo: userInfo
)
}

return chunks
}

var splitInHalf: [ModifyOperation] {
Expand Down
36 changes: 36 additions & 0 deletions Tests/CloudSyncSessionTests/SyncWorkTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
@testable import CloudSyncSession
import CloudKit
import XCTest

final class SyncWorkTests: XCTestCase {
func testSplitPreservesCheckpointIDWhenThereAreNoDeletions() {
let checkpointID = UUID()
let operation = ModifyOperation(
records: (0 ..< 900).map { _ in makeTestRecord() },
recordIDsToDelete: [],
checkpointID: checkpointID,
userInfo: nil
)

let chunks = operation.split

XCTAssertEqual(chunks.count, 3)
XCTAssertEqual(chunks.last?.checkpointID, checkpointID)
XCTAssertTrue(chunks.dropLast().allSatisfy { $0.checkpointID == nil })
}

func testSplitKeepsCheckpointIDOnLastDeleteChunkWhenDeletionsExist() {
let checkpointID = UUID()
let operation = ModifyOperation(
records: (0 ..< 500).map { _ in makeTestRecord() },
recordIDsToDelete: (0 ..< 500).map { _ in makeTestRecord().recordID },
checkpointID: checkpointID,
userInfo: nil
)

let chunks = operation.split

XCTAssertEqual(chunks.last?.checkpointID, checkpointID)
XCTAssertEqual(chunks.filter { $0.checkpointID != nil }.count, 1)
}
}
Loading