Skip to content
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

use lock in InMemoryNormalizedCache to avoid race conditions #552

Merged
merged 2 commits into from
Jan 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Sources/Apollo/InMemoryNormalizedCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Foundation

public final class InMemoryNormalizedCache: NormalizedCache {
private var records: RecordSet
private let recordsLock = NSRecursiveLock()

public init(records: RecordSet = RecordSet()) {
self.records = records
Expand All @@ -10,7 +11,9 @@ public final class InMemoryNormalizedCache: NormalizedCache {
public func loadRecords(forKeys keys: [CacheKey],
callbackQueue: DispatchQueue?,
completion: @escaping (Result<[Record?], Error>) -> Void) {
self.recordsLock.lock()
let records = keys.map { self.records[$0] }
self.recordsLock.unlock()
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .success(records))
Expand All @@ -19,15 +22,19 @@ public final class InMemoryNormalizedCache: NormalizedCache {
public func merge(records: RecordSet,
callbackQueue: DispatchQueue?,
completion: @escaping (Result<Set<CacheKey>, Error>) -> Void) {
self.recordsLock.lock()
let cacheKeys = self.records.merge(records: records)
self.recordsLock.unlock()
DispatchQueue.apollo_returnResultAsyncIfNeeded(on: callbackQueue,
action: completion,
result: .success(cacheKeys))
}

public func clear(callbackQueue: DispatchQueue?,
completion: ((Result<Void, Error>) -> Void)?) {
self.recordsLock.lock()
self.records.clear()
self.recordsLock.unlock()

guard let completion = completion else {
return
Expand Down
91 changes: 91 additions & 0 deletions Tests/ApolloCacheDependentTests/FetchQueryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -383,4 +383,95 @@ class FetchQueryTests: XCTestCase {
waitForExpectations(timeout: 5, handler: nil)
}
}

func testThreadedCache() throws {
let cache = InMemoryNormalizedCache()

let networkTransport1 = MockNetworkTransport(body: [
"data": [
"hero": [
"id": "1000",
"name": "Luke Skywalker",
"__typename": "Human",
"friends": [
["__typename": "Human", "name": "Leia Organa", "id": "1003"],
["__typename": "Human", "name": "Han Solo", "id": "1002"],
]
]
]
])

let networkTransport2 = MockNetworkTransport(body: [
"data": [
"hero": [
"id": "1002",
"name": "Han Solo",
"__typename": "Human",
"friends": [
["__typename": "Human", "name": "Leia Organa", "id": "1003"],
["__typename": "Human", "name": "Luke Skywalker", "id": "1000"],
]
]
]
])

let store = ApolloStore(cache: cache)
let store2 = ApolloStore(cache: cache)

let client1 = ApolloClient(networkTransport: networkTransport1, store: store)
let client2 = ApolloClient(networkTransport: networkTransport2, store: store2)

let group = DispatchGroup()

let watcherQueue = DispatchQueue(label: "test watcher queue")
var watchers = [GraphQLQueryWatcher<HeroAndFriendsNamesWithIDsQuery>]()

for _ in 0...1000 {

group.enter()
DispatchQueue.global().async {
let watcher =
client1.watch(
query: HeroAndFriendsNamesWithIDsQuery(), cachePolicy: .returnCacheDataAndFetch) { result in
if result.value?.source == .some(.server) {
group.leave()
}
}

watcherQueue.sync {
watchers.append(watcher)
}
}

group.enter()
DispatchQueue.global().async {
let watcher =
client2.watch(
query: HeroAndFriendsNamesWithIDsQuery(), cachePolicy: .returnCacheDataAndFetch) { result in
if result.value?.source == .some(.server) {
group.leave()
}
}

watcherQueue.sync {
watchers.append(watcher)
}
}

group.enter()
DispatchQueue.global().async {
_ = client1.clearCache() { _ in
group.leave()
}
}

}

let expectation = self.expectation(description: "Fetching query")
group.notify(queue: .main) {
expectation.fulfill()
}
self.wait(for: [expectation], timeout: 10)

}
}