NetNewsWire/Frameworks/Account/CloudKit/CloudKitZone.swift

581 lines
17 KiB
Swift
Raw Normal View History

//
// CloudKitZone.swift
// Account
//
// Created by Maurice Parker on 3/21/20.
// Copyright © 2020 Ranchero Software, LLC. All rights reserved.
//
import CloudKit
import os.log
import RSWeb
enum CloudKitZoneError: LocalizedError {
2020-03-29 10:43:20 +02:00
case userDeletedZone
2020-03-29 15:52:59 +02:00
case invalidParameter
2020-03-27 19:59:42 +01:00
case unknown
var errorDescription: String? {
if case .userDeletedZone = self {
return NSLocalizedString("The iCloud data was deleted. Please delete the NetNewsWire iCloud account and add it again to continue using NetNewsWire's iCloud support.", comment: "User deleted zone.")
} else {
return NSLocalizedString("An unexpected CloudKit error occurred.", comment: "An unexpected CloudKit error occurred.")
}
}
2020-03-27 19:59:42 +01:00
}
2020-03-29 18:53:52 +02:00
protocol CloudKitZoneDelegate: class {
func cloudKitDidModify(changed: [CKRecord], deleted: [CloudKitRecordKey], completion: @escaping (Result<Void, Error>) -> Void);
2020-03-29 18:53:52 +02:00
}
2020-04-01 19:22:59 +02:00
typealias CloudKitRecordKey = (recordType: CKRecord.RecordType, recordID: CKRecord.ID)
2020-03-29 18:53:52 +02:00
protocol CloudKitZone: class {
2020-03-27 19:59:42 +01:00
static var zoneID: CKRecordZone.ID { get }
var log: OSLog { get }
var container: CKContainer? { get }
var database: CKDatabase? { get }
2020-03-29 18:53:52 +02:00
var delegate: CloudKitZoneDelegate? { get set }
2020-04-04 09:33:41 +02:00
/// Reset the change token used to determine what point in time we are doing changes fetches
func resetChangeToken()
/// Generates a new CKRecord.ID using a UUID for the record's name
func generateRecordID() -> CKRecord.ID
/// Subscribe to changes at a zone level
2020-04-04 20:33:49 +02:00
func subscribeToZoneChanges()
2020-04-04 09:33:41 +02:00
/// Process a remove notification
func receiveRemoteNotification(userInfo: [AnyHashable : Any], completion: @escaping () -> Void)
}
extension CloudKitZone {
/// Reset the change token used to determine what point in time we are doing changes fetches
func resetChangeToken() {
changeToken = nil
}
2020-03-27 19:59:42 +01:00
func generateRecordID() -> CKRecord.ID {
return CKRecord.ID(recordName: UUID().uuidString, zoneID: Self.zoneID)
}
func retryIfPossible(after: Double, block: @escaping () -> ()) {
let delayTime = DispatchTime.now() + after
DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {
block()
})
}
func receiveRemoteNotification(userInfo: [AnyHashable : Any], completion: @escaping () -> Void) {
let note = CKRecordZoneNotification(fromRemoteNotificationDictionary: userInfo)
guard note?.recordZoneID?.zoneName == Self.zoneID.zoneName else {
completion()
return
}
fetchChangesInZone() { result in
if case .failure(let error) = result {
2020-04-05 00:35:09 +02:00
os_log(.error, log: self.log, "%@ zone remote notification fetch error: %@", Self.zoneID.zoneName, error.localizedDescription)
}
completion()
}
}
2020-04-26 09:28:19 +02:00
/// Creates the zone record
func createZoneRecord(completion: @escaping (Result<Void, Error>) -> Void) {
guard let database = database else {
completion(.failure(CloudKitZoneError.unknown))
return
}
database.save(CKRecordZone(zoneID: Self.zoneID)) { (recordZone, error) in
if let error = error {
DispatchQueue.main.async {
completion(.failure(CloudKitError(error)))
}
} else {
DispatchQueue.main.async {
completion(.success(()))
}
}
}
}
2020-04-26 09:28:19 +02:00
/// Subscribes to zone changes
func subscribeToZoneChanges() {
let subscription = CKRecordZoneSubscription(zoneID: Self.zoneID)
let info = CKSubscription.NotificationInfo()
info.shouldSendContentAvailable = true
subscription.notificationInfo = info
save(subscription) { result in
if case .failure(let error) = result {
os_log(.error, log: self.log, "%@ zone subscribe to changes error: %@", Self.zoneID.zoneName, error.localizedDescription)
}
}
}
/// Issue a CKQuery and return the resulting CKRecords.s
2020-03-30 22:15:45 +02:00
func query(_ query: CKQuery, completion: @escaping (Result<[CKRecord], Error>) -> Void) {
guard let database = database else {
completion(.failure(CloudKitZoneError.unknown))
return
}
database.perform(query, inZoneWith: Self.zoneID) { [weak self] records, error in
guard let self = self else {
completion(.failure(CloudKitZoneError.unknown))
return
}
2020-03-30 22:15:45 +02:00
switch CloudKitZoneResult.resolve(error) {
case .success:
DispatchQueue.main.async {
if let records = records {
completion(.success(records))
} else {
completion(.failure(CloudKitZoneError.unknown))
}
2020-03-30 22:15:45 +02:00
}
case .zoneNotFound:
self.createZoneRecord() { result in
switch result {
case .success:
self.query(query, completion: completion)
case .failure(let error):
DispatchQueue.main.async {
completion(.failure(error))
}
}
}
2020-03-30 22:15:45 +02:00
case .retry(let timeToWait):
2020-04-28 17:59:01 +02:00
os_log(.error, log: self.log, "%@ zone query retry in %f seconds.", Self.zoneID.zoneName, timeToWait)
self.retryIfPossible(after: timeToWait) {
self.query(query, completion: completion)
2020-03-30 22:15:45 +02:00
}
2020-04-04 03:39:50 +02:00
case .userDeletedZone:
DispatchQueue.main.async {
completion(.failure(CloudKitZoneError.userDeletedZone))
}
2020-03-30 22:15:45 +02:00
default:
DispatchQueue.main.async {
2020-04-04 04:20:55 +02:00
completion(.failure(CloudKitError(error!)))
}
2020-03-30 22:15:45 +02:00
}
}
}
/// Fetch a CKRecord by using its externalID
func fetch(externalID: String?, completion: @escaping (Result<CKRecord, Error>) -> Void) {
guard let externalID = externalID else {
completion(.failure(CloudKitZoneError.invalidParameter))
return
}
let recordID = CKRecord.ID(recordName: externalID, zoneID: Self.zoneID)
database?.fetch(withRecordID: recordID) { [weak self] record, error in
guard let self = self else {
completion(.failure(CloudKitZoneError.unknown))
return
}
switch CloudKitZoneResult.resolve(error) {
case .success:
DispatchQueue.main.async {
if let record = record {
completion(.success(record))
} else {
completion(.failure(CloudKitZoneError.unknown))
}
}
case .zoneNotFound:
self.createZoneRecord() { result in
switch result {
case .success:
self.fetch(externalID: externalID, completion: completion)
case .failure(let error):
DispatchQueue.main.async {
completion(.failure(error))
}
}
}
case .retry(let timeToWait):
2020-04-28 17:59:01 +02:00
os_log(.error, log: self.log, "%@ zone fetch retry in %f seconds.", Self.zoneID.zoneName, timeToWait)
self.retryIfPossible(after: timeToWait) {
self.fetch(externalID: externalID, completion: completion)
}
2020-04-04 03:39:50 +02:00
case .userDeletedZone:
DispatchQueue.main.async {
completion(.failure(CloudKitZoneError.userDeletedZone))
}
default:
DispatchQueue.main.async {
2020-04-04 04:20:55 +02:00
completion(.failure(CloudKitError(error!)))
}
}
}
}
/// Save the CKRecord
func save(_ record: CKRecord, completion: @escaping (Result<Void, Error>) -> Void) {
modify(recordsToSave: [record], recordIDsToDelete: [], completion: completion)
}
/// Save the CKRecords
func save(_ records: [CKRecord], completion: @escaping (Result<Void, Error>) -> Void) {
modify(recordsToSave: records, recordIDsToDelete: [], completion: completion)
}
2020-04-04 20:33:49 +02:00
/// Save the CKSubscription
func save(_ subscription: CKSubscription, completion: @escaping (Result<CKSubscription, Error>) -> Void) {
database?.save(subscription) { [weak self] savedSubscription, error in
guard let self = self else {
completion(.failure(CloudKitZoneError.unknown))
return
}
2020-04-04 20:33:49 +02:00
switch CloudKitZoneResult.resolve(error) {
case .success:
DispatchQueue.main.async {
completion(.success((savedSubscription!)))
}
case .zoneNotFound:
self.createZoneRecord() { result in
switch result {
case .success:
self.save(subscription, completion: completion)
case .failure(let error):
DispatchQueue.main.async {
completion(.failure(error))
}
}
}
2020-04-04 20:33:49 +02:00
case .retry(let timeToWait):
2020-04-28 17:59:01 +02:00
os_log(.error, log: self.log, "%@ zone save subscription retry in %f seconds.", Self.zoneID.zoneName, timeToWait)
2020-04-04 20:33:49 +02:00
self.retryIfPossible(after: timeToWait) {
self.save(subscription, completion: completion)
}
default:
DispatchQueue.main.async {
completion(.failure(CloudKitError(error!)))
}
2020-04-04 20:33:49 +02:00
}
}
}
/// Delete CKRecords using a CKQuery
func delete(ckQuery: CKQuery, completion: @escaping (Result<Void, Error>) -> Void) {
var records = [CKRecord]()
let op = CKQueryOperation(query: ckQuery)
op.recordFetchedBlock = { record in
records.append(record)
}
op.queryCompletionBlock = { [weak self] (cursor, error) in
guard let self = self else {
completion(.failure(CloudKitZoneError.unknown))
return
}
if let cursor = cursor {
self.delete(cursor: cursor, carriedRecords: records, completion: completion)
} else {
guard !records.isEmpty else {
2020-04-28 02:06:50 +02:00
DispatchQueue.main.async {
completion(.success(()))
}
return
}
let recordIDs = records.map { $0.recordID }
self.modify(recordsToSave: [], recordIDsToDelete: recordIDs, completion: completion)
}
}
database?.add(op)
}
/// Delete CKRecords using a CKQuery
func delete(cursor: CKQueryOperation.Cursor, carriedRecords: [CKRecord], completion: @escaping (Result<Void, Error>) -> Void) {
var records = [CKRecord]()
let op = CKQueryOperation(cursor: cursor)
op.recordFetchedBlock = { record in
records.append(record)
}
op.queryCompletionBlock = { [weak self] (cursor, error) in
guard let self = self else {
completion(.failure(CloudKitZoneError.unknown))
return
}
records.append(contentsOf: carriedRecords)
if let cursor = cursor {
self.delete(cursor: cursor, carriedRecords: records, completion: completion)
} else {
let recordIDs = records.map { $0.recordID }
self.modify(recordsToSave: [], recordIDsToDelete: recordIDs, completion: completion)
}
}
database?.add(op)
}
2020-04-04 20:33:49 +02:00
/// Delete a CKRecord using its recordID
func delete(recordID: CKRecord.ID, completion: @escaping (Result<Void, Error>) -> Void) {
modify(recordsToSave: [], recordIDsToDelete: [recordID], completion: completion)
}
2020-04-26 09:28:19 +02:00
/// Delete CKRecords
func delete(recordIDs: [CKRecord.ID], completion: @escaping (Result<Void, Error>) -> Void) {
modify(recordsToSave: [], recordIDsToDelete: recordIDs, completion: completion)
}
/// Delete a CKRecord using its externalID
func delete(externalID: String?, completion: @escaping (Result<Void, Error>) -> Void) {
guard let externalID = externalID else {
completion(.failure(CloudKitZoneError.invalidParameter))
return
}
let recordID = CKRecord.ID(recordName: externalID, zoneID: Self.zoneID)
modify(recordsToSave: [], recordIDsToDelete: [recordID], completion: completion)
}
2020-04-04 20:33:49 +02:00
/// Delete a CKSubscription
func delete(subscriptionID: String, completion: @escaping (Result<Void, Error>) -> Void) {
database?.delete(withSubscriptionID: subscriptionID) { [weak self] _, error in
guard let self = self else {
completion(.failure(CloudKitZoneError.unknown))
return
}
2020-04-04 20:33:49 +02:00
switch CloudKitZoneResult.resolve(error) {
case .success:
DispatchQueue.main.async {
completion(.success(()))
}
2020-04-04 20:33:49 +02:00
case .retry(let timeToWait):
2020-04-28 17:59:01 +02:00
os_log(.error, log: self.log, "%@ zone delete subscription retry in %f seconds.", Self.zoneID.zoneName, timeToWait)
2020-04-04 20:33:49 +02:00
self.retryIfPossible(after: timeToWait) {
self.delete(subscriptionID: subscriptionID, completion: completion)
}
default:
DispatchQueue.main.async {
completion(.failure(CloudKitError(error!)))
}
2020-04-04 20:33:49 +02:00
}
}
}
/// Modify and delete the supplied CKRecords and CKRecord.IDs
2020-03-29 18:53:52 +02:00
func modify(recordsToSave: [CKRecord], recordIDsToDelete: [CKRecord.ID], completion: @escaping (Result<Void, Error>) -> Void) {
2020-04-28 06:09:45 +02:00
guard !(recordsToSave.isEmpty && recordIDsToDelete.isEmpty) else {
completion(.success(()))
return
}
2020-03-29 15:52:59 +02:00
let op = CKModifyRecordsOperation(recordsToSave: recordsToSave, recordIDsToDelete: recordIDsToDelete)
2020-03-27 19:59:42 +01:00
op.savePolicy = .changedKeys
op.isAtomic = true
2020-03-27 19:59:42 +01:00
op.modifyRecordsCompletionBlock = { [weak self] (_, _, error) in
guard let self = self else {
completion(.failure(CloudKitZoneError.unknown))
return
}
2020-03-29 10:43:20 +02:00
switch CloudKitZoneResult.resolve(error) {
case .success:
DispatchQueue.main.async {
2020-03-27 19:59:42 +01:00
completion(.success(()))
}
2020-03-29 10:43:20 +02:00
case .zoneNotFound:
2020-03-28 14:30:25 +01:00
self.createZoneRecord() { result in
switch result {
case .success:
2020-03-29 15:52:59 +02:00
self.modify(recordsToSave: recordsToSave, recordIDsToDelete: recordIDsToDelete, completion: completion)
2020-03-28 14:30:25 +01:00
case .failure(let error):
DispatchQueue.main.async {
completion(.failure(error))
}
2020-03-28 14:30:25 +01:00
}
}
2020-03-29 10:43:20 +02:00
case .userDeletedZone:
DispatchQueue.main.async {
completion(.failure(CloudKitZoneError.userDeletedZone))
}
2020-03-27 19:59:42 +01:00
case .retry(let timeToWait):
2020-04-28 17:59:01 +02:00
os_log(.error, log: self.log, "%@ zone modify retry in %f seconds.", Self.zoneID.zoneName, timeToWait)
self.retryIfPossible(after: timeToWait) {
2020-03-29 15:52:59 +02:00
self.modify(recordsToSave: recordsToSave, recordIDsToDelete: recordIDsToDelete, completion: completion)
}
2020-03-29 10:43:20 +02:00
case .limitExceeded:
2020-03-29 15:52:59 +02:00
let chunkedRecords = recordsToSave.chunked(into: 300)
2020-04-01 22:39:07 +02:00
let group = DispatchGroup()
var errorOccurred = false
for chunk in chunkedRecords {
2020-04-01 22:39:07 +02:00
group.enter()
self.modify(recordsToSave: chunk, recordIDsToDelete: recordIDsToDelete) { result in
if case .failure(let error) = result {
2020-04-05 00:35:09 +02:00
os_log(.error, log: self.log, "%@ zone modify records error: %@", Self.zoneID.zoneName, error.localizedDescription)
2020-04-01 22:39:07 +02:00
errorOccurred = true
}
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
if errorOccurred {
completion(.failure(CloudKitZoneError.unknown))
} else {
completion(.success(()))
}
}
2020-04-01 22:39:07 +02:00
default:
2020-03-29 10:43:20 +02:00
DispatchQueue.main.async {
2020-04-04 04:20:55 +02:00
completion(.failure(CloudKitError(error!)))
2020-03-29 10:43:20 +02:00
}
}
}
database?.add(op)
2020-03-27 19:59:42 +01:00
}
/// Fetch all the changes in the CKZone since the last time we checked
func fetchChangesInZone(completion: @escaping (Result<Void, Error>) -> Void) {
var savedChangeToken = changeToken
2020-04-01 19:22:59 +02:00
var changedRecords = [CKRecord]()
var deletedRecordKeys = [CloudKitRecordKey]()
2020-03-29 18:53:52 +02:00
let zoneConfig = CKFetchRecordZoneChangesOperation.ZoneConfiguration()
zoneConfig.previousServerChangeToken = changeToken
let op = CKFetchRecordZoneChangesOperation(recordZoneIDs: [Self.zoneID], configurationsByRecordZoneID: [Self.zoneID: zoneConfig])
op.fetchAllChanges = true
op.recordZoneChangeTokensUpdatedBlock = { zoneID, token, _ in
savedChangeToken = token
2020-03-29 18:53:52 +02:00
}
op.recordChangedBlock = { record in
2020-04-01 19:22:59 +02:00
changedRecords.append(record)
2020-03-29 18:53:52 +02:00
}
op.recordWithIDWasDeletedBlock = { recordID, recordType in
2020-04-01 19:22:59 +02:00
let recordKey = CloudKitRecordKey(recordType: recordType, recordID: recordID)
deletedRecordKeys.append(recordKey)
2020-03-29 18:53:52 +02:00
}
op.recordZoneFetchCompletionBlock = { zoneID ,token, _, _, error in
if case .success = CloudKitZoneResult.resolve(error) {
savedChangeToken = token
}
2020-03-29 18:53:52 +02:00
}
op.fetchRecordZoneChangesCompletionBlock = { [weak self] error in
guard let self = self else {
completion(.failure(CloudKitZoneError.unknown))
return
}
2020-04-01 21:55:40 +02:00
switch CloudKitZoneResult.resolve(error) {
case .success:
DispatchQueue.main.async {
self.delegate?.cloudKitDidModify(changed: changedRecords, deleted: deletedRecordKeys) { result in
switch result {
case .success:
self.changeToken = savedChangeToken
completion(.success(()))
case .failure(let error):
completion(.failure(error))
}
}
}
2020-04-01 21:55:40 +02:00
case .zoneNotFound:
self.createZoneRecord() { result in
switch result {
case .success:
self.fetchChangesInZone(completion: completion)
case .failure(let error):
DispatchQueue.main.async {
completion(.failure(error))
}
}
}
case .userDeletedZone:
DispatchQueue.main.async {
completion(.failure(CloudKitZoneError.userDeletedZone))
}
case .retry(let timeToWait):
2020-04-28 17:59:01 +02:00
os_log(.error, log: self.log, "%@ zone fetch changes retry in %f seconds.", Self.zoneID.zoneName, timeToWait)
2020-04-01 21:55:40 +02:00
self.retryIfPossible(after: timeToWait) {
self.fetchChangesInZone(completion: completion)
}
case .changeTokenExpired:
DispatchQueue.main.async {
self.changeToken = nil
self.fetchChangesInZone(completion: completion)
}
default:
DispatchQueue.main.async {
2020-04-04 04:20:55 +02:00
completion(.failure(CloudKitError(error!)))
2020-04-01 21:55:40 +02:00
}
2020-03-29 18:53:52 +02:00
}
2020-04-01 21:55:40 +02:00
2020-03-29 18:53:52 +02:00
}
database?.add(op)
2020-03-29 18:53:52 +02:00
}
}
private extension CloudKitZone {
var changeTokenKey: String {
return "cloudkit.server.token.\(Self.zoneID.zoneName)"
}
var changeToken: CKServerChangeToken? {
get {
guard let tokenData = UserDefaults.standard.object(forKey: changeTokenKey) as? Data else { return nil }
return try? NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: tokenData)
}
set {
guard let token = newValue, let data = try? NSKeyedArchiver.archivedData(withRootObject: token, requiringSecureCoding: false) else {
UserDefaults.standard.removeObject(forKey: changeTokenKey)
return
}
UserDefaults.standard.set(data, forKey: changeTokenKey)
}
}
var zoneConfiguration: CKFetchRecordZoneChangesOperation.ZoneConfiguration {
let config = CKFetchRecordZoneChangesOperation.ZoneConfiguration()
config.previousServerChangeToken = changeToken
return config
}
}