Skip to content

Commit 4cd55d7

Browse files
committed
remove auth state listeners
1 parent 796cd84 commit 4cd55d7

File tree

6 files changed

+23
-142
lines changed

6 files changed

+23
-142
lines changed

AmplifyPlugins/DataStore/AWSDataStoreCategoryPlugin/AWSDataStorePlugin.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin {
8888
let filter = HubFilters.forEventName(HubPayload.EventName.Amplify.configured)
8989
var token: UnsubscribeToken?
9090
token = Amplify.Hub.listen(to: .dataStore, isIncluded: filter) { _ in
91-
self.storageEngine.tryStartSync()
91+
self.storageEngine.startSync()
9292
if let token = token {
9393
Amplify.Hub.removeListener(token)
9494
}
@@ -105,7 +105,7 @@ final public class AWSDataStorePlugin: DataStoreCategoryPlugin {
105105
}
106106
try resolveStorageEngine(dataStoreConfiguration: dataStoreConfiguration)
107107
try storageEngine.setUp(models: ModelRegistry.models)
108-
storageEngine.tryStartSync()
108+
storageEngine.startSync()
109109
} catch {
110110
log.error(error: error)
111111
}

AmplifyPlugins/DataStore/AWSDataStoreCategoryPlugin/Storage/StorageEngine+SyncRequirement.swift

Lines changed: 2 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import AWSPluginsCore
1212

1313
extension StorageEngine {
1414

15-
func tryStartSync() {
15+
func startSync() {
1616
guard let api = tryGetAPIPlugin() else {
1717
log.info("Unable to find suitable API plugin for syncEngine. syncEngine will not be started")
1818
return
@@ -30,18 +30,7 @@ extension StorageEngine {
3030
return
3131
}
3232

33-
isSignedIn(auth: auth) { result in
34-
switch result {
35-
case .success(let isSignedIn):
36-
if isSignedIn {
37-
self.syncEngine?.start(api: api, auth: auth)
38-
} else {
39-
self.waitForAuthSignedIn(api: api, auth: auth)
40-
}
41-
case .failure(let authError):
42-
self.log.error("Unable to check if user is signed in, error: \(authError)")
43-
}
44-
}
33+
syncEngine?.start(api: api, auth: auth)
4534
}
4635

4736
private func tryGetAPIPlugin() -> APICategoryGraphQLBehavior? {
@@ -67,61 +56,4 @@ extension StorageEngine {
6756

6857
return containsAuthEnabledSyncableModels
6958
}
70-
71-
private func isSignedIn(auth: AuthCategoryBehavior, onComplete: @escaping (Result<Bool, AuthError>) -> Void) {
72-
_ = auth.fetchAuthSession(options: nil) { event in
73-
switch event {
74-
case .success(let authSession):
75-
onComplete(.success(authSession.isSignedIn))
76-
case .failure(let error):
77-
onComplete(.failure(error))
78-
}
79-
}
80-
}
81-
82-
private func waitForAuthSignedIn(api: APICategoryGraphQLBehavior, auth: AuthCategoryBehavior) {
83-
log.debug("\(#function) Amplify.Hub.listen to Auth.signedIn event")
84-
guard signInListener == nil else {
85-
log.debug("\(#function) Already listening to Auth.signedIn event")
86-
return
87-
}
88-
let filter = HubFilters.forEventName(HubPayload.EventName.Auth.signedIn)
89-
signInListener = Amplify.Hub.listen(to: .auth, isIncluded: filter) { _ in
90-
self.syncEngine?.start(api: api, auth: auth)
91-
self.waitForAuthSignedOut(api: api, auth: auth)
92-
self.removeSignInListener()
93-
}
94-
}
95-
96-
private func waitForAuthSignedOut(api: APICategoryGraphQLBehavior, auth: AuthCategoryBehavior) {
97-
log.debug("\(#function) Amplify.Hub.listen to Auth.signedOut event")
98-
guard signOutListener == nil else {
99-
log.debug("\(#function) Already listening to Auth.signedOut event")
100-
return
101-
}
102-
let filter = HubFilters.forEventName(HubPayload.EventName.Auth.signedOut)
103-
signOutListener = Amplify.Hub.listen(to: .auth, isIncluded: filter) { _ in
104-
Amplify.DataStore.clear { result in
105-
switch result {
106-
case .success:
107-
self.waitForAuthSignedIn(api: api, auth: auth)
108-
case .failure(let dataStoreError):
109-
self.log.warn("Unable to clear on SignOut, error: \(dataStoreError)")
110-
}
111-
}
112-
self.removeSignOutListener()
113-
}
114-
}
115-
116-
private func removeSignInListener() {
117-
if let listener = signInListener {
118-
Amplify.Hub.removeListener(listener)
119-
}
120-
}
121-
122-
private func removeSignOutListener() {
123-
if let listener = signOutListener {
124-
Amplify.Hub.removeListener(listener)
125-
}
126-
}
12759
}

AmplifyPlugins/DataStore/AWSDataStoreCategoryPlugin/Storage/StorageEngine.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ final class StorageEngine: StorageEngineBehavior {
1818
let validAPIPluginKey: String
1919
let validAuthPluginKey: String
2020
var signInListener: UnsubscribeToken?
21-
var signOutListener: UnsubscribeToken?
2221

2322
var iSyncEngineSink: Any?
2423
@available(iOS 13.0, *)

AmplifyPlugins/DataStore/AWSDataStoreCategoryPlugin/Storage/StorageEngineBehavior.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ protocol StorageEngineBehavior: class, ModelStorageBehavior {
1919
@available(iOS 13.0, *)
2020
var publisher: AnyPublisher<StorageEngineEvent, DataStoreError> { get }
2121

22-
/// Try to start remote sync, based on if sync is enabled and/or authentication is required
23-
func tryStartSync()
22+
/// start remote sync, based on if sync is enabled and/or authentication is required
23+
func startSync()
2424

2525
func clear(completion: @escaping DataStoreCallback<Void>)
2626
}

AmplifyPlugins/DataStore/AWSDataStoreCategoryPluginAuthIntegrationTests/AWSDataStoreCategoryPluginAuthIntegrationTests.swift

Lines changed: 16 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,8 @@ class AWSDataStoreCategoryPluginAuthIntegrationTests: XCTestCase {
7272
/// - When:
7373
/// - User is not signed in, then user can successfully save a note to local store
7474
/// - User remains signed out, then user can successfully retrieve the saved note, with empty owner field
75-
/// - User signs in, then the sync engine is started and reconciles local store with the ownerId
76-
/// - User retrieves the note again and now it contains the ownerId
77-
/// - User signs out, the local store is cleared, then retrieving note returns nil
75+
/// - User signs in, retrieves note, sync engine is started and reconciles local store with the ownerId
76+
/// - The note now it contains the ownerId
7877
func testUnauthenticatedSavesToLocalStoreIsReconciledWithCloudStoreAfterAuthentication() throws {
7978
let savedLocalNote = saveNote(content: "owner saved note")
8079
let queriedNoteOptional = queryNote(byId: savedLocalNote.id)
@@ -84,17 +83,6 @@ class AWSDataStoreCategoryPluginAuthIntegrationTests: XCTestCase {
8483
}
8584
XCTAssertNil(note.owner)
8685

87-
let syncStartedInvoked = expectation(description: "Sync started after sign In")
88-
let syncStartedListener = Amplify.Hub.listen(
89-
to: .dataStore,
90-
eventName: HubPayload.EventName.DataStore.syncStarted) { _ in
91-
syncStartedInvoked.fulfill()
92-
}
93-
guard try HubListenerTestUtilities.waitForListener(with: syncStartedListener, timeout: 5.0) else {
94-
XCTFail("syncStartedListener not registered")
95-
return
96-
}
97-
9886
let syncReceivedInvoked = expectation(description: "Received SyncReceived event")
9987
var remoteNoteOptional: SocialNote?
10088
let syncReceivedListener = Amplify.Hub.listen(to: .dataStore, eventName: syncReceived) { payload in
@@ -115,54 +103,27 @@ class AWSDataStoreCategoryPluginAuthIntegrationTests: XCTestCase {
115103

116104
signIn(username: user1.username, password: user1.password)
117105

118-
wait(for: [syncStartedInvoked], timeout: TestCommonConstants.networkTimeout)
119106
wait(for: [syncReceivedInvoked], timeout: TestCommonConstants.networkTimeout)
120-
Amplify.Hub.removeListener(syncStartedListener)
121107
Amplify.Hub.removeListener(syncReceivedListener)
122108
guard let remoteNote = remoteNoteOptional else {
123109
XCTFail("Should have received a SyncReceived event with the remote note reconciled to local store")
124110
return
125111
}
126112
XCTAssertNotNil(remoteNote.owner)
127-
128-
let clearCompletedInvoked = expectation(description: "received clearCompleted invoked")
129-
let clearCompletedListener = Amplify.Hub.listen(to: .dataStore, eventName: clearCompleted) { _ in
130-
clearCompletedInvoked.fulfill()
131-
}
132-
guard try HubListenerTestUtilities.waitForListener(with: clearCompletedListener, timeout: 5.0) else {
133-
XCTFail("clearCompletedListener not registered")
134-
return
135-
}
136-
137-
signOut()
138-
wait(for: [clearCompletedInvoked], timeout: TestCommonConstants.networkTimeout)
139-
140-
let localNoteOptional = queryNote(byId: savedLocalNote.id)
141-
XCTAssertNil(localNoteOptional)
142113
}
143114

144-
/// A signed in user (the owner) creates some data in local store will be synced to cloud. After signing out,
115+
/// A signed in user (the owner) creates some data in local store will be synced to cloud. After `DataStore.clear`,
145116
/// the data can no longer be retrieved. Signing back in with another user will update the local store with all
146117
/// the data that can be read by that the user in the sync process. Then other user can read the owner's data.
147118
///
148119
/// - Given: A DataStore plugin configured with auth enabled SocialNote model that can be read others.
149120
/// - When:
150-
/// - The owner user is signed in, then user can save a note successfully
151-
/// - Owner signs out, then retrieving the note returns nil
121+
/// - The owner user is signed in, user saves a note, syncReceived successfully
122+
/// - Owner signs out, `DataStore.clear`, then retrieving the note returns nil
152123
/// - The other user signs in, sync engine is started and does a full sync
153124
/// - The other user is able to retrieve the owner's note
154125
func testOwnerCreatedDataCanBeReadByOtherUsersForReadableModel() throws {
155-
let syncStartedInvoked = expectation(description: "Sync started after sign In")
156-
let syncStartedListener = Amplify.Hub.listen(to: .dataStore, eventName: syncStarted) { _ in
157-
syncStartedInvoked.fulfill()
158-
}
159-
guard try HubListenerTestUtilities.waitForListener(with: syncStartedListener, timeout: 5.0) else {
160-
XCTFail("syncStartedListener not registered")
161-
return
162-
}
163126
signIn(username: user1.username, password: user1.password)
164-
wait(for: [syncStartedInvoked], timeout: TestCommonConstants.networkTimeout)
165-
Amplify.Hub.removeListener(syncStartedListener)
166127

167128
let id = UUID().uuidString
168129
let localNote = SocialNote(id: id, content: "owner created content", owner: nil)
@@ -207,17 +168,19 @@ class AWSDataStoreCategoryPluginAuthIntegrationTests: XCTestCase {
207168
return
208169
}
209170

210-
let clearCompletedInvoked = expectation(description: "received clearCompleted invoked")
211-
let clearCompletedListener = Amplify.Hub.listen(to: .dataStore, eventName: clearCompleted) { _ in
212-
clearCompletedInvoked.fulfill()
213-
}
214-
guard try HubListenerTestUtilities.waitForListener(with: clearCompletedListener, timeout: 5.0) else {
215-
XCTFail("clearCompletedListener not registered")
216-
return
217-
}
218171
signOut()
172+
173+
let clearCompletedInvoked = expectation(description: "clear completed")
174+
Amplify.DataStore.clear { result in
175+
switch result {
176+
case .success:
177+
clearCompletedInvoked.fulfill()
178+
case .failure(let error):
179+
XCTFail("Failed to clear \(error)")
180+
}
181+
}
182+
219183
wait(for: [clearCompletedInvoked], timeout: TestCommonConstants.networkTimeout)
220-
Amplify.Hub.removeListener(clearCompletedListener)
221184

222185
let localNoteOptional = queryNote(byId: id)
223186
XCTAssertNil(localNoteOptional)
@@ -264,18 +227,5 @@ class AWSDataStoreCategoryPluginAuthIntegrationTests: XCTestCase {
264227
}
265228

266229
XCTAssertEqual(owner, remoteNoteOwner)
267-
268-
let clearCompletedInvoked2 = expectation(description: "received clearCompleted invoked")
269-
let clearCompletedListener2 = Amplify.Hub.listen(to: .dataStore, eventName: clearCompleted) { _ in
270-
clearCompletedInvoked2.fulfill()
271-
}
272-
guard try HubListenerTestUtilities.waitForListener(with: clearCompletedListener2, timeout: 5.0) else {
273-
XCTFail("clearCompletedListener not registered")
274-
return
275-
}
276-
277-
signOut()
278-
wait(for: [clearCompletedInvoked2], timeout: TestCommonConstants.networkTimeout)
279-
Amplify.Hub.removeListener(clearCompletedListener2)
280230
}
281231
}

AmplifyPlugins/DataStore/AWSDataStoreCategoryPluginTests/Sync/SubscriptionSync/Support/MockSQLiteStorageEngineAdapter.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ class MockStorageEngineBehavior: StorageEngineBehavior {
187187
return PassthroughSubject<StorageEngineEvent, DataStoreError>().eraseToAnyPublisher()
188188
}
189189

190-
func tryStartSync() {
190+
func startSync() {
191191
}
192192

193193
func setUp(models: [Model.Type]) throws {

0 commit comments

Comments
 (0)