-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathQueryInfo.ts
437 lines (381 loc) · 14.5 KB
/
QueryInfo.ts
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import { DocumentNode, GraphQLError } from 'graphql';
import { equal } from "@wry/equality";
import { Cache, ApolloCache } from '../cache';
import { WatchQueryOptions, ErrorPolicy } from './watchQueryOptions';
import { ObservableQuery } from './ObservableQuery';
import { QueryListener } from './types';
import { FetchResult } from '../link/core';
import {
ObservableSubscription,
isNonEmptyArray,
graphQLResultHasError,
canUseWeakMap,
} from '../utilities';
import {
NetworkStatus,
isNetworkRequestInFlight,
} from './networkStatus';
import { ApolloError } from '../errors';
export type QueryStoreValue = Pick<QueryInfo,
| "variables"
| "networkStatus"
| "networkError"
| "graphQLErrors"
>;
const destructiveMethodCounts = new (
canUseWeakMap ? WeakMap : Map
)<ApolloCache<any>, number>();
function wrapDestructiveCacheMethod(
cache: ApolloCache<any>,
methodName: keyof ApolloCache<any>,
) {
const original = cache[methodName];
if (typeof original === "function") {
cache[methodName] = function () {
destructiveMethodCounts.set(
cache,
// The %1e15 allows the count to wrap around to 0 safely every
// quadrillion evictions, so there's no risk of overflow. To be
// clear, this is more of a pedantic principle than something
// that matters in any conceivable practical scenario.
(destructiveMethodCounts.get(cache)! + 1) % 1e15,
);
return original.apply(this, arguments);
};
}
}
function cancelNotifyTimeout(info: QueryInfo) {
if (info["notifyTimeout"]) {
clearTimeout(info["notifyTimeout"]);
info["notifyTimeout"] = void 0;
}
}
// A QueryInfo object represents a single query managed by the
// QueryManager, which tracks all QueryInfo objects by queryId in its
// this.queries Map. QueryInfo objects store the latest results and errors
// for the given query, and are responsible for reporting those results to
// the corresponding ObservableQuery, via the QueryInfo.notify method.
// Results are reported asynchronously whenever setDiff marks the
// QueryInfo object as dirty, though a call to the QueryManager's
// broadcastQueries method may trigger the notification before it happens
// automatically. This class used to be a simple interface type without
// any field privacy or meaningful methods, which is why it still has so
// many public fields. The effort to lock down and simplify the QueryInfo
// interface is ongoing, and further improvements are welcome.
export class QueryInfo {
listeners = new Set<QueryListener>();
document: DocumentNode | null = null;
lastRequestId = 1;
subscriptions = new Set<ObservableSubscription>();
variables?: Record<string, any>;
networkStatus?: NetworkStatus;
networkError?: Error | null;
graphQLErrors?: ReadonlyArray<GraphQLError>;
stopped = false;
constructor(private cache: ApolloCache<any>) {
// Track how often cache.evict is called, since we want eviction to
// override the feud-stopping logic in the markResult method, by
// causing shouldWrite to return true. Wrapping the cache.evict method
// is a bit of a hack, but it saves us from having to make eviction
// counting an official part of the ApolloCache API.
if (!destructiveMethodCounts.has(cache)) {
destructiveMethodCounts.set(cache, 0);
wrapDestructiveCacheMethod(cache, "evict");
wrapDestructiveCacheMethod(cache, "modify");
wrapDestructiveCacheMethod(cache, "reset");
}
}
public init(query: {
document: DocumentNode;
variables: Record<string, any> | undefined,
// The initial networkStatus for this fetch, most often
// NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
// or setVariables.
networkStatus?: NetworkStatus,
observableQuery?: ObservableQuery<any>;
lastRequestId?: number;
}): this {
let networkStatus = query.networkStatus || NetworkStatus.loading;
if (this.variables &&
this.networkStatus !== NetworkStatus.loading &&
!equal(this.variables, query.variables)) {
networkStatus = NetworkStatus.setVariables;
}
if (!equal(query.variables, this.variables)) {
this.diff = null;
}
Object.assign(this, {
document: query.document,
variables: query.variables,
networkError: null,
graphQLErrors: this.graphQLErrors || [],
networkStatus,
});
if (query.observableQuery) {
this.setObservableQuery(query.observableQuery);
}
if (query.lastRequestId) {
this.lastRequestId = query.lastRequestId;
}
return this;
}
private dirty: boolean = false;
private notifyTimeout?: ReturnType<typeof setTimeout>;
private diff: Cache.DiffResult<any> | null = null;
getDiff(variables = this.variables): Cache.DiffResult<any> {
if (this.diff && equal(variables, this.variables)) {
return this.diff;
}
this.updateWatch(this.variables = variables);
return this.diff = this.cache.diff({
query: this.document!,
variables,
returnPartialData: true,
optimistic: true,
});
}
setDiff(diff: Cache.DiffResult<any> | null) {
const oldDiff = this.diff;
this.diff = diff;
if (!this.dirty &&
(diff && diff.result) !== (oldDiff && oldDiff.result)) {
this.dirty = true;
if (!this.notifyTimeout) {
this.notifyTimeout = setTimeout(() => this.notify(), 0);
}
}
}
public readonly observableQuery: ObservableQuery<any> | null = null;
private oqListener?: QueryListener;
setObservableQuery(oq: ObservableQuery<any> | null) {
if (oq === this.observableQuery) return;
if (this.oqListener) {
this.listeners.delete(this.oqListener);
}
(this as any).observableQuery = oq;
if (oq) {
oq["queryInfo"] = this;
this.listeners.add(this.oqListener = () => {
// If this.diff came from an optimistic transaction, deliver the
// current cache data to the ObservableQuery, but don't perform a
// full reobservation, since oq.reobserve might make a network
// request, and we don't want to trigger network requests for
// optimistic updates.
if (this.getDiff().fromOptimisticTransaction) {
oq["observe"]();
} else {
oq.reobserve();
}
});
} else {
delete this.oqListener;
}
}
notify() {
cancelNotifyTimeout(this);
if (this.shouldNotify()) {
this.listeners.forEach(listener => listener(this));
}
this.dirty = false;
}
private shouldNotify() {
if (!this.dirty || !this.listeners.size) {
return false;
}
if (isNetworkRequestInFlight(this.networkStatus) &&
this.observableQuery) {
const { fetchPolicy } = this.observableQuery.options;
if (fetchPolicy !== "cache-only" &&
fetchPolicy !== "cache-and-network") {
return false;
}
}
return true;
}
public stop() {
if (!this.stopped) {
this.stopped = true;
this.cancel();
// Revert back to the no-op version of cancel inherited from
// QueryInfo.prototype.
delete this.cancel;
this.subscriptions.forEach(sub => sub.unsubscribe());
const oq = this.observableQuery;
if (oq) oq.stopPolling();
}
}
// This method is a no-op by default, until/unless overridden by the
// updateWatch method.
private cancel() {}
private lastWatch?: Cache.WatchOptions;
private updateWatch(variables = this.variables) {
const oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return;
}
if (!this.lastWatch ||
this.lastWatch.query !== this.document ||
!equal(variables, this.lastWatch.variables)) {
this.cancel();
this.cancel = this.cache.watch(this.lastWatch = {
query: this.document!,
variables,
optimistic: true,
callback: diff => this.setDiff(diff),
});
}
}
private lastWrite?: {
result: FetchResult<any>;
variables: WatchQueryOptions["variables"];
dmCount: number | undefined;
};
private shouldWrite(
result: FetchResult<any>,
variables: WatchQueryOptions["variables"],
) {
const { lastWrite } = this;
return !(
lastWrite &&
// If cache.evict has been called since the last time we wrote this
// data into the cache, there's a chance writing this result into
// the cache will repair what was evicted.
lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
equal(variables, lastWrite.variables) &&
equal(result.data, lastWrite.result.data)
);
}
public markResult<T>(
result: FetchResult<T>,
options: Pick<WatchQueryOptions,
| "variables"
| "fetchPolicy"
| "errorPolicy">,
allowCacheWrite: boolean,
) {
this.graphQLErrors = isNonEmptyArray(result.errors) ? result.errors : [];
// If there is a pending notify timeout, cancel it because we are
// about to update this.diff to hold the latest data, and we can
// assume the data will be broadcast through some other mechanism.
cancelNotifyTimeout(this);
if (options.fetchPolicy === 'no-cache') {
this.diff = { result: result.data, complete: true };
} else if (allowCacheWrite) {
if (shouldWriteResult(result, options.errorPolicy)) {
// Using a transaction here so we have a chance to read the result
// back from the cache before the watch callback fires as a result
// of writeQuery, so we can store the new diff quietly and ignore
// it when we receive it redundantly from the watch callback.
this.cache.performTransaction(cache => {
if (this.shouldWrite(result, options.variables)) {
cache.writeQuery({
query: this.document!,
data: result.data as T,
variables: options.variables,
});
this.lastWrite = {
result,
variables: options.variables,
dmCount: destructiveMethodCounts.get(this.cache),
};
} else {
// If result is the same as the last result we received from
// the network (and the variables match too), avoid writing
// result into the cache again. The wisdom of skipping this
// cache write is far from obvious, since any cache write
// could be the one that puts the cache back into a desired
// state, fixing corruption or missing data. However, if we
// always write every network result into the cache, we enable
// feuds between queries competing to update the same data in
// incompatible ways, which can lead to an endless cycle of
// cache broadcasts and useless network requests. As with any
// feud, eventually one side must step back from the brink,
// letting the other side(s) have the last word(s). There may
// be other points where we could break this cycle, such as
// silencing the broadcast for cache.writeQuery (not a good
// idea, since it just delays the feud a bit) or somehow
// avoiding the network request that just happened (also bad,
// because the server could return useful new data). All
// options considered, skipping this cache write seems to be
// the least damaging place to break the cycle, because it
// reflects the intuition that we recently wrote this exact
// result into the cache, so the cache *should* already/still
// contain this data. If some other query has clobbered that
// data in the meantime, that's too bad, but there will be no
// winners if every query blindly reverts to its own version
// of the data. This approach also gives the network a chance
// to return new data, which will be written into the cache as
// usual, notifying only those queries that are directly
// affected by the cache updates, as usual. In the future, an
// even more sophisticated cache could perhaps prevent or
// mitigate the clobbering somehow, but that would make this
// particular cache write even less important, and thus
// skipping it would be even safer than it is today.
if (this.diff && this.diff.complete) {
// Reuse data from the last good (complete) diff that we
// received, when possible.
result.data = this.diff.result;
return;
}
// If the previous this.diff was incomplete, fall through to
// re-reading the latest data with cache.diff, below.
}
const diff = cache.diff<T>({
query: this.document!,
variables: options.variables,
returnPartialData: true,
optimistic: true,
});
// In case the QueryManager stops this QueryInfo before its
// results are delivered, it's important to avoid restarting the
// cache watch when markResult is called.
if (!this.stopped) {
// Any time we're about to update this.diff, we need to make
// sure we've started watching the cache.
this.updateWatch(options.variables);
}
// If we're allowed to write to the cache, and we can read a
// complete result from the cache, update result.data to be the
// result from the cache, rather than the raw network result.
// Set without setDiff to avoid triggering a notify call, since
// we have other ways of notifying for this result.
this.diff = diff;
if (diff.complete) {
result.data = diff.result;
}
});
} else {
this.lastWrite = void 0;
}
}
}
public markReady() {
this.networkError = null;
return this.networkStatus = NetworkStatus.ready;
}
public markError(error: ApolloError) {
this.networkStatus = NetworkStatus.error;
this.lastWrite = void 0;
cancelNotifyTimeout(this);
if (error.graphQLErrors) {
this.graphQLErrors = error.graphQLErrors;
}
if (error.networkError) {
this.networkError = error.networkError;
}
return error;
}
}
export function shouldWriteResult<T>(
result: FetchResult<T>,
errorPolicy: ErrorPolicy = "none",
) {
const ignoreErrors =
errorPolicy === "ignore" ||
errorPolicy === "all";
let writeWithErrors = !graphQLResultHasError(result);
if (!writeWithErrors && ignoreErrors && result.data) {
writeWithErrors = true;
}
return writeWithErrors;
}