-
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
Open
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.
Open
Changes from 2 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
There are no files selected for viewing
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) | ||
| } | ||
| } |
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,8 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Foundation | ||
|
|
||
| public protocol DataTransformable: Sendable { | ||
| func transform(_ data: Data) throws -> Data | ||
| func restore(_ data: Data) throws -> Data | ||
| } |
106 changes: 106 additions & 0 deletions
106
Packages/Store/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,106 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Foundation | ||
| import CloudKit | ||
|
|
||
| public actor CloudSyncService { | ||
| private let container: CKContainer | ||
| private let database: CKDatabase | ||
| private let transformer: DataTransformable | ||
|
|
||
| public init( | ||
| containerIdentifier: String, | ||
| transformer: DataTransformable | ||
| ) { | ||
| self.container = CKContainer(identifier: containerIdentifier) | ||
| self.database = container.privateCloudDatabase | ||
| self.transformer = transformer | ||
| } | ||
|
|
||
| // 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 data = try JSONEncoder().encode(item) | ||
| let record = CKRecord(recordType: T.recordType, recordID: item.recordID) | ||
| record.payload = try transformer.transform(data) | ||
| 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 JSONDecoder().decode(type, from: try transformer.restore(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 } | ||
| } | ||
| } |
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,8 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Foundation | ||
|
|
||
| public enum CloudSyncError: Error, Sendable { | ||
| case invalidRecordData | ||
| case encryptionFailed | ||
| } |
23 changes: 23 additions & 0 deletions
23
Packages/Store/CloudStore/Types/EncryptedTransformer.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,23 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Foundation | ||
| import CryptoKit | ||
|
|
||
| public struct EncryptedTransformer: DataTransformable { | ||
| private let key: SymmetricKey | ||
|
|
||
| public init(key: SymmetricKey) { | ||
| self.key = key | ||
| } | ||
|
|
||
| public func transform(_ data: Data) throws -> Data { | ||
| guard let combined = try AES.GCM.seal(data, using: key).combined else { | ||
| throw CloudSyncError.encryptionFailed | ||
| } | ||
| return combined | ||
| } | ||
|
|
||
| public func restore(_ data: Data) throws -> Data { | ||
| try AES.GCM.open(try AES.GCM.SealedBox(combined: data), using: key) | ||
| } | ||
| } | ||
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,10 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Foundation | ||
|
|
||
| public struct PlainTransformer: DataTransformable { | ||
| public init() {} | ||
|
|
||
| public func transform(_ data: Data) throws -> Data { data } | ||
| public func restore(_ data: Data) throws -> Data { data } | ||
| } |
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
30 changes: 30 additions & 0 deletions
30
Packages/Store/Tests/StoreTests/EncryptedTransformerTests.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,30 @@ | ||
| // Copyright (c). Gem Wallet. All rights reserved. | ||
|
|
||
| import Testing | ||
| import Foundation | ||
| import CryptoKit | ||
| @testable import CloudStore | ||
|
|
||
| struct EncryptedTransformerTests { | ||
|
|
||
| @Test | ||
| func encryptDecrypt() throws { | ||
| let transformer = EncryptedTransformer(key: SymmetricKey(size: .bits256)) | ||
| let original = Data("secret data".utf8) | ||
|
|
||
| let encrypted = try transformer.transform(original) | ||
| let decrypted = try transformer.restore(encrypted) | ||
|
|
||
| #expect(decrypted == original) | ||
| #expect(encrypted != original) | ||
| } | ||
|
|
||
| @Test | ||
| func wrongKeyFails() throws { | ||
| let encrypted = try EncryptedTransformer(key: SymmetricKey(size: .bits256)).transform(Data("secret".utf8)) | ||
|
|
||
| #expect(throws: CryptoKitError.self) { | ||
| try EncryptedTransformer(key: SymmetricKey(size: .bits256)).restore(encrypted) | ||
| } | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Move to
SystemServices