-
Notifications
You must be signed in to change notification settings - Fork 739
/
Copy pathApolloStore.swift
379 lines (335 loc) · 13.7 KB
/
ApolloStore.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import Foundation
#if !COCOAPODS
import ApolloAPI
#endif
public typealias DidChangeKeysFunc = (Set<CacheKey>, UUID?) -> Void
/// The `ApolloStoreSubscriber` provides a means to observe changes to items in the ApolloStore.
/// This protocol is available for advanced use cases only. Most users will prefer using `ApolloClient.watch(query:)`.
public protocol ApolloStoreSubscriber: AnyObject {
/// A callback that can be received by subscribers when keys are changed within the database
///
/// - Parameters:
/// - store: The store which made the changes
/// - changedKeys: The list of changed keys
/// - contextIdentifier: [optional] A unique identifier for the request that kicked off this change, to assist in de-duping cache hits for watchers.
func store(_ store: ApolloStore,
didChangeKeys changedKeys: Set<CacheKey>,
contextIdentifier: UUID?)
}
/// The `ApolloStore` class acts as a local cache for normalized GraphQL results.
public class ApolloStore {
private let cache: any NormalizedCache
private let queue: DispatchQueue
internal var subscribers: [any ApolloStoreSubscriber] = []
/// Designated initializer
/// - Parameters:
/// - cache: An instance of `normalizedCache` to use to cache results.
/// Defaults to an `InMemoryNormalizedCache`.
public init(cache: any NormalizedCache = InMemoryNormalizedCache()) {
self.cache = cache
self.queue = DispatchQueue(label: "com.apollographql.ApolloStore", attributes: .concurrent)
}
fileprivate func didChangeKeys(_ changedKeys: Set<CacheKey>, identifier: UUID?) {
for subscriber in self.subscribers {
subscriber.store(self, didChangeKeys: changedKeys, contextIdentifier: identifier)
}
}
/// Clears the instance of the cache. Note that a cache can be shared across multiple `ApolloClient` objects, so clearing that underlying cache will clear it for all clients.
///
/// - Parameters:
/// - callbackQueue: The queue to call the completion block on. Defaults to `DispatchQueue.main`.
/// - completion: [optional] A completion block to be called after records are merged into the cache.
public func clearCache(callbackQueue: DispatchQueue = .main, completion: ((Result<Void, any Swift.Error>) -> Void)? = nil) {
queue.async(flags: .barrier) {
let result = Result { try self.cache.clear() }
DispatchQueue.returnResultAsyncIfNeeded(
on: callbackQueue,
action: completion,
result: result
)
}
}
/// Merges a `RecordSet` into the normalized cache.
/// - Parameters:
/// - records: The records to be merged into the cache.
/// - identifier: [optional] A unique identifier for the request that kicked off this change,
/// to assist in de-duping cache hits for watchers.
/// - callbackQueue: The queue to call the completion block on. Defaults to `DispatchQueue.main`.
/// - completion: [optional] A completion block to be called after records are merged into the cache.
public func publish(records: RecordSet, identifier: UUID? = nil, callbackQueue: DispatchQueue = .main, completion: ((Result<Void, any Swift.Error>) -> Void)? = nil) {
queue.async(flags: .barrier) {
do {
let changedKeys = try self.cache.merge(records: records)
self.didChangeKeys(changedKeys, identifier: identifier)
DispatchQueue.returnResultAsyncIfNeeded(
on: callbackQueue,
action: completion,
result: .success(())
)
} catch {
DispatchQueue.returnResultAsyncIfNeeded(
on: callbackQueue,
action: completion,
result: .failure(error)
)
}
}
}
/// Subscribes to notifications of ApolloStore content changes
///
/// - Parameters:
/// - subscriber: A subscriber to receive content change notificatons. To avoid a retain cycle,
/// ensure you call `unsubscribe` on this subscriber before it goes out of scope.
public func subscribe(_ subscriber: any ApolloStoreSubscriber) {
queue.async(flags: .barrier) {
self.subscribers.append(subscriber)
}
}
/// Unsubscribes from notifications of ApolloStore content changes
///
/// - Parameters:
/// - subscriber: A subscribe that has previously been added via `subscribe`. To avoid retain cycles,
/// call `unsubscribe` on all active subscribers before they go out of scope.
public func unsubscribe(_ subscriber: any ApolloStoreSubscriber) {
queue.async(flags: .barrier) {
self.subscribers = self.subscribers.filter({ $0 !== subscriber })
}
}
/// Performs an operation within a read transaction
///
/// - Parameters:
/// - body: The body of the operation to perform.
/// - callbackQueue: [optional] The callback queue to use to perform the completion block on. Will perform on the current queue if not provided. Defaults to nil.
/// - completion: [optional] The completion block to perform when the read transaction completes. Defaults to nil.
public func withinReadTransaction<T>(
_ body: @escaping (ReadTransaction) throws -> T,
callbackQueue: DispatchQueue? = nil,
completion: ((Result<T, any Swift.Error>) -> Void)? = nil
) {
self.queue.async {
do {
let returnValue = try body(ReadTransaction(store: self))
DispatchQueue.returnResultAsyncIfNeeded(
on: callbackQueue,
action: completion,
result: .success(returnValue)
)
} catch {
DispatchQueue.returnResultAsyncIfNeeded(
on: callbackQueue,
action: completion,
result: .failure(error)
)
}
}
}
/// Performs an operation within a read-write transaction
///
/// - Parameters:
/// - body: The body of the operation to perform
/// - callbackQueue: [optional] a callback queue to perform the action on. Will perform on the current queue if not provided. Defaults to nil.
/// - completion: [optional] a completion block to fire when the read-write transaction completes. Defaults to nil.
public func withinReadWriteTransaction<T>(
_ body: @escaping (ReadWriteTransaction) throws -> T,
callbackQueue: DispatchQueue? = nil,
completion: ((Result<T, any Swift.Error>) -> Void)? = nil
) {
self.queue.async(flags: .barrier) {
do {
let returnValue = try body(ReadWriteTransaction(store: self))
DispatchQueue.returnResultAsyncIfNeeded(
on: callbackQueue,
action: completion,
result: .success(returnValue)
)
} catch {
DispatchQueue.returnResultAsyncIfNeeded(
on: callbackQueue,
action: completion,
result: .failure(error)
)
}
}
}
/// Loads the results for the given query from the cache.
///
/// - Parameters:
/// - query: The query to load results for
/// - resultHandler: The completion handler to execute on success or error
public func load<Operation: GraphQLOperation>(
_ operation: Operation,
callbackQueue: DispatchQueue? = nil,
resultHandler: @escaping GraphQLResultHandler<Operation.Data>
) {
withinReadTransaction({ transaction in
let (data, dependentKeys) = try transaction.readObject(
ofType: Operation.Data.self,
withKey: CacheReference.rootCacheReference(for: Operation.operationType).key,
variables: operation.__variables,
accumulator: zip(GraphQLSelectionSetMapper<Operation.Data>(),
GraphQLDependencyTracker())
)
return GraphQLResult(
data: data,
extensions: nil,
errors: nil,
source:.cache,
dependentKeys: dependentKeys
)
}, callbackQueue: callbackQueue, completion: resultHandler)
}
public enum Error: Swift.Error {
case notWithinReadTransaction
}
public class ReadTransaction {
fileprivate let cache: any NormalizedCache
fileprivate lazy var loader: DataLoader<CacheKey, Record> = DataLoader { [weak self] batchLoad in
guard let self else { return [:] }
return try cache.loadRecords(forKeys: batchLoad)
}
fileprivate lazy var executor = GraphQLExecutor(
executionSource: CacheDataExecutionSource(transaction: self)
)
fileprivate init(store: ApolloStore) {
self.cache = store.cache
}
public func read<Query: GraphQLQuery>(query: Query) throws -> Query.Data {
return try readObject(
ofType: Query.Data.self,
withKey: CacheReference.rootCacheReference(for: Query.operationType).key,
variables: query.__variables
)
}
public func readObject<SelectionSet: RootSelectionSet>(
ofType type: SelectionSet.Type,
withKey key: CacheKey,
variables: GraphQLOperation.Variables? = nil
) throws -> SelectionSet {
return try self.readObject(
ofType: type,
withKey: key,
variables: variables,
accumulator: GraphQLSelectionSetMapper<SelectionSet>()
)
}
func readObject<SelectionSet: RootSelectionSet, Accumulator: GraphQLResultAccumulator>(
ofType type: SelectionSet.Type,
withKey key: CacheKey,
variables: GraphQLOperation.Variables? = nil,
accumulator: Accumulator
) throws -> Accumulator.FinalResult {
let object = try loadObject(forKey: key).get()
return try executor.execute(
selectionSet: type,
on: object,
withRootCacheReference: CacheReference(key),
variables: variables,
accumulator: accumulator
)
}
final func loadObject(forKey key: CacheKey) -> PossiblyDeferred<Record> {
self.loader[key].map { record in
guard let record = record else { throw JSONDecodingError.missingValue }
return record
}
}
}
public final class ReadWriteTransaction: ReadTransaction {
fileprivate var updateChangedKeysFunc: DidChangeKeysFunc?
override init(store: ApolloStore) {
self.updateChangedKeysFunc = store.didChangeKeys
super.init(store: store)
}
public func update<CacheMutation: LocalCacheMutation>(
_ cacheMutation: CacheMutation,
_ body: (inout CacheMutation.Data) throws -> Void
) throws {
try updateObject(
ofType: CacheMutation.Data.self,
withKey: CacheReference.rootCacheReference(for: CacheMutation.operationType).key,
variables: cacheMutation.__variables,
body
)
}
public func updateObject<SelectionSet: MutableRootSelectionSet>(
ofType type: SelectionSet.Type,
withKey key: CacheKey,
variables: GraphQLOperation.Variables? = nil,
_ body: (inout SelectionSet) throws -> Void
) throws {
var object = try readObject(
ofType: type,
withKey: key,
variables: variables,
accumulator: GraphQLSelectionSetMapper<SelectionSet>(
handleMissingValues: .allowForOptionalFields
)
)
try body(&object)
try write(selectionSet: object, withKey: key, variables: variables)
}
public func write<CacheMutation: LocalCacheMutation>(
data: CacheMutation.Data,
for cacheMutation: CacheMutation
) throws {
try write(selectionSet: data,
withKey: CacheReference.rootCacheReference(for: CacheMutation.operationType).key,
variables: cacheMutation.__variables)
}
public func write<Operation: GraphQLOperation>(
data: Operation.Data,
for operation: Operation
) throws {
try write(selectionSet: data,
withKey: CacheReference.rootCacheReference(for: Operation.operationType).key,
variables: operation.__variables)
}
public func write<SelectionSet: RootSelectionSet>(
selectionSet: SelectionSet,
withKey key: CacheKey,
variables: GraphQLOperation.Variables? = nil
) throws {
let normalizer = ResultNormalizerFactory.selectionSetDataNormalizer()
let executor = GraphQLExecutor(executionSource: SelectionSetModelExecutionSource())
let records = try executor.execute(
selectionSet: SelectionSet.self,
on: selectionSet.__data,
withRootCacheReference: CacheReference(key),
variables: variables,
accumulator: normalizer
)
let changedKeys = try self.cache.merge(records: records)
// Remove cached records, so subsequent reads
// within the same transaction will reload the updated value.
loader.removeAll()
if let didChangeKeysFunc = self.updateChangedKeysFunc {
didChangeKeysFunc(changedKeys, nil)
}
}
/// Removes the object for the specified cache key. Does not cascade
/// or allow removal of only certain fields. Does nothing if an object
/// does not exist for the given key.
///
/// - Parameters:
/// - key: The cache key to remove the object for
public func removeObject(for key: CacheKey) throws {
try self.cache.removeRecord(for: key)
}
/// Removes records with keys that match the specified pattern. This method will only
/// remove whole records, it does not perform cascading deletes. This means only the
/// records with matched keys will be removed, and not any references to them. Key
/// matching is case-insensitive.
///
/// If you attempt to pass a cache path for a single field, this method will do nothing
/// since it won't be able to locate a record to remove based on that path.
///
/// - Note: This method can be very slow depending on the number of records in the cache.
/// It is recommended that this method be called in a background queue.
///
/// - Parameters:
/// - pattern: The pattern that will be applied to find matching keys.
public func removeObjects(matching pattern: CacheKey) throws {
try self.cache.removeRecords(matching: pattern)
}
}
}