relay-runtime 0.0.0-main-ca31ec10 → 0.0.0-main-83136765

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,409 @@
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 {ReaderRelayResolver} from '../../util/ReaderNode';
16
+ import type {DataID, Variables} from '../../util/RelayRuntimeTypes';
17
+ import type {
18
+ MissingRequiredFields,
19
+ MutableRecordSource,
20
+ Record,
21
+ RelayResolverErrors,
22
+ SingularReaderSelector,
23
+ } from '../RelayStoreTypes';
24
+ import type {ResolverCache} from '../ResolverCache';
25
+ import type {ExternalState} from './ExternalStateResolverStore';
26
+
27
+ const recycleNodesInto = require('../../util/recycleNodesInto');
28
+ const {generateClientID} = require('../ClientID');
29
+ const RelayModernRecord = require('../RelayModernRecord');
30
+ const RelayRecordSource = require('../RelayRecordSource');
31
+ const {
32
+ RELAY_RESOLVER_ERROR_KEY,
33
+ RELAY_RESOLVER_INPUTS_KEY,
34
+ RELAY_RESOLVER_INVALIDATION_KEY,
35
+ RELAY_RESOLVER_MISSING_REQUIRED_FIELDS_KEY,
36
+ RELAY_RESOLVER_READER_SELECTOR_KEY,
37
+ RELAY_RESOLVER_VALUE_KEY,
38
+ getStorageKey,
39
+ } = require('../RelayStoreUtils');
40
+ const ExternalStateResolverStore = require('./ExternalStateResolverStore');
41
+ const warning = require('warning');
42
+
43
+ // When this experiment gets promoted to stable, these keys will move into
44
+ // `RelayStoreUtils`.
45
+ const RELAY_RESOLVER_EXTERNAL_STATE_SUBSCRIPTION_KEY =
46
+ '__resolverExternalStateSubscription';
47
+ const RELAY_EXTERNAL_STATE_VALUE = '__resolverExternalStateValue';
48
+ const RELAY_EXTERNAL_STATE_DIRTY = '__resolverExternalStateDirty';
49
+
50
+ /**
51
+ * An experimental fork of store/ResolverCache.js intended to let us experiment
52
+ * with External State Resolvers.
53
+ */
54
+
55
+ type ResolverID = string;
56
+
57
+ type EvaluationResult<T> = {|
58
+ resolverResult: T,
59
+ fragmentValue: {...},
60
+ resolverID: ResolverID,
61
+ seenRecordIDs: Set<DataID>,
62
+ readerSelector: SingularReaderSelector,
63
+ errors: RelayResolverErrors,
64
+ missingRequiredFields: ?MissingRequiredFields,
65
+ |};
66
+
67
+ // $FlowFixMe[unclear-type] - will always be empty
68
+ const emptySet: $ReadOnlySet<any> = new Set();
69
+
70
+ function addDependencyEdge(
71
+ edges: Map<ResolverID, Set<DataID>> | Map<DataID, Set<ResolverID>>,
72
+ from: ResolverID | DataID,
73
+ to: ResolverID | DataID,
74
+ ): void {
75
+ let set = edges.get(from);
76
+ if (!set) {
77
+ set = new Set();
78
+ edges.set(from, set);
79
+ }
80
+ set.add(to);
81
+ }
82
+
83
+ class ExternalStateResolverCache implements ResolverCache {
84
+ _resolverIDToRecordIDs: Map<ResolverID, Set<DataID>>;
85
+ _recordIDToResolverIDs: Map<DataID, Set<ResolverID>>;
86
+
87
+ _getRecordSource: () => MutableRecordSource;
88
+ _store: ExternalStateResolverStore;
89
+
90
+ constructor(
91
+ getRecordSource: () => MutableRecordSource,
92
+ store: ExternalStateResolverStore,
93
+ ) {
94
+ this._resolverIDToRecordIDs = new Map();
95
+ this._recordIDToResolverIDs = new Map();
96
+ this._getRecordSource = getRecordSource;
97
+ this._store = store;
98
+ }
99
+
100
+ readFromCacheOrEvaluate<T>(
101
+ record: Record,
102
+ field: ReaderRelayResolver,
103
+ variables: Variables,
104
+ evaluate: () => EvaluationResult<T>,
105
+ getDataForResolverFragment: SingularReaderSelector => mixed,
106
+ ): [
107
+ T /* Answer */,
108
+ ?DataID /* Seen record */,
109
+ RelayResolverErrors,
110
+ ?MissingRequiredFields,
111
+ ] {
112
+ const recordSource = this._getRecordSource();
113
+ const recordID = RelayModernRecord.getDataID(record);
114
+
115
+ const storageKey = getStorageKey(field, variables);
116
+ let linkedID = RelayModernRecord.getLinkedRecordID(record, storageKey);
117
+ let linkedRecord = linkedID == null ? null : recordSource.get(linkedID);
118
+
119
+ if (
120
+ linkedRecord == null ||
121
+ this._isInvalid(linkedRecord, getDataForResolverFragment)
122
+ ) {
123
+ // Cache miss; evaluate the selector and store the result in a new record:
124
+ linkedID = linkedID ?? generateClientID(recordID, storageKey);
125
+ linkedRecord = RelayModernRecord.create(linkedID, '__RELAY_RESOLVER__');
126
+
127
+ const evaluationResult = evaluate();
128
+
129
+ // In the future we we know from the Reader AST node if we are trying to
130
+ // read a Relay Resolver field or not. For the purpose of this hack, we
131
+ // will just check if it quacks like a duck.
132
+ const externalState = isExternalStateValue(
133
+ evaluationResult.resolverResult,
134
+ );
135
+
136
+ if (externalState != null) {
137
+ this._setExternalStateValue(linkedRecord, linkedID, externalState);
138
+ } else {
139
+ RelayModernRecord.setValue(
140
+ linkedRecord,
141
+ RELAY_RESOLVER_VALUE_KEY,
142
+ evaluationResult.resolverResult,
143
+ );
144
+ }
145
+ RelayModernRecord.setValue(
146
+ linkedRecord,
147
+ RELAY_RESOLVER_INPUTS_KEY,
148
+ evaluationResult.fragmentValue,
149
+ );
150
+ RelayModernRecord.setValue(
151
+ linkedRecord,
152
+ RELAY_RESOLVER_READER_SELECTOR_KEY,
153
+ evaluationResult.readerSelector,
154
+ );
155
+ RelayModernRecord.setValue(
156
+ linkedRecord,
157
+ RELAY_RESOLVER_MISSING_REQUIRED_FIELDS_KEY,
158
+ evaluationResult.missingRequiredFields,
159
+ );
160
+ RelayModernRecord.setValue(
161
+ linkedRecord,
162
+ RELAY_RESOLVER_ERROR_KEY,
163
+ evaluationResult.errors,
164
+ );
165
+ recordSource.set(linkedID, linkedRecord);
166
+
167
+ // Link the resolver value record to the resolver field of the record being read:
168
+ const nextRecord = RelayModernRecord.clone(record);
169
+ RelayModernRecord.setLinkedRecordID(nextRecord, storageKey, linkedID);
170
+ recordSource.set(RelayModernRecord.getDataID(nextRecord), nextRecord);
171
+
172
+ // Put records observed by the resolver into the dependency graph:
173
+ const resolverID = evaluationResult.resolverID;
174
+ addDependencyEdge(this._resolverIDToRecordIDs, resolverID, linkedID);
175
+ addDependencyEdge(this._recordIDToResolverIDs, recordID, resolverID);
176
+ for (const seenRecordID of evaluationResult.seenRecordIDs) {
177
+ addDependencyEdge(
178
+ this._recordIDToResolverIDs,
179
+ seenRecordID,
180
+ resolverID,
181
+ );
182
+ }
183
+ } else {
184
+ // If this is an External State Resolver, we might have a cache hit (the
185
+ // fragment data hasn't changed since we last evaluated the resolver),
186
+ // but it might still be "dirty" (the external state changed and we need
187
+ // to call `.read()` again).
188
+ //
189
+ // This is currently a bit implicit for now since we rely on the fact that
190
+ // only External State Resolvers can have `RELAY_EXTERNAL_STATE_DIRTY`
191
+ // set. However, in the future, we will have a distinct Reader AST node
192
+ // for External State Resolvers, so we won't have to be so implicit.
193
+ if (
194
+ RelayModernRecord.getValue(linkedRecord, RELAY_EXTERNAL_STATE_DIRTY)
195
+ ) {
196
+ linkedID = linkedID ?? generateClientID(recordID, storageKey);
197
+ linkedRecord = RelayModernRecord.clone(linkedRecord);
198
+ // $FlowFixMe[incompatible-type] - casting mixed
199
+ const externalState: ExternalState<mixed> = RelayModernRecord.getValue(
200
+ linkedRecord,
201
+ RELAY_EXTERNAL_STATE_VALUE,
202
+ );
203
+ // Set the new value for this and future reads.
204
+ RelayModernRecord.setValue(
205
+ linkedRecord,
206
+ RELAY_RESOLVER_VALUE_KEY,
207
+ externalState.read(),
208
+ );
209
+ // Mark the resolver as clean again.
210
+ RelayModernRecord.setValue(
211
+ linkedRecord,
212
+ RELAY_EXTERNAL_STATE_DIRTY,
213
+ false,
214
+ );
215
+ recordSource.set(linkedID, linkedRecord);
216
+ }
217
+ }
218
+
219
+ // $FlowFixMe[incompatible-type] - will always be empty
220
+ const answer: T = linkedRecord[RELAY_RESOLVER_VALUE_KEY];
221
+
222
+ const missingRequiredFields: ?MissingRequiredFields =
223
+ // $FlowFixMe[incompatible-type] - casting mixed
224
+ linkedRecord[RELAY_RESOLVER_MISSING_REQUIRED_FIELDS_KEY];
225
+
226
+ // $FlowFixMe[incompatible-type] - casting mixed
227
+ const errors: RelayResolverErrors = linkedRecord[RELAY_RESOLVER_ERROR_KEY];
228
+ return [answer, linkedID, errors, missingRequiredFields];
229
+ }
230
+
231
+ // Register a new External State object in the store, subscribing to future
232
+ // updates.
233
+ _setExternalStateValue(
234
+ linkedRecord: Record,
235
+ linkedID: DataID,
236
+ externalState: ExternalState<mixed>,
237
+ ) {
238
+ // If there's an existing subscription, unsubscribe.
239
+ // $FlowFixMe[incompatible-type] - casting mixed
240
+ const previousUnsubscribe: () => void = RelayModernRecord.getValue(
241
+ linkedRecord,
242
+ RELAY_RESOLVER_EXTERNAL_STATE_SUBSCRIPTION_KEY,
243
+ );
244
+
245
+ if (previousUnsubscribe != null) {
246
+ previousUnsubscribe();
247
+ }
248
+
249
+ // Subscribe to future values
250
+ const handler = this._makeExternalStateHandler(linkedID, externalState);
251
+ const unsubscribe = externalState.subscribe(handler);
252
+
253
+ // Store the external state value for future re-reads.
254
+ RelayModernRecord.setValue(
255
+ linkedRecord,
256
+ RELAY_EXTERNAL_STATE_VALUE,
257
+ externalState,
258
+ );
259
+
260
+ // Store the current value, for this read, and future cached reads.
261
+ RelayModernRecord.setValue(
262
+ linkedRecord,
263
+ RELAY_RESOLVER_VALUE_KEY,
264
+ externalState.read(),
265
+ );
266
+
267
+ // Mark the field as clean.
268
+ RelayModernRecord.setValue(linkedRecord, RELAY_EXTERNAL_STATE_DIRTY, false);
269
+
270
+ // Store our our unsubscribe function for future cleanup.
271
+ RelayModernRecord.setValue(
272
+ linkedRecord,
273
+ RELAY_RESOLVER_EXTERNAL_STATE_SUBSCRIPTION_KEY,
274
+ unsubscribe,
275
+ );
276
+ }
277
+
278
+ // Create a callback to handle notifications from the external source that the
279
+ // value may have changed.
280
+ _makeExternalStateHandler(
281
+ linkedID: DataID,
282
+ externalState: ExternalState<mixed>,
283
+ ): () => void {
284
+ return () => {
285
+ const currentSource = this._getRecordSource();
286
+ const currentRecord = currentSource.get(linkedID);
287
+ if (!currentRecord) {
288
+ warning(
289
+ false,
290
+ 'Expected a resolver record with ID %s, but it was missing.',
291
+ linkedID,
292
+ );
293
+ return;
294
+ }
295
+
296
+ const nextSource = RelayRecordSource.create();
297
+ const nextRecord = RelayModernRecord.clone(currentRecord);
298
+
299
+ // Mark the field as dirty. The next time it's read, we will call
300
+ // `ExternalState.read()`.
301
+ RelayModernRecord.setValue(nextRecord, RELAY_EXTERNAL_STATE_DIRTY, true);
302
+
303
+ nextSource.set(linkedID, nextRecord);
304
+ this._store.publish(nextSource);
305
+
306
+ // In the future, this notify might be defferred if we are within a
307
+ // transaction.
308
+ this._store.notify();
309
+ };
310
+ }
311
+
312
+ invalidateDataIDs(
313
+ updatedDataIDs: Set<DataID>, // Mutated in place
314
+ ): void {
315
+ const recordSource = this._getRecordSource();
316
+ const visited: Set<string> = new Set();
317
+ const recordsToVisit = Array.from(updatedDataIDs);
318
+ while (recordsToVisit.length) {
319
+ const recordID = recordsToVisit.pop();
320
+ updatedDataIDs.add(recordID);
321
+ for (const fragment of this._recordIDToResolverIDs.get(recordID) ??
322
+ emptySet) {
323
+ if (!visited.has(fragment)) {
324
+ for (const anotherRecordID of this._resolverIDToRecordIDs.get(
325
+ fragment,
326
+ ) ?? emptySet) {
327
+ this._markInvalidatedResolverRecord(anotherRecordID, recordSource);
328
+ if (!visited.has(anotherRecordID)) {
329
+ recordsToVisit.push(anotherRecordID);
330
+ }
331
+ }
332
+ }
333
+ }
334
+ }
335
+ }
336
+
337
+ _markInvalidatedResolverRecord(
338
+ dataID: DataID,
339
+ recordSource: MutableRecordSource, // Written to
340
+ ) {
341
+ const record = recordSource.get(dataID);
342
+ if (!record) {
343
+ warning(
344
+ false,
345
+ 'Expected a resolver record with ID %s, but it was missing.',
346
+ dataID,
347
+ );
348
+ return;
349
+ }
350
+ const nextRecord = RelayModernRecord.clone(record);
351
+ RelayModernRecord.setValue(
352
+ nextRecord,
353
+ RELAY_RESOLVER_INVALIDATION_KEY,
354
+ true,
355
+ );
356
+ recordSource.set(dataID, nextRecord);
357
+ }
358
+
359
+ _isInvalid(
360
+ record: Record,
361
+ getDataForResolverFragment: SingularReaderSelector => mixed,
362
+ ): boolean {
363
+ if (!RelayModernRecord.getValue(record, RELAY_RESOLVER_INVALIDATION_KEY)) {
364
+ return false;
365
+ }
366
+ const originalInputs = RelayModernRecord.getValue(
367
+ record,
368
+ RELAY_RESOLVER_INPUTS_KEY,
369
+ );
370
+ // $FlowFixMe[incompatible-type] - storing values in records is not typed
371
+ const readerSelector: ?SingularReaderSelector = RelayModernRecord.getValue(
372
+ record,
373
+ RELAY_RESOLVER_READER_SELECTOR_KEY,
374
+ );
375
+ if (originalInputs == null || readerSelector == null) {
376
+ warning(
377
+ false,
378
+ 'Expected previous inputs and reader selector on resolver record with ID %s, but they were missing.',
379
+ RelayModernRecord.getDataID(record),
380
+ );
381
+ return true;
382
+ }
383
+ const latestValues = getDataForResolverFragment(readerSelector);
384
+ const recycled = recycleNodesInto(originalInputs, latestValues);
385
+ if (recycled !== originalInputs) {
386
+ return true;
387
+ }
388
+ return false;
389
+ }
390
+ }
391
+
392
+ // In the real implementaiton, we will probably have a special Reader AST node to tell us when
393
+ // a value is external state
394
+ // $FlowFixMe
395
+ function isExternalStateValue(v: Object): ?ExternalState {
396
+ if (
397
+ v != null &&
398
+ typeof v.read === 'function' &&
399
+ typeof v.subscribe === 'function'
400
+ ) {
401
+ return v;
402
+ } else {
403
+ return null;
404
+ }
405
+ }
406
+
407
+ module.exports = {
408
+ ExternalStateResolverCache,
409
+ };