relay-runtime 8.0.0 → 10.0.1

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