relay-runtime 0.0.0-main-32d17fa8 → 0.0.0-main-3070fa31

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