From a43eff21bd644afd44b6b8574303cb3bbf09efab Mon Sep 17 00:00:00 2001 From: Evgenii Kononenko Date: Wed, 31 Jul 2024 19:20:39 +0200 Subject: [PATCH] tokens store - made thread safe --- Sources/Auth/Storage/DefaultTokensStore.swift | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/Sources/Auth/Storage/DefaultTokensStore.swift b/Sources/Auth/Storage/DefaultTokensStore.swift index 6823d7c3..4b0fb740 100644 --- a/Sources/Auth/Storage/DefaultTokensStore.swift +++ b/Sources/Auth/Storage/DefaultTokensStore.swift @@ -9,6 +9,8 @@ final class DefaultTokensStore: TokensStore { private var latestTokens: Tokens? + private let credentialsQueue = DispatchQueue(label: "com.tidal.auth.credentialsQueue") + init(credentialsKey: String, credentialsAccessGroup: String?) { storageKey = "\(credentialsKey)_\(PREFS_FILE_NAME)" self.credentialsKey = credentialsKey @@ -20,8 +22,12 @@ final class DefaultTokensStore: TokensStore { } func getLatestTokens() throws -> Tokens? { - latestTokens = try latestTokens ?? loadTokens() - return latestTokens + try credentialsQueue.sync { + if latestTokens == nil { + latestTokens = try loadTokens() + } + return latestTokens + } } private func loadTokens() throws -> Tokens? { @@ -38,7 +44,7 @@ final class DefaultTokensStore: TokensStore { // try to decode legacy tokens, convert them to tokens and save tokens print("Failed to decode tokens. Attempting to decode legacy tokens") if let convertedLegacyTokens = try? decoder.decode(LegacyTokens.self, from: data).toTokens() { - try saveTokens(tokens: convertedLegacyTokens) + try saveTokensUnsafe(tokens: convertedLegacyTokens) return convertedLegacyTokens } else { throw error @@ -48,14 +54,22 @@ final class DefaultTokensStore: TokensStore { } func saveTokens(tokens: Tokens) throws { + try credentialsQueue.sync { + try saveTokensUnsafe(tokens: tokens) + } + } + + func eraseTokens() throws { + try credentialsQueue.sync { + latestTokens = nil + try encryptedStorage.removeAll() + } + } + + private func saveTokensUnsafe(tokens: Tokens) throws { let data = try JSONEncoder().encode(tokens) encryptedStorage[credentialsKey] = String(data: data, encoding: .utf8) latestTokens = tokens // TODO: emit credentails update: `bus.emit(CredentialsUpdatedMessage)` } - - func eraseTokens() throws { - latestTokens = nil - try encryptedStorage.removeAll() - } }