-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathreplace-related-records.ts
488 lines (431 loc) · 16.2 KB
/
replace-related-records.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import { deprecate } from '@ember/debug';
import { DEBUG_RELATIONSHIP_NOTIFICATIONS, LOG_METRIC_COUNTS } from '@warp-drive/build-config/debugging';
import { DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE } from '@warp-drive/build-config/deprecations';
import { DEBUG } from '@warp-drive/build-config/env';
import { assert } from '@warp-drive/build-config/macros';
import type { StableRecordIdentifier } from '@warp-drive/core-types';
import type { ReplaceRelatedRecordsOperation } from '@warp-drive/core-types/graph';
import { _addLocal, _removeLocal, _removeRemote, diffCollection } from '../-diff';
import { isBelongsTo, isHasMany, isNew, notifyChange } from '../-utils';
import { assertPolymorphicType } from '../debug/assert-polymorphic-type';
import type { CollectionEdge } from '../edges/collection';
import type { Graph } from '../graph';
function count(label: string) {
// @ts-expect-error
// eslint-disable-next-line
globalThis.__WarpDriveMetricCountData[label] = (globalThis.__WarpDriveMetricCountData[label] || 0) + 1;
}
/*
case many:1
========
In a bi-directional graph with Many:1 edges, adding a value
results in up-to 3 discrete value transitions, while removing
a value is only 2 transitions.
For adding C to A
If: A <<-> B, C <->> D is the initial state,
and: B <->> A <<-> C, D is the final state
then we would undergo the following transitions.
add C to A
remove C from D
add A to C
For removing B from A
If: A <<-> B, C <->> D is the initial state,
and: A, B, C <->> D is the final state
then we would undergo the following transitions.
remove B from A
remove A from B
case many:many
===========
In a bi-directional graph with Many:Many edges, adding or
removing a value requires only 2 value transitions.
For Adding
If: A<<->>B, C<<->>D is the initial state (double arrows representing the many side)
And: D<<->>C<<->>A<<->>B is the final state
Then we would undergo two transitions.
add C to A.
add A to C
For Removing
If: A<<->>B, C<<->>D is the initial state (double arrows representing the many side)
And: A, B, C<<->>D is the final state
Then we would undergo two transitions.
remove B from A
remove A from B
case many:?
========
In a uni-directional graph with Many:? edges (modeled in EmberData with `inverse:null`) with
artificial (implicit) inverses, replacing a value results in 2 discrete value transitions.
This is because a Many:? relationship is effectively Many:Many.
*/
export default function replaceRelatedRecords(graph: Graph, op: ReplaceRelatedRecordsOperation, isRemote: boolean) {
if (isRemote) {
replaceRelatedRecordsRemote(graph, op, isRemote);
} else {
replaceRelatedRecordsLocal(graph, op, isRemote);
}
}
function replaceRelatedRecordsLocal(graph: Graph, op: ReplaceRelatedRecordsOperation, isRemote: boolean) {
const identifiers = op.value;
const relationship = graph.get(op.record, op.field);
assert(`expected hasMany relationship`, isHasMany(relationship));
relationship.state.hasReceivedData = true;
const { additions, removals } = relationship;
const { inverseKey, type } = relationship.definition;
const { record } = op;
const wasDirty = relationship.isDirty;
let localBecameDirty = false;
if (LOG_METRIC_COUNTS) {
count(`replaceRelatedRecordsLocal ${'type' in record ? record.type : '<document>'} ${op.field}`);
}
const onAdd = (identifier: StableRecordIdentifier) => {
// Since we are diffing against the remote state, we check
// if our previous local state did not contain this identifier
const removalsHas = removals?.has(identifier);
if (removalsHas || !additions?.has(identifier)) {
if (type !== identifier.type) {
if (DEBUG) {
assertPolymorphicType(relationship.identifier, relationship.definition, identifier, graph.store);
}
graph.registerPolymorphicType(type, identifier.type);
}
// we've added a record locally that wasn't in the local state before
localBecameDirty = true;
addToInverse(graph, identifier, inverseKey, op.record, isRemote);
if (removalsHas) {
removals!.delete(identifier);
}
}
};
const onRemove = (identifier: StableRecordIdentifier) => {
// Since we are diffing against the remote state, we check
// if our previous local state had contained this identifier
const additionsHas = additions?.has(identifier);
if (additionsHas || !removals?.has(identifier)) {
// we've removed a record locally that was in the local state before
localBecameDirty = true;
removeFromInverse(graph, identifier, inverseKey, record, isRemote);
if (additionsHas) {
additions!.delete(identifier);
}
}
};
const diff = diffCollection(identifiers, relationship, onAdd, onRemove);
// any additions no longer in the local state
// also need to be removed from the inverse
if (additions && additions.size > 0) {
additions.forEach((identifier) => {
if (!diff.add.has(identifier)) {
localBecameDirty = true;
onRemove(identifier);
}
});
}
// any removals no longer in the local state
// also need to be added back to the inverse
if (removals && removals.size > 0) {
removals.forEach((identifier) => {
if (!diff.del.has(identifier)) {
localBecameDirty = true;
onAdd(identifier);
}
});
}
const becameDirty = diff.changed || localBecameDirty;
relationship.additions = diff.add;
relationship.removals = diff.del;
relationship.localState = diff.finalState;
// we only notify if the localState changed and were not already dirty before
// because if we were already dirty then we have already notified
if (becameDirty && !wasDirty) {
notifyChange(graph, relationship);
}
}
function replaceRelatedRecordsRemote(graph: Graph, op: ReplaceRelatedRecordsOperation, isRemote: boolean) {
const identifiers = op.value;
const relationship = graph.get(op.record, op.field);
if (LOG_METRIC_COUNTS) {
count(`replaceRelatedRecordsRemote ${'type' in op.record ? op.record.type : '<document>'} ${op.field}`);
}
assert(
`You can only '${op.op}' on a hasMany relationship. ${op.record.type}.${op.field} is a ${relationship.definition.kind}`,
isHasMany(relationship)
);
if (isRemote) {
graph._addToTransaction(relationship);
}
const wasDirty = relationship.isDirty;
// if this is our first time receiving data
// we need to mark the relationship as dirty
// so that non-materializing APIs like `hasManyReference.value()`
// will get notified and updated.
if (!relationship.state.hasReceivedData) {
relationship.isDirty = true;
}
relationship.state.hasReceivedData = true;
// cache existing state
const { definition } = relationship;
const { type } = relationship.definition;
const diff = diffCollection(
identifiers,
relationship,
(identifier) => {
if (type !== identifier.type) {
if (DEBUG) {
assertPolymorphicType(relationship.identifier, relationship.definition, identifier, graph.store);
}
graph.registerPolymorphicType(type, identifier.type);
}
// commit additions
// TODO build this into the diff?
// because we are not dirty if this was a committed local addition
if (relationship.additions?.has(identifier)) {
relationship.additions.delete(identifier);
} else {
if (DEBUG_RELATIONSHIP_NOTIFICATIONS) {
if (!relationship.isDirty) {
// eslint-disable-next-line no-console
console.log(
`setting relationship to dirty because the remote addition was not in our previous list of local additions`
);
}
}
}
addToInverse(graph, identifier, definition.inverseKey, op.record, isRemote);
},
(identifier) => {
// commit removals
// TODO build this into the diff?
// because we are not dirty if this was a committed local addition
if (relationship.removals?.has(identifier)) {
relationship.removals.delete(identifier);
} else {
if (DEBUG_RELATIONSHIP_NOTIFICATIONS) {
if (!relationship.isDirty) {
// eslint-disable-next-line no-console
console.log(
`setting relationship to dirty because the remote removal was not in our previous list of local removals`
);
}
}
}
removeFromInverse(graph, identifier, definition.inverseKey, op.record, isRemote);
}
);
// replace existing state
relationship.remoteMembers = diff.finalSet;
relationship.remoteState = diff.finalState;
// changed also indicates a change in order
if (diff.changed) {
relationship.isDirty = true;
}
// TODO unsure if we need this but it
// may allow us to more efficiently patch
// the associated ManyArray
relationship._diff = diff;
if (DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE) {
// only do this for legacy hasMany, not collection
// and provide a way to incrementally migrate
if (
// we do not guard by diff.changed here
// because we want to clear local changes even if
// no change has occurred to preserve the legacy behavior
relationship.definition.kind === 'hasMany' &&
relationship.definition.resetOnRemoteUpdate !== false &&
(diff.changed || wasDirty)
) {
const deprecationInfo: {
removals: StableRecordIdentifier[];
additions: StableRecordIdentifier[];
triggered: boolean;
} = {
removals: [],
additions: [],
triggered: false,
};
if (relationship.removals) {
relationship.isDirty = true;
relationship.removals.forEach((identifier) => {
deprecationInfo.triggered = true;
deprecationInfo.removals.push(identifier);
// reverse the removal
// if we are still in removals at this point then
// we were not "committed" which means we are present
// in the remoteMembers. So we "add back" on the inverse.
addToInverse(graph, identifier, definition.inverseKey, op.record, false);
});
relationship.removals = null;
}
if (relationship.additions) {
relationship.additions.forEach((identifier) => {
// reverse the addition
// if we are still in additions at this point then
// we were not "committed" which means we are not present
// in the remoteMembers. So we "remove" from the inverse.
// however we only do this if we are not a "new" record.
if (!isNew(identifier)) {
deprecationInfo.triggered = true;
deprecationInfo.additions.push(identifier);
relationship.isDirty = true;
relationship.additions!.delete(identifier);
removeFromInverse(graph, identifier, definition.inverseKey, op.record, false);
}
});
if (relationship.additions.size === 0) {
relationship.additions = null;
}
}
if (deprecationInfo.triggered) {
deprecate(
`EmberData is changing the default semantics of updates to the remote state of relationships.\n\nThe following local state was cleared from the <${
relationship.identifier.type
}>.${
relationship.definition.key
} hasMany relationship but will not be once this deprecation is resolved by opting into the new behavior:\n\n\tAdded: [${deprecationInfo.additions
.map((i) => i.lid)
.join(', ')}]\n\tRemoved: [${deprecationInfo.removals.map((i) => i.lid).join(', ')}]`,
false,
{
id: 'ember-data:deprecate-relationship-remote-update-clearing-local-state',
for: 'ember-data',
since: { enabled: '5.3', available: '4.13' },
until: '6.0',
url: 'https://deprecations.emberjs.com/v5.x#ember-data-deprecate-relationship-remote-update-clearing-local-state',
}
);
}
}
}
if (relationship.isDirty && !wasDirty) {
flushCanonical(graph, relationship);
}
}
export function addToInverse(
graph: Graph,
identifier: StableRecordIdentifier,
key: string,
value: StableRecordIdentifier,
isRemote: boolean
) {
const relationship = graph.get(identifier, key);
const { type } = relationship.definition;
if (type !== value.type) {
if (DEBUG) {
assertPolymorphicType(relationship.identifier, relationship.definition, value, graph.store);
}
graph.registerPolymorphicType(type, value.type);
}
if (isBelongsTo(relationship)) {
relationship.state.hasReceivedData = true;
relationship.state.isEmpty = false;
if (isRemote) {
graph._addToTransaction(relationship);
if (relationship.remoteState !== null) {
removeFromInverse(graph, relationship.remoteState, relationship.definition.inverseKey, identifier, isRemote);
}
relationship.remoteState = value;
}
if (relationship.localState !== value) {
if (!isRemote && relationship.localState) {
removeFromInverse(graph, relationship.localState, relationship.definition.inverseKey, identifier, isRemote);
}
relationship.localState = value;
notifyChange(graph, relationship);
}
} else if (isHasMany(relationship)) {
if (isRemote) {
// TODO this needs to alert stuffs
// And patch state better
// This is almost definitely wrong
// WARNING WARNING WARNING
if (!relationship.remoteMembers.has(value)) {
graph._addToTransaction(relationship);
relationship.remoteState.push(value);
relationship.remoteMembers.add(value);
if (relationship.additions?.has(value)) {
relationship.additions.delete(value);
} else {
relationship.isDirty = true;
relationship.state.hasReceivedData = true;
flushCanonical(graph, relationship);
}
}
} else {
// if we are not dirty but have a null localState then we
// are mutating a relationship that has never been fetched
// so we initialize localState to an empty array
if (!relationship.isDirty && !relationship.localState) {
relationship.localState = [];
}
if (_addLocal(graph, identifier, relationship, value, null)) {
notifyChange(graph, relationship);
}
}
} else {
if (isRemote) {
if (!relationship.remoteMembers.has(value)) {
relationship.remoteMembers.add(value);
relationship.localMembers.add(value);
}
} else {
if (!relationship.localMembers.has(value)) {
relationship.localMembers.add(value);
}
}
}
}
export function notifyInverseOfPotentialMaterialization(
graph: Graph,
identifier: StableRecordIdentifier,
key: string,
value: StableRecordIdentifier,
isRemote: boolean
) {
const relationship = graph.get(identifier, key);
if (isHasMany(relationship) && isRemote && relationship.remoteMembers.has(value)) {
notifyChange(graph, relationship);
}
}
export function removeFromInverse(
graph: Graph,
identifier: StableRecordIdentifier,
key: string,
value: StableRecordIdentifier,
isRemote: boolean
) {
const relationship = graph.get(identifier, key);
if (isBelongsTo(relationship)) {
relationship.state.isEmpty = true;
if (isRemote) {
graph._addToTransaction(relationship);
relationship.remoteState = null;
}
if (relationship.localState === value) {
relationship.localState = null;
notifyChange(graph, relationship);
}
} else if (isHasMany(relationship)) {
if (isRemote) {
graph._addToTransaction(relationship);
if (_removeRemote(relationship, value)) {
notifyChange(graph, relationship);
}
} else {
if (_removeLocal(relationship, value)) {
notifyChange(graph, relationship);
}
}
} else {
if (isRemote) {
relationship.remoteMembers.delete(value);
relationship.localMembers.delete(value);
} else {
if (value && relationship.localMembers.has(value)) {
relationship.localMembers.delete(value);
}
}
}
}
function flushCanonical(graph: Graph, rel: CollectionEdge) {
if (rel.accessed) {
graph._scheduleLocalSync(rel);
}
}