-
Notifications
You must be signed in to change notification settings - Fork 58
Add CloudStore module for iCloud sync #1721
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
Draft
DRadmir
wants to merge
5
commits into
main
Choose a base branch
from
cloud-store
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9d79222
Add CloudStore module for iCloud sync
DRadmir 1770e10
Add pagination support and optimize deleteAll
DRadmir 1e32fce
Merge branch 'main' of github.com:gemwalletcom/gem-ios into cloud-store
DRadmir e2b6b7f
Remove DataTransformable protocol and simplify CloudSyncService
DRadmir cc30c73
Move CloudStore from Store to SystemServices
DRadmir File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
Packages/SystemServices/CloudStore/Protocols/CloudSyncable.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Foundation | ||
| import CloudKit | ||
|
|
||
| public protocol CloudSyncable: Identifiable, Codable, Sendable where ID == String { | ||
| static var recordType: String { get } | ||
| } | ||
|
|
||
| extension CloudSyncable { | ||
| public static var recordType: String { | ||
| String(describing: Self.self) | ||
| } | ||
|
|
||
| var recordID: CKRecord.ID { | ||
| CKRecord.ID(recordName: id) | ||
| } | ||
| } | ||
108 changes: 108 additions & 0 deletions
108
Packages/SystemServices/CloudStore/Services/CloudSyncService.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Foundation | ||
| import CloudKit | ||
|
|
||
| public actor CloudSyncService { | ||
| private let container: CKContainer | ||
| private let database: CKDatabase | ||
| private let encoder: JSONEncoder | ||
| private let decoder: JSONDecoder | ||
|
|
||
| public init( | ||
| containerIdentifier: String, | ||
| encoder: JSONEncoder = JSONEncoder(), | ||
| decoder: JSONDecoder = JSONDecoder() | ||
| ) { | ||
| self.container = CKContainer(identifier: containerIdentifier) | ||
| self.database = container.privateCloudDatabase | ||
| self.encoder = encoder | ||
| self.decoder = decoder | ||
| } | ||
|
|
||
| // MARK: - Account Status | ||
|
|
||
| public func checkAccountStatus() async throws -> CKAccountStatus { | ||
| try await container.accountStatus() | ||
| } | ||
|
|
||
| public func isAvailable() async -> Bool { | ||
| (try? await checkAccountStatus()) == .available | ||
| } | ||
|
|
||
| // MARK: - Save | ||
|
|
||
| public func save<T: CloudSyncable>(_ item: T) async throws { | ||
| try await database.save(try createRecord(for: item)) | ||
| } | ||
|
|
||
| public func save<T: CloudSyncable>(_ items: [T]) async throws { | ||
| let records = try items.map { try createRecord(for: $0) } | ||
| _ = try await database.modifyRecords(saving: records, deleting: []) | ||
| } | ||
|
|
||
| // MARK: - Fetch | ||
|
|
||
| public func fetch<T: CloudSyncable>(_ type: T.Type) async throws -> [T] { | ||
| try await fetchAllRecords(recordType: T.recordType).compactMap { _, result in | ||
| switch result { | ||
| case .success(let record): try decodeRecord(record, as: type) | ||
| case .failure: nil | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Delete | ||
|
|
||
| public func delete<T: CloudSyncable>(_ item: T) async throws { | ||
| try await database.deleteRecord(withID: item.recordID) | ||
| } | ||
|
|
||
| public func delete<T: CloudSyncable>(_ items: [T]) async throws { | ||
| _ = try await database.modifyRecords(saving: [], deleting: items.map { $0.recordID }) | ||
| } | ||
|
|
||
| public func deleteAll<T: CloudSyncable>(_ type: T.Type) async throws { | ||
| let ids = try await fetchAllRecords(recordType: T.recordType, desiredKeys: []).map { $0.0 } | ||
| guard !ids.isEmpty else { return } | ||
| _ = try await database.modifyRecords(saving: [], deleting: ids) | ||
| } | ||
|
|
||
| // MARK: - Private | ||
|
|
||
| private func createRecord<T: CloudSyncable>(for item: T) throws -> CKRecord { | ||
| let record = CKRecord(recordType: T.recordType, recordID: item.recordID) | ||
| record.payload = try encoder.encode(item) | ||
| return record | ||
| } | ||
|
|
||
| private func decodeRecord<T: CloudSyncable>(_ record: CKRecord, as type: T.Type) throws -> T { | ||
| guard let data = record.payload else { | ||
| throw CloudSyncError.invalidRecordData | ||
| } | ||
| return try decoder.decode(type, from: data) | ||
| } | ||
|
|
||
| private func fetchAllRecords( | ||
| recordType: String, | ||
| desiredKeys: [CKRecord.FieldKey]? = nil | ||
| ) async throws -> [(CKRecord.ID, Result<CKRecord, any Error>)] { | ||
| let query = CKQuery(recordType: recordType, predicate: NSPredicate(value: true)) | ||
| var (allResults, cursor) = try await database.records(matching: query, desiredKeys: desiredKeys) | ||
|
|
||
| while let currentCursor = cursor { | ||
| let (nextResults, nextCursor) = try await database.records(continuingMatchFrom: currentCursor, desiredKeys: desiredKeys) | ||
| allResults.append(contentsOf: nextResults) | ||
| cursor = nextCursor | ||
| } | ||
|
|
||
| return allResults | ||
| } | ||
| } | ||
|
|
||
| private extension CKRecord { | ||
| var payload: Data? { | ||
| get { self["data"] as? Data } | ||
| set { self["data"] = newValue } | ||
| } | ||
| } |
7 changes: 7 additions & 0 deletions
7
Packages/SystemServices/CloudStore/Types/CloudSyncError.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Foundation | ||
|
|
||
| public enum CloudSyncError: Error, Sendable { | ||
| case invalidRecordData | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.