relay-runtime 9.0.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/handlers/RelayDefaultHandlerProvider.js.flow +34 -0
  2. package/handlers/connection/ConnectionHandler.js.flow +549 -0
  3. package/handlers/connection/ConnectionInterface.js.flow +92 -0
  4. package/index.js +1 -1
  5. package/index.js.flow +314 -0
  6. package/lib/handlers/connection/ConnectionHandler.js +1 -3
  7. package/lib/index.js +1 -2
  8. package/lib/mutations/RelayDeclarativeMutationConfig.js +22 -45
  9. package/lib/mutations/RelayRecordProxy.js +1 -3
  10. package/lib/mutations/RelayRecordSourceMutator.js +1 -3
  11. package/lib/mutations/RelayRecordSourceProxy.js +1 -3
  12. package/lib/mutations/RelayRecordSourceSelectorProxy.js +1 -3
  13. package/lib/mutations/commitMutation.js +2 -0
  14. package/lib/mutations/validateMutation.js +13 -4
  15. package/lib/network/RelayObservable.js +9 -9
  16. package/lib/network/RelayQueryResponseCache.js +8 -6
  17. package/lib/query/fetchQueryInternal.js +1 -8
  18. package/lib/store/DataChecker.js +23 -51
  19. package/lib/store/RelayConcreteVariables.js +6 -2
  20. package/lib/store/RelayModernEnvironment.js +30 -12
  21. package/lib/store/RelayModernFragmentSpecResolver.js +9 -13
  22. package/lib/store/RelayModernQueryExecutor.js +73 -37
  23. package/lib/store/RelayModernRecord.js +14 -9
  24. package/lib/store/RelayModernStore.js +107 -70
  25. package/lib/store/RelayOperationTracker.js +35 -78
  26. package/lib/store/RelayOptimisticRecordSource.js +7 -5
  27. package/lib/store/RelayPublishQueue.js +1 -3
  28. package/lib/store/RelayReader.js +1 -3
  29. package/lib/store/RelayRecordSource.js +1 -3
  30. package/lib/store/RelayRecordSourceMapImpl.js +13 -18
  31. package/lib/store/RelayReferenceMarker.js +2 -6
  32. package/lib/store/RelayResponseNormalizer.js +9 -10
  33. package/lib/store/StoreInspector.js +7 -5
  34. package/lib/store/normalizeRelayPayload.js +6 -2
  35. package/lib/subscription/requestSubscription.js +4 -2
  36. package/lib/util/RelayFeatureFlags.js +1 -1
  37. package/lib/util/RelayReplaySubject.js +1 -3
  38. package/lib/util/createPayloadFor3DField.js +7 -2
  39. package/mutations/RelayDeclarativeMutationConfig.js.flow +380 -0
  40. package/mutations/RelayRecordProxy.js.flow +165 -0
  41. package/mutations/RelayRecordSourceMutator.js.flow +238 -0
  42. package/mutations/RelayRecordSourceProxy.js.flow +164 -0
  43. package/mutations/RelayRecordSourceSelectorProxy.js.flow +119 -0
  44. package/mutations/applyOptimisticMutation.js.flow +76 -0
  45. package/mutations/commitLocalUpdate.js.flow +24 -0
  46. package/mutations/commitMutation.js.flow +184 -0
  47. package/mutations/validateMutation.js.flow +211 -0
  48. package/network/ConvertToExecuteFunction.js.flow +49 -0
  49. package/network/RelayNetwork.js.flow +84 -0
  50. package/network/RelayNetworkTypes.js.flow +123 -0
  51. package/network/RelayObservable.js.flow +634 -0
  52. package/network/RelayQueryResponseCache.js.flow +111 -0
  53. package/package.json +1 -1
  54. package/query/GraphQLTag.js.flow +166 -0
  55. package/query/fetchQuery.js.flow +47 -0
  56. package/query/fetchQueryInternal.js.flow +349 -0
  57. package/relay-runtime.js +2 -2
  58. package/relay-runtime.min.js +2 -2
  59. package/store/ClientID.js.flow +43 -0
  60. package/store/DataChecker.js.flow +426 -0
  61. package/store/RelayConcreteVariables.js.flow +96 -0
  62. package/store/RelayModernEnvironment.js.flow +526 -0
  63. package/store/RelayModernFragmentSpecResolver.js.flow +426 -0
  64. package/store/RelayModernOperationDescriptor.js.flow +88 -0
  65. package/store/RelayModernQueryExecutor.js.flow +1327 -0
  66. package/store/RelayModernRecord.js.flow +403 -0
  67. package/store/RelayModernSelector.js.flow +444 -0
  68. package/store/RelayModernStore.js.flow +757 -0
  69. package/store/RelayOperationTracker.js.flow +164 -0
  70. package/store/RelayOptimisticRecordSource.js.flow +119 -0
  71. package/store/RelayPublishQueue.js.flow +401 -0
  72. package/store/RelayReader.js.flow +376 -0
  73. package/store/RelayRecordSource.js.flow +29 -0
  74. package/store/RelayRecordSourceMapImpl.js.flow +87 -0
  75. package/store/RelayRecordState.js.flow +37 -0
  76. package/store/RelayReferenceMarker.js.flow +236 -0
  77. package/store/RelayResponseNormalizer.js.flow +556 -0
  78. package/store/RelayStoreTypes.js.flow +873 -0
  79. package/store/RelayStoreUtils.js.flow +218 -0
  80. package/store/StoreInspector.js.flow +173 -0
  81. package/store/ViewerPattern.js.flow +26 -0
  82. package/store/cloneRelayHandleSourceField.js.flow +66 -0
  83. package/store/createFragmentSpecResolver.js.flow +55 -0
  84. package/store/createRelayContext.js.flow +44 -0
  85. package/store/defaultGetDataID.js.flow +27 -0
  86. package/store/hasOverlappingIDs.js.flow +34 -0
  87. package/store/isRelayModernEnvironment.js.flow +27 -0
  88. package/store/normalizeRelayPayload.js.flow +51 -0
  89. package/store/readInlineData.js.flow +75 -0
  90. package/subscription/requestSubscription.js.flow +100 -0
  91. package/util/JSResourceTypes.flow.js.flow +20 -0
  92. package/util/NormalizationNode.js.flow +191 -0
  93. package/util/ReaderNode.js.flow +208 -0
  94. package/util/RelayConcreteNode.js.flow +80 -0
  95. package/util/RelayDefaultHandleKey.js.flow +17 -0
  96. package/util/RelayError.js.flow +33 -0
  97. package/util/RelayFeatureFlags.js.flow +30 -0
  98. package/util/RelayProfiler.js.flow +284 -0
  99. package/util/RelayReplaySubject.js.flow +134 -0
  100. package/util/RelayRuntimeTypes.js.flow +70 -0
  101. package/util/createPayloadFor3DField.js.flow +43 -0
  102. package/util/deepFreeze.js.flow +36 -0
  103. package/util/generateID.js.flow +21 -0
  104. package/util/getFragmentIdentifier.js.flow +52 -0
  105. package/util/getRelayHandleKey.js.flow +41 -0
  106. package/util/getRequestIdentifier.js.flow +41 -0
  107. package/util/isPromise.js.flow +21 -0
  108. package/util/isScalarAndEqual.js.flow +26 -0
  109. package/util/recycleNodesInto.js.flow +80 -0
  110. package/util/resolveImmediate.js.flow +30 -0
  111. package/util/stableCopy.js.flow +35 -0
@@ -0,0 +1,757 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow strict-local
8
+ * @format
9
+ */
10
+
11
+ // flowlint ambiguous-object-type:error
12
+
13
+ 'use strict';
14
+
15
+ const DataChecker = require('./DataChecker');
16
+ const RelayModernRecord = require('./RelayModernRecord');
17
+ const RelayOptimisticRecordSource = require('./RelayOptimisticRecordSource');
18
+ const RelayProfiler = require('../util/RelayProfiler');
19
+ const RelayReader = require('./RelayReader');
20
+ const RelayReferenceMarker = require('./RelayReferenceMarker');
21
+ const RelayStoreUtils = require('./RelayStoreUtils');
22
+
23
+ const deepFreeze = require('../util/deepFreeze');
24
+ const defaultGetDataID = require('./defaultGetDataID');
25
+ const hasOverlappingIDs = require('./hasOverlappingIDs');
26
+ const invariant = require('invariant');
27
+ const recycleNodesInto = require('../util/recycleNodesInto');
28
+ const resolveImmediate = require('../util/resolveImmediate');
29
+
30
+ const {ROOT_ID, ROOT_TYPE} = require('./RelayStoreUtils');
31
+
32
+ import type {DataID, Disposable} from '../util/RelayRuntimeTypes';
33
+ import type {Availability} from './DataChecker';
34
+ import type {GetDataID} from './RelayResponseNormalizer';
35
+ import type {
36
+ CheckOptions,
37
+ MutableRecordSource,
38
+ OperationAvailability,
39
+ OperationDescriptor,
40
+ OperationLoader,
41
+ RecordSource,
42
+ RequestDescriptor,
43
+ Scheduler,
44
+ SingularReaderSelector,
45
+ Snapshot,
46
+ Store,
47
+ UpdatedRecords,
48
+ } from './RelayStoreTypes';
49
+
50
+ export opaque type InvalidationState = {|
51
+ dataIDs: $ReadOnlyArray<DataID>,
52
+ invalidations: Map<DataID, ?number>,
53
+ |};
54
+
55
+ type Subscription = {
56
+ callback: (snapshot: Snapshot) => void,
57
+ snapshot: Snapshot,
58
+ stale: boolean,
59
+ backup: ?Snapshot,
60
+ ...
61
+ };
62
+
63
+ type InvalidationSubscription = {|
64
+ callback: () => void,
65
+ invalidationState: InvalidationState,
66
+ |};
67
+
68
+ const DEFAULT_RELEASE_BUFFER_SIZE = 0;
69
+
70
+ /**
71
+ * @public
72
+ *
73
+ * An implementation of the `Store` interface defined in `RelayStoreTypes`.
74
+ *
75
+ * Note that a Store takes ownership of all records provided to it: other
76
+ * objects may continue to hold a reference to such records but may not mutate
77
+ * them. The static Relay core is architected to avoid mutating records that may have been
78
+ * passed to a store: operations that mutate records will either create fresh
79
+ * records or clone existing records and modify the clones. Record immutability
80
+ * is also enforced in development mode by freezing all records passed to a store.
81
+ */
82
+ class RelayModernStore implements Store {
83
+ _currentWriteEpoch: number;
84
+ _gcHoldCounter: number;
85
+ _gcReleaseBufferSize: number;
86
+ _gcScheduler: Scheduler;
87
+ _getDataID: GetDataID;
88
+ _globalInvalidationEpoch: ?number;
89
+ _hasScheduledGC: boolean;
90
+ _index: number;
91
+ _invalidationSubscriptions: Set<InvalidationSubscription>;
92
+ _invalidatedRecordIDs: Set<DataID>;
93
+ _queryCacheExpirationTime: ?number;
94
+ _operationLoader: ?OperationLoader;
95
+ _optimisticSource: ?MutableRecordSource;
96
+ _recordSource: MutableRecordSource;
97
+ _releaseBuffer: Array<string>;
98
+ _roots: Map<
99
+ string,
100
+ {|
101
+ operation: OperationDescriptor,
102
+ refCount: number,
103
+ epoch: ?number,
104
+ fetchTime: ?number,
105
+ |},
106
+ >;
107
+ _shouldScheduleGC: boolean;
108
+ _subscriptions: Set<Subscription>;
109
+ _updatedRecordIDs: UpdatedRecords;
110
+
111
+ constructor(
112
+ source: MutableRecordSource,
113
+ options?: {|
114
+ gcScheduler?: ?Scheduler,
115
+ operationLoader?: ?OperationLoader,
116
+ UNSTABLE_DO_NOT_USE_getDataID?: ?GetDataID,
117
+ gcReleaseBufferSize?: ?number,
118
+ queryCacheExpirationTime?: ?number,
119
+ |},
120
+ ) {
121
+ // Prevent mutation of a record from outside the store.
122
+ if (__DEV__) {
123
+ const storeIDs = source.getRecordIDs();
124
+ for (let ii = 0; ii < storeIDs.length; ii++) {
125
+ const record = source.get(storeIDs[ii]);
126
+ if (record) {
127
+ RelayModernRecord.freeze(record);
128
+ }
129
+ }
130
+ }
131
+ this._currentWriteEpoch = 0;
132
+ this._gcHoldCounter = 0;
133
+ this._gcReleaseBufferSize =
134
+ options?.gcReleaseBufferSize ?? DEFAULT_RELEASE_BUFFER_SIZE;
135
+ this._gcScheduler = options?.gcScheduler ?? resolveImmediate;
136
+ this._getDataID =
137
+ options?.UNSTABLE_DO_NOT_USE_getDataID ?? defaultGetDataID;
138
+ this._globalInvalidationEpoch = null;
139
+ this._hasScheduledGC = false;
140
+ this._index = 0;
141
+ this._invalidationSubscriptions = new Set();
142
+ this._invalidatedRecordIDs = new Set();
143
+ this._queryCacheExpirationTime = options?.queryCacheExpirationTime;
144
+ this._operationLoader = options?.operationLoader ?? null;
145
+ this._optimisticSource = null;
146
+ this._recordSource = source;
147
+ this._releaseBuffer = [];
148
+ this._roots = new Map();
149
+ this._shouldScheduleGC = false;
150
+ this._subscriptions = new Set();
151
+ this._updatedRecordIDs = {};
152
+
153
+ initializeRecordSource(this._recordSource);
154
+ }
155
+
156
+ getSource(): RecordSource {
157
+ return this._optimisticSource ?? this._recordSource;
158
+ }
159
+
160
+ check(
161
+ operation: OperationDescriptor,
162
+ options?: CheckOptions,
163
+ ): OperationAvailability {
164
+ const selector = operation.root;
165
+ const source = this._optimisticSource ?? this._recordSource;
166
+ const globalInvalidationEpoch = this._globalInvalidationEpoch;
167
+
168
+ const rootEntry = this._roots.get(operation.request.identifier);
169
+ const operationLastWrittenAt = rootEntry != null ? rootEntry.epoch : null;
170
+
171
+ // Check if store has been globally invalidated
172
+ if (globalInvalidationEpoch != null) {
173
+ // If so, check if the operation we're checking was last written
174
+ // before or after invalidation occured.
175
+ if (
176
+ operationLastWrittenAt == null ||
177
+ operationLastWrittenAt <= globalInvalidationEpoch
178
+ ) {
179
+ // If the operation was written /before/ global invalidation occurred,
180
+ // or if this operation has never been written to the store before,
181
+ // we will consider the data for this operation to be stale
182
+ // (i.e. not resolvable from the store).
183
+ return {status: 'stale'};
184
+ }
185
+ }
186
+
187
+ const target = options?.target ?? source;
188
+ const handlers = options?.handlers ?? [];
189
+ const operationAvailability = DataChecker.check(
190
+ source,
191
+ target,
192
+ selector,
193
+ handlers,
194
+ this._operationLoader,
195
+ this._getDataID,
196
+ );
197
+
198
+ return getAvailabilityStatus(
199
+ operationAvailability,
200
+ operationLastWrittenAt,
201
+ rootEntry?.fetchTime,
202
+ this._queryCacheExpirationTime,
203
+ );
204
+ }
205
+
206
+ retain(operation: OperationDescriptor): Disposable {
207
+ const id = operation.request.identifier;
208
+ let disposed = false;
209
+ const dispose = () => {
210
+ // Ensure each retain can only dispose once
211
+ if (disposed) {
212
+ return;
213
+ }
214
+ disposed = true;
215
+ // For Flow: guard against the entry somehow not existing
216
+ const rootEntry = this._roots.get(id);
217
+ if (rootEntry == null) {
218
+ return;
219
+ }
220
+ // Decrement the ref count: if it becomes zero it is eligible
221
+ // for release.
222
+ rootEntry.refCount--;
223
+
224
+ if (rootEntry.refCount === 0) {
225
+ const {_queryCacheExpirationTime} = this;
226
+ const rootEntryIsStale =
227
+ rootEntry.fetchTime != null &&
228
+ _queryCacheExpirationTime != null &&
229
+ rootEntry.fetchTime <= Date.now() - _queryCacheExpirationTime;
230
+
231
+ if (rootEntryIsStale) {
232
+ this._roots.delete(id);
233
+ this._scheduleGC();
234
+ } else {
235
+ this._releaseBuffer.push(id);
236
+
237
+ // If the release buffer is now over-full, remove the least-recently
238
+ // added entry and schedule a GC. Note that all items in the release
239
+ // buffer have a refCount of 0.
240
+ if (this._releaseBuffer.length > this._gcReleaseBufferSize) {
241
+ const _id = this._releaseBuffer.shift();
242
+ this._roots.delete(_id);
243
+ this._scheduleGC();
244
+ }
245
+ }
246
+ }
247
+ };
248
+
249
+ const rootEntry = this._roots.get(id);
250
+ if (rootEntry != null) {
251
+ if (rootEntry.refCount === 0) {
252
+ // This entry should be in the release buffer, but it no longer belongs
253
+ // there since it's retained. Remove it to maintain the invariant that
254
+ // all release buffer entries have a refCount of 0.
255
+ this._releaseBuffer = this._releaseBuffer.filter(_id => _id !== id);
256
+ }
257
+ // If we've previously retained this operation, increment the refCount
258
+ rootEntry.refCount += 1;
259
+ } else {
260
+ // Otherwise create a new entry for the operation
261
+ this._roots.set(id, {
262
+ operation,
263
+ refCount: 1,
264
+ epoch: null,
265
+ fetchTime: null,
266
+ });
267
+ }
268
+
269
+ return {dispose};
270
+ }
271
+
272
+ lookup(selector: SingularReaderSelector): Snapshot {
273
+ const source = this.getSource();
274
+ const snapshot = RelayReader.read(source, selector);
275
+ if (__DEV__) {
276
+ deepFreeze(snapshot);
277
+ }
278
+ return snapshot;
279
+ }
280
+
281
+ // This method will return a list of updated owners from the subscriptions
282
+ notify(
283
+ sourceOperation?: OperationDescriptor,
284
+ invalidateStore?: boolean,
285
+ ): $ReadOnlyArray<RequestDescriptor> {
286
+ // Increment the current write when notifying after executing
287
+ // a set of changes to the store.
288
+ this._currentWriteEpoch++;
289
+
290
+ if (invalidateStore === true) {
291
+ this._globalInvalidationEpoch = this._currentWriteEpoch;
292
+ }
293
+
294
+ const source = this.getSource();
295
+ const updatedOwners = [];
296
+ this._subscriptions.forEach(subscription => {
297
+ const owner = this._updateSubscription(source, subscription);
298
+ if (owner != null) {
299
+ updatedOwners.push(owner);
300
+ }
301
+ });
302
+ this._invalidationSubscriptions.forEach(subscription => {
303
+ this._updateInvalidationSubscription(
304
+ subscription,
305
+ invalidateStore === true,
306
+ );
307
+ });
308
+ this._updatedRecordIDs = {};
309
+ this._invalidatedRecordIDs.clear();
310
+
311
+ // If a source operation was provided (indicating the operation
312
+ // that produced this update to the store), record the current epoch
313
+ // at which this operation was written.
314
+ if (sourceOperation != null) {
315
+ // We only track the epoch at which the operation was written if
316
+ // it was previously retained, to keep the size of our operation
317
+ // epoch map bounded. If a query wasn't retained, we assume it can
318
+ // may be deleted at any moment and thus is not relevant for us to track
319
+ // for the purposes of invalidation.
320
+ const id = sourceOperation.request.identifier;
321
+ const rootEntry = this._roots.get(id);
322
+ if (rootEntry != null) {
323
+ rootEntry.epoch = this._currentWriteEpoch;
324
+ rootEntry.fetchTime = Date.now();
325
+ } else if (
326
+ sourceOperation.request.node.params.operationKind === 'query' &&
327
+ this._gcReleaseBufferSize > 0 &&
328
+ this._releaseBuffer.length < this._gcReleaseBufferSize
329
+ ) {
330
+ // The operation isn't retained but there is space in the release buffer:
331
+ // temporarily track this operation in case the data can be reused soon.
332
+ const temporaryRootEntry = {
333
+ operation: sourceOperation,
334
+ refCount: 0,
335
+ epoch: this._currentWriteEpoch,
336
+ fetchTime: Date.now(),
337
+ };
338
+ this._releaseBuffer.push(id);
339
+ this._roots.set(id, temporaryRootEntry);
340
+ }
341
+ }
342
+
343
+ return updatedOwners;
344
+ }
345
+
346
+ publish(source: RecordSource, idsMarkedForInvalidation?: Set<DataID>): void {
347
+ const target = this._optimisticSource ?? this._recordSource;
348
+ updateTargetFromSource(
349
+ target,
350
+ source,
351
+ // We increment the current epoch at the end of the set of updates,
352
+ // in notify(). Here, we pass what will be the incremented value of
353
+ // the epoch to use to write to invalidated records.
354
+ this._currentWriteEpoch + 1,
355
+ idsMarkedForInvalidation,
356
+ this._updatedRecordIDs,
357
+ this._invalidatedRecordIDs,
358
+ );
359
+ }
360
+
361
+ subscribe(
362
+ snapshot: Snapshot,
363
+ callback: (snapshot: Snapshot) => void,
364
+ ): Disposable {
365
+ const subscription = {backup: null, callback, snapshot, stale: false};
366
+ const dispose = () => {
367
+ this._subscriptions.delete(subscription);
368
+ };
369
+ this._subscriptions.add(subscription);
370
+ return {dispose};
371
+ }
372
+
373
+ holdGC(): Disposable {
374
+ this._gcHoldCounter++;
375
+ const dispose = () => {
376
+ if (this._gcHoldCounter > 0) {
377
+ this._gcHoldCounter--;
378
+ if (this._gcHoldCounter === 0 && this._shouldScheduleGC) {
379
+ this._scheduleGC();
380
+ this._shouldScheduleGC = false;
381
+ }
382
+ }
383
+ };
384
+ return {dispose};
385
+ }
386
+
387
+ toJSON(): mixed {
388
+ return 'RelayModernStore()';
389
+ }
390
+
391
+ // Internal API
392
+ __getUpdatedRecordIDs(): UpdatedRecords {
393
+ return this._updatedRecordIDs;
394
+ }
395
+
396
+ // Returns the owner (RequestDescriptor) if the subscription was affected by the
397
+ // latest update, or null if it was not affected.
398
+ _updateSubscription(
399
+ source: RecordSource,
400
+ subscription: Subscription,
401
+ ): ?RequestDescriptor {
402
+ const {backup, callback, snapshot, stale} = subscription;
403
+ const hasOverlappingUpdates = hasOverlappingIDs(
404
+ snapshot.seenRecords,
405
+ this._updatedRecordIDs,
406
+ );
407
+ if (!stale && !hasOverlappingUpdates) {
408
+ return;
409
+ }
410
+ let nextSnapshot: Snapshot =
411
+ hasOverlappingUpdates || !backup
412
+ ? RelayReader.read(source, snapshot.selector)
413
+ : backup;
414
+ const nextData = recycleNodesInto(snapshot.data, nextSnapshot.data);
415
+ nextSnapshot = ({
416
+ data: nextData,
417
+ isMissingData: nextSnapshot.isMissingData,
418
+ seenRecords: nextSnapshot.seenRecords,
419
+ selector: nextSnapshot.selector,
420
+ }: Snapshot);
421
+ if (__DEV__) {
422
+ deepFreeze(nextSnapshot);
423
+ }
424
+ subscription.snapshot = nextSnapshot;
425
+ subscription.stale = false;
426
+ if (nextSnapshot.data !== snapshot.data) {
427
+ callback(nextSnapshot);
428
+ return snapshot.selector.owner;
429
+ }
430
+ }
431
+
432
+ lookupInvalidationState(dataIDs: $ReadOnlyArray<DataID>): InvalidationState {
433
+ const invalidations = new Map();
434
+ dataIDs.forEach(dataID => {
435
+ const record = this.getSource().get(dataID);
436
+ invalidations.set(
437
+ dataID,
438
+ RelayModernRecord.getInvalidationEpoch(record) ?? null,
439
+ );
440
+ });
441
+ invalidations.set('global', this._globalInvalidationEpoch);
442
+ return {
443
+ dataIDs,
444
+ invalidations,
445
+ };
446
+ }
447
+
448
+ checkInvalidationState(prevInvalidationState: InvalidationState): boolean {
449
+ const latestInvalidationState = this.lookupInvalidationState(
450
+ prevInvalidationState.dataIDs,
451
+ );
452
+ const currentInvalidations = latestInvalidationState.invalidations;
453
+ const prevInvalidations = prevInvalidationState.invalidations;
454
+
455
+ // Check if global invalidation has changed
456
+ if (
457
+ currentInvalidations.get('global') !== prevInvalidations.get('global')
458
+ ) {
459
+ return true;
460
+ }
461
+
462
+ // Check if the invalidation state for any of the ids has changed.
463
+ for (const dataID of prevInvalidationState.dataIDs) {
464
+ if (currentInvalidations.get(dataID) !== prevInvalidations.get(dataID)) {
465
+ return true;
466
+ }
467
+ }
468
+
469
+ return false;
470
+ }
471
+
472
+ subscribeToInvalidationState(
473
+ invalidationState: InvalidationState,
474
+ callback: () => void,
475
+ ): Disposable {
476
+ const subscription = {callback, invalidationState};
477
+ const dispose = () => {
478
+ this._invalidationSubscriptions.delete(subscription);
479
+ };
480
+ this._invalidationSubscriptions.add(subscription);
481
+ return {dispose};
482
+ }
483
+
484
+ _updateInvalidationSubscription(
485
+ subscription: InvalidationSubscription,
486
+ invalidatedStore: boolean,
487
+ ) {
488
+ const {callback, invalidationState} = subscription;
489
+ const {dataIDs} = invalidationState;
490
+ const isSubscribedToInvalidatedIDs =
491
+ invalidatedStore ||
492
+ dataIDs.some(dataID => this._invalidatedRecordIDs.has(dataID));
493
+ if (!isSubscribedToInvalidatedIDs) {
494
+ return;
495
+ }
496
+ callback();
497
+ }
498
+
499
+ snapshot(): void {
500
+ invariant(
501
+ this._optimisticSource == null,
502
+ 'RelayModernStore: Unexpected call to snapshot() while a previous ' +
503
+ 'snapshot exists.',
504
+ );
505
+ this._subscriptions.forEach(subscription => {
506
+ // Backup occurs after writing a new "final" payload(s) and before (re)applying
507
+ // optimistic changes. Each subscription's `snapshot` represents what was *last
508
+ // published to the subscriber*, which notably may include previous optimistic
509
+ // updates. Therefore a subscription can be in any of the following states:
510
+ // - stale=true: This subscription was restored to a different value than
511
+ // `snapshot`. That means this subscription has changes relative to its base,
512
+ // but its base has changed (we just applied a final payload): recompute
513
+ // a backup so that we can later restore to the state the subscription
514
+ // should be in.
515
+ // - stale=false: This subscription was restored to the same value than
516
+ // `snapshot`. That means this subscription does *not* have changes relative
517
+ // to its base, so the current `snapshot` is valid to use as a backup.
518
+ if (!subscription.stale) {
519
+ subscription.backup = subscription.snapshot;
520
+ return;
521
+ }
522
+ const snapshot = subscription.snapshot;
523
+ const backup = RelayReader.read(this.getSource(), snapshot.selector);
524
+ const nextData = recycleNodesInto(snapshot.data, backup.data);
525
+ (backup: $FlowFixMe).data = nextData; // backup owns the snapshot and can safely mutate
526
+ subscription.backup = backup;
527
+ });
528
+ this._optimisticSource = RelayOptimisticRecordSource.create(
529
+ this.getSource(),
530
+ );
531
+ }
532
+
533
+ restore(): void {
534
+ invariant(
535
+ this._optimisticSource != null,
536
+ 'RelayModernStore: Unexpected call to restore(), expected a snapshot ' +
537
+ 'to exist (make sure to call snapshot()).',
538
+ );
539
+ this._optimisticSource = null;
540
+ this._subscriptions.forEach(subscription => {
541
+ const backup = subscription.backup;
542
+ subscription.backup = null;
543
+ if (backup) {
544
+ if (backup.data !== subscription.snapshot.data) {
545
+ subscription.stale = true;
546
+ }
547
+ subscription.snapshot = {
548
+ data: subscription.snapshot.data,
549
+ isMissingData: backup.isMissingData,
550
+ seenRecords: backup.seenRecords,
551
+ selector: backup.selector,
552
+ };
553
+ } else {
554
+ subscription.stale = true;
555
+ }
556
+ });
557
+ }
558
+
559
+ _scheduleGC() {
560
+ if (this._gcHoldCounter > 0) {
561
+ this._shouldScheduleGC = true;
562
+ return;
563
+ }
564
+ if (this._hasScheduledGC) {
565
+ return;
566
+ }
567
+ this._hasScheduledGC = true;
568
+ this._gcScheduler(() => {
569
+ this.__gc();
570
+ this._hasScheduledGC = false;
571
+ });
572
+ }
573
+
574
+ __gc(): void {
575
+ // Don't run GC while there are optimistic updates applied
576
+ if (this._optimisticSource != null) {
577
+ return;
578
+ }
579
+ const references = new Set();
580
+ // Mark all records that are traversable from a root
581
+ this._roots.forEach(({operation}) => {
582
+ const selector = operation.root;
583
+ RelayReferenceMarker.mark(
584
+ this._recordSource,
585
+ selector,
586
+ references,
587
+ this._operationLoader,
588
+ );
589
+ });
590
+ if (references.size === 0) {
591
+ // Short-circuit if *nothing* is referenced
592
+ this._recordSource.clear();
593
+ } else {
594
+ // Evict any unreferenced nodes
595
+ const storeIDs = this._recordSource.getRecordIDs();
596
+ for (let ii = 0; ii < storeIDs.length; ii++) {
597
+ const dataID = storeIDs[ii];
598
+ if (!references.has(dataID)) {
599
+ this._recordSource.remove(dataID);
600
+ }
601
+ }
602
+ }
603
+ }
604
+ }
605
+
606
+ function initializeRecordSource(target: MutableRecordSource) {
607
+ if (!target.has(ROOT_ID)) {
608
+ const rootRecord = RelayModernRecord.create(ROOT_ID, ROOT_TYPE);
609
+ target.set(ROOT_ID, rootRecord);
610
+ }
611
+ }
612
+
613
+ /**
614
+ * Updates the target with information from source, also updating a mapping of
615
+ * which records in the target were changed as a result.
616
+ * Additionally, will marc records as invalidated at the current write epoch
617
+ * given the set of record ids marked as stale in this update.
618
+ */
619
+ function updateTargetFromSource(
620
+ target: MutableRecordSource,
621
+ source: RecordSource,
622
+ currentWriteEpoch: number,
623
+ idsMarkedForInvalidation: ?Set<DataID>,
624
+ updatedRecordIDs: UpdatedRecords,
625
+ invalidatedRecordIDs: Set<DataID>,
626
+ ): void {
627
+ // First, update any records that were marked for invalidation.
628
+ // For each provided dataID that was invalidated, we write the
629
+ // INVALIDATED_AT_KEY on the record, indicating
630
+ // the epoch at which the record was invalidated.
631
+ if (idsMarkedForInvalidation) {
632
+ idsMarkedForInvalidation.forEach(dataID => {
633
+ const targetRecord = target.get(dataID);
634
+ const sourceRecord = source.get(dataID);
635
+
636
+ // If record was deleted during the update (and also invalidated),
637
+ // we don't need to count it as an invalidated id
638
+ if (sourceRecord === null) {
639
+ return;
640
+ }
641
+
642
+ let nextRecord;
643
+ if (targetRecord != null) {
644
+ // If the target record exists, use it to set the epoch
645
+ // at which it was invalidated. This record will be updated with
646
+ // any changes from source in the section below
647
+ // where we update the target records based on the source.
648
+ nextRecord = RelayModernRecord.clone(targetRecord);
649
+ } else {
650
+ // If the target record doesn't exist, it means that a new record
651
+ // in the source was created (and also invalidated), so we use that
652
+ // record to set the epoch at which it was invalidated. This record
653
+ // will be updated with any changes from source in the section below
654
+ // where we update the target records based on the source.
655
+ nextRecord =
656
+ sourceRecord != null ? RelayModernRecord.clone(sourceRecord) : null;
657
+ }
658
+ if (!nextRecord) {
659
+ return;
660
+ }
661
+ RelayModernRecord.setValue(
662
+ nextRecord,
663
+ RelayStoreUtils.INVALIDATED_AT_KEY,
664
+ currentWriteEpoch,
665
+ );
666
+ invalidatedRecordIDs.add(dataID);
667
+ target.set(dataID, nextRecord);
668
+ });
669
+ }
670
+
671
+ // Update the target based on the changes present in source
672
+ const dataIDs = source.getRecordIDs();
673
+ for (let ii = 0; ii < dataIDs.length; ii++) {
674
+ const dataID = dataIDs[ii];
675
+ const sourceRecord = source.get(dataID);
676
+ const targetRecord = target.get(dataID);
677
+
678
+ // Prevent mutation of a record from outside the store.
679
+ if (__DEV__) {
680
+ if (sourceRecord) {
681
+ RelayModernRecord.freeze(sourceRecord);
682
+ }
683
+ }
684
+ if (sourceRecord && targetRecord) {
685
+ const nextRecord = RelayModernRecord.update(targetRecord, sourceRecord);
686
+ if (nextRecord !== targetRecord) {
687
+ // Prevent mutation of a record from outside the store.
688
+ if (__DEV__) {
689
+ RelayModernRecord.freeze(nextRecord);
690
+ }
691
+ updatedRecordIDs[dataID] = true;
692
+ target.set(dataID, nextRecord);
693
+ }
694
+ } else if (sourceRecord === null) {
695
+ target.delete(dataID);
696
+ if (targetRecord !== null) {
697
+ updatedRecordIDs[dataID] = true;
698
+ }
699
+ } else if (sourceRecord) {
700
+ target.set(dataID, sourceRecord);
701
+ updatedRecordIDs[dataID] = true;
702
+ } // don't add explicit undefined
703
+ }
704
+ }
705
+
706
+ /**
707
+ * Returns an OperationAvailability given the Availability returned
708
+ * by checking an operation, and when that operation was last written to the store.
709
+ * Specifically, the provided Availability of an operation will contain the
710
+ * value of when a record referenced by the operation was most recently
711
+ * invalidated; given that value, and given when this operation was last
712
+ * written to the store, this function will return the overall
713
+ * OperationAvailability for the operation.
714
+ */
715
+ function getAvailabilityStatus(
716
+ operationAvailability: Availability,
717
+ operationLastWrittenAt: ?number,
718
+ operationFetchTime: ?number,
719
+ queryCacheExpirationTime: ?number,
720
+ ): OperationAvailability {
721
+ const {mostRecentlyInvalidatedAt, status} = operationAvailability;
722
+ if (typeof mostRecentlyInvalidatedAt === 'number') {
723
+ // If some record referenced by this operation is stale, then the operation itself is stale
724
+ // if either the operation itself was never written *or* the operation was last written
725
+ // before the most recent invalidation of its reachable records.
726
+ if (
727
+ operationLastWrittenAt == null ||
728
+ mostRecentlyInvalidatedAt > operationLastWrittenAt
729
+ ) {
730
+ return {status: 'stale'};
731
+ }
732
+ }
733
+
734
+ if (status === 'missing') {
735
+ return {status: 'missing'};
736
+ }
737
+
738
+ if (operationFetchTime != null && queryCacheExpirationTime != null) {
739
+ const isStale = operationFetchTime <= Date.now() - queryCacheExpirationTime;
740
+ if (isStale) {
741
+ return {status: 'stale'};
742
+ }
743
+ }
744
+
745
+ // There were no invalidations of any reachable records *or* the operation is known to have
746
+ // been fetched after the most recent record invalidation.
747
+ return {status: 'available', fetchTime: operationFetchTime ?? null};
748
+ }
749
+
750
+ RelayProfiler.instrumentMethods(RelayModernStore.prototype, {
751
+ lookup: 'RelayModernStore.prototype.lookup',
752
+ notify: 'RelayModernStore.prototype.notify',
753
+ publish: 'RelayModernStore.prototype.publish',
754
+ __gc: 'RelayModernStore.prototype.__gc',
755
+ });
756
+
757
+ module.exports = RelayModernStore;