-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathmemory-source.ts
More file actions
559 lines (486 loc) · 16.9 KB
/
memory-source.ts
File metadata and controls
559 lines (486 loc) · 16.9 KB
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import { Assertion, Orbit } from '@orbit/core';
import {
DefaultRequestOptions,
FullRequestOptions,
FullResponse,
queryable,
RequestOptions,
Resettable,
ResponseHints,
syncable,
updatable
} from '@orbit/data';
import { RecordCacheUpdateDetails } from '@orbit/record-cache';
import {
coalesceRecordOperations,
RecordOperation,
RecordOperationResult,
RecordQuery,
RecordQueryable,
RecordQueryBuilder,
RecordQueryExpressionResult,
RecordQueryResult,
RecordSource,
RecordSourceQueryOptions,
RecordSourceSettings,
RecordSyncable,
RecordTransform,
RecordTransformBuilder,
RecordTransformResult,
RecordUpdatable
} from '@orbit/records';
import { Dict, toArray } from '@orbit/utils';
import {
MemoryCache,
MemoryCacheClass,
MemoryCacheSettings
} from './memory-cache';
const { assert, deprecate } = Orbit;
export interface MemorySourceSettings<
QO extends RequestOptions = RecordSourceQueryOptions,
TO extends RequestOptions = RequestOptions,
QB = RecordQueryBuilder,
TB = RecordTransformBuilder,
QRD = unknown,
TRD extends RecordCacheUpdateDetails = RecordCacheUpdateDetails
> extends RecordSourceSettings<QO, TO, QB, TB> {
base?: MemorySource<QO, TO, QB, TB, QRD, TRD>;
cacheClass?: MemoryCacheClass<QO, TO, QB, TB, QRD, TRD>;
cacheSettings?: Partial<MemoryCacheSettings<QO, TO, QB, TB, QRD, TRD>>;
}
export interface MemorySourceMergeOptions {
coalesce?: boolean;
/**
* @deprecated since v0.17
*/
sinceTransformId?: string;
/**
* @deprecated since v0.17, include transform options alongside merge options instead
*/
transformOptions?: RequestOptions;
}
export interface MemorySource<
QO extends RequestOptions = RecordSourceQueryOptions,
TO extends RequestOptions = RequestOptions,
QB = RecordQueryBuilder,
TB = RecordTransformBuilder,
QRD = unknown,
TRD extends RecordCacheUpdateDetails = RecordCacheUpdateDetails
> extends RecordSource<QO, TO, QB, TB>,
RecordSyncable,
RecordQueryable<QRD, QB, QO>,
RecordUpdatable<TRD, TB, TO> {}
@syncable
@queryable
@updatable
export class MemorySource<
QO extends RequestOptions = RecordSourceQueryOptions,
TO extends RequestOptions = RequestOptions,
QB = RecordQueryBuilder,
TB = RecordTransformBuilder,
QRD = unknown,
TRD extends RecordCacheUpdateDetails = RecordCacheUpdateDetails
>
extends RecordSource<QO, TO, QB, TB>
implements
RecordSyncable,
RecordQueryable<QRD, QB, QO>,
RecordUpdatable<TRD, TB, TO>,
Resettable {
protected _cache: MemoryCache<QO, TO, QB, TB, QRD, TRD>;
protected _base?: MemorySource<QO, TO, QB, TB, QRD, TRD>;
protected _forkPoint?: string;
protected _transforms: Dict<RecordTransform>;
protected _transformInverses: Dict<RecordOperation[]>;
constructor(settings: MemorySourceSettings<QO, TO, QB, TB, QRD, TRD>) {
const { keyMap, schema, base } = settings;
settings.name = settings.name ?? 'memory';
super(settings);
this._transforms = {};
this._transformInverses = {};
this.transformLog.on('clear', this._logCleared.bind(this));
this.transformLog.on('truncate', this._logTruncated.bind(this));
this.transformLog.on('rollback', this._logRolledback.bind(this));
let cacheSettings: Partial<MemoryCacheSettings<QO, TO, QB, TB, QRD, TRD>> =
settings.cacheSettings ?? {};
cacheSettings.schema = schema;
cacheSettings.keyMap = keyMap;
cacheSettings.queryBuilder ??= this.queryBuilder;
cacheSettings.transformBuilder ??= this.transformBuilder;
cacheSettings.defaultQueryOptions ??= this.defaultQueryOptions;
cacheSettings.defaultTransformOptions ??= this.defaultTransformOptions;
cacheSettings.autoValidate ??= settings.autoValidate;
if (
cacheSettings.autoValidate !== false &&
cacheSettings.validatorFor === undefined &&
cacheSettings.validators === undefined
) {
cacheSettings.validatorFor = this._validatorFor;
}
if (base) {
this._base = base;
this._forkPoint = base.transformLog.head;
cacheSettings.base = base.cache;
}
const cacheClass = settings.cacheClass ?? MemoryCache;
this._cache = new cacheClass(
cacheSettings as MemoryCacheSettings<QO, TO, QB, TB, QRD, TRD>
);
}
get cache(): MemoryCache<QO, TO, QB, TB, QRD, TRD> {
return this._cache;
}
get base(): MemorySource<QO, TO, QB, TB, QRD, TRD> | undefined {
return this._base;
}
get forkPoint(): string | undefined {
return this._forkPoint;
}
async upgrade(): Promise<void> {
this._cache.upgrade();
}
/////////////////////////////////////////////////////////////////////////////
// Syncable interface implementation
/////////////////////////////////////////////////////////////////////////////
async _sync(transform: RecordTransform): Promise<void> {
if (!this.transformLog.contains(transform.id)) {
this._applyTransform(transform);
await this.transformed([transform]);
}
}
/////////////////////////////////////////////////////////////////////////////
// Updatable interface implementation
/////////////////////////////////////////////////////////////////////////////
async _update(
transform: RecordTransform,
hints?: ResponseHints<RecordTransformResult, TRD>
): Promise<FullResponse<RecordTransformResult, TRD, RecordOperation>> {
let results: RecordTransformResult;
const response: FullResponse<
RecordTransformResult,
TRD,
RecordOperation
> = {};
if (!this.transformLog.contains(transform.id)) {
results = this._applyTransform(transform);
response.transforms = [transform];
}
if (hints?.data) {
if (Array.isArray(transform.operations)) {
assert(
'MemorySource#update: `hints.data` must be an array if `transform.operations` is an array',
Array.isArray(hints.data)
);
response.data = (hints.data as RecordOperationResult[]).map((h) =>
this._retrieveOperationResult(h)
);
} else {
response.data = this._retrieveOperationResult(
hints.data as RecordOperationResult
);
}
} else if (results) {
response.data = results;
}
if (hints?.details) {
response.details = hints.details;
}
return response;
}
/////////////////////////////////////////////////////////////////////////////
// Queryable interface implementation
/////////////////////////////////////////////////////////////////////////////
async _query(
query: RecordQuery,
hints?: ResponseHints<RecordQueryResult, QRD>
): Promise<FullResponse<RecordQueryResult, QRD, RecordOperation>> {
let response: FullResponse<RecordQueryResult, QRD, RecordOperation>;
if (hints?.data) {
response = {};
if (Array.isArray(query.expressions)) {
assert(
'MemorySource#query: `hints.data` must be an array if `query.expressions` is an array',
Array.isArray(hints.data)
);
response.data = (hints.data as RecordQueryExpressionResult[]).map((h) =>
this._retrieveQueryExpressionResult(h)
);
} else {
response.data = this._retrieveQueryExpressionResult(
hints.data as RecordQueryExpressionResult
);
}
} else {
response = this._cache.query(query, {
fullResponse: true
} as FullRequestOptions<QO>);
}
if (hints?.details) {
response.details = hints.details;
}
return response;
}
/////////////////////////////////////////////////////////////////////////////
// Public methods
/////////////////////////////////////////////////////////////////////////////
/**
* Create a clone, or "fork", from a "base" source.
*
* The forked source will have the same `schema` and `keyMap` as its base source.
* The forked source's cache will start with the same immutable document as
* the base source. Its contents and log will evolve independently.
*
* @returns The forked source.
*/
fork(
settings: Partial<MemorySourceSettings<QO, TO, QB, TB, QRD, TRD>> = {}
): MemorySource<QO, TO, QB, TB, QRD, TRD> {
// required settings
settings.base = this;
settings.schema = this.schema;
settings.keyMap = this.keyMap;
// customizable settings
settings.queryBuilder ??= this._queryBuilder;
settings.transformBuilder ??= this._transformBuilder;
settings.defaultQueryOptions ??= this._defaultQueryOptions;
settings.defaultTransformOptions ??= this._defaultTransformOptions;
if (settings.autoValidate !== false) {
settings.validatorFor ??= this._validatorFor;
if (
settings.autoValidate === undefined &&
settings.validatorFor === undefined
) {
settings.autoValidate = false;
}
}
return new MemorySource<QO, TO, QB, TB, QRD, TRD>(
settings as MemorySourceSettings<QO, TO, QB, TB, QRD, TRD>
);
}
/**
* Merge transforms from a forked source back into a base source.
*
* By default, all of the operations from all of the transforms in the forked
* source's history will be reduced into a single transform. A subset of
* operations can be selected by specifying the `sinceTransformId` option.
*
* The `coalesce` option controls whether operations are coalesced into a
* minimal equivalent set before being reduced into a transform.
*
* @param forkedSource - The source to merge.
* @param options - Merge options
* @returns The result of calling `update()` with the forked transforms.
*/
merge<RequestData extends RecordTransformResult = RecordTransformResult>(
forkedSource: MemorySource<QO, TO, QB, TB, QRD, TRD>,
options?: DefaultRequestOptions<TO> & MemorySourceMergeOptions
): Promise<RequestData>;
merge<RequestData extends RecordTransformResult = RecordTransformResult>(
forkedSource: MemorySource<QO, TO, QB, TB, QRD, TRD>,
options: FullRequestOptions<TO> & MemorySourceMergeOptions
): Promise<FullResponse<RequestData, TRD, RecordOperation>>;
async merge<
RequestData extends RecordTransformResult = RecordTransformResult
>(
forkedSource: MemorySource<QO, TO, QB, TB, QRD, TRD>,
options?: TO & MemorySourceMergeOptions
): Promise<
RecordTransformResult | FullResponse<RequestData, TRD, RecordOperation>
> {
let { coalesce, sinceTransformId, transformOptions, ...remainingOptions } =
options ?? {};
let requestOptions: TO;
if (transformOptions) {
deprecate(
'In MemorySource#merge, passing `transformOptions` nested within `options` is deprecated. Instead, include them directly alongside other options.'
);
requestOptions = transformOptions as TO;
} else {
requestOptions = (remainingOptions ?? {}) as TO;
}
let ops: RecordOperation[] = [];
if (forkedSource.cache.isTrackingUpdateOperations) {
ops = forkedSource.cache.getAllUpdateOperations();
} else {
let transforms: RecordTransform[];
if (sinceTransformId) {
deprecate(
'In MemorySource#merge, passing `sinceTransformId` is deprecated. Instead, call `update` with a custom transform/operations.'
);
transforms = forkedSource.getTransformsSince(sinceTransformId);
} else {
transforms = forkedSource.getAllTransforms();
}
transforms.forEach((t) => {
Array.prototype.push.apply(ops, toArray(t.operations));
});
}
if (coalesce !== false) {
ops = coalesceRecordOperations(ops);
}
if (requestOptions.fullResponse) {
return this.update<RequestData>(
ops,
requestOptions as FullRequestOptions<TO>
);
} else {
return this.update<RequestData>(
ops,
requestOptions as DefaultRequestOptions<TO>
);
}
}
/**
* Rebase works similarly to a git rebase:
*
* After a source is forked, there is a parent- and a child-source. Both may
* be updated with transforms. When `childSource.rebase()` is called, the
* child source's state will be reset to match the current state of its
* parent, and then any locally made transforms will be replayed on the child
* source.
*/
rebase(): void {
const base = this._base;
if (!base) {
throw new Assertion(
'A `base` source must be defined for `rebase` to work'
);
}
// reset the state of the cache to match the base cache
this.cache.reset();
// replay all locally made transforms
this.getAllTransforms().forEach((t) => this._applyTransform(t));
// reset the fork point
this._forkPoint = base.transformLog.head;
}
/**
* Reset the source's cache and transform log to its initial state, which will
* be either empty or a matching its `base`, if it has one.
*/
async reset(): Promise<void> {
// reset the state of the cache (which will match a base cache, if present)
this.cache.reset();
// reset the fork point
this._forkPoint = this._base ? this._base.transformLog.head : undefined;
// clear the transform log, which in turn will clear any tracked transforms
await this.transformLog.clear();
}
/**
* Rolls back the source to a particular `transformId`.
*
* `relativePosition` can be a positive or negative integer used to specify a
* position relative to `transformId`.
*/
rollback(transformId: string, relativePosition = 0): Promise<void> {
return this.transformLog.rollback(transformId, relativePosition);
}
/**
* Returns all logged transforms since a particular `transformId`.
*/
getTransformsSince(transformId: string): RecordTransform[] {
return this.transformLog
.after(transformId)
.map((id) => this._transforms[id]);
}
/**
* @deprecated since v0.17, call `getTransformsSince` instead
*/
transformsSince(transformId: string): RecordTransform[] {
deprecate(
'MemorySource#transformsSince has been deprecated. Please call `source.getTransformsSince(tranformId)` instead.'
);
return this.getTransformsSince(transformId);
}
/**
* Returns all logged transforms.
*/
getAllTransforms(): RecordTransform[] {
return this.transformLog.entries.map((id) => this._transforms[id]);
}
/**
* @deprecated since v0.17, call `getAllTransforms` instead
*/
allTransforms(): RecordTransform[] {
deprecate(
'MemorySource#allTransforms has been deprecated. Please call `source.getAllTransforms()` instead.'
);
return this.getAllTransforms();
}
getTransform(transformId: string): RecordTransform {
return this._transforms[transformId];
}
getInverseOperations(transformId: string): RecordOperation[] {
return this._transformInverses[transformId];
}
get defaultQueryOptions(): DefaultRequestOptions<QO> | undefined {
return super.defaultQueryOptions;
}
set defaultQueryOptions(options: DefaultRequestOptions<QO> | undefined) {
super.defaultQueryOptions = this._cache.defaultQueryOptions = options;
}
get defaultTransformOptions(): DefaultRequestOptions<TO> | undefined {
return super.defaultTransformOptions;
}
set defaultTransformOptions(options: DefaultRequestOptions<TO> | undefined) {
this._defaultTransformOptions = this._cache.defaultTransformOptions = options;
}
/////////////////////////////////////////////////////////////////////////////
// Protected methods
/////////////////////////////////////////////////////////////////////////////
protected _retrieveQueryExpressionResult(
result: RecordQueryExpressionResult
): RecordQueryExpressionResult {
if (Array.isArray(result)) {
return this._cache.getRecordsSync(result);
} else if (result) {
return this._cache.getRecordSync(result);
} else {
return result;
}
}
protected _retrieveOperationResult(
result: RecordOperationResult
): RecordOperationResult {
if (result) {
return this._cache.getRecordSync(result);
} else {
return result;
}
}
protected _applyTransform(transform: RecordTransform): RecordTransformResult {
const { data, details } = this.cache.update(transform, {
fullResponse: true
} as FullRequestOptions<TO>);
this._transforms[transform.id] = transform;
this._transformInverses[transform.id] = details?.inverseOperations ?? [];
return data;
}
protected _clearTransformFromHistory(transformId: string): void {
delete this._transforms[transformId];
delete this._transformInverses[transformId];
}
protected _logCleared(): void {
this._transforms = {};
this._transformInverses = {};
}
protected _logTruncated(
transformId: string,
relativePosition: number,
removed: string[]
): void {
removed.forEach((id) => this._clearTransformFromHistory(id));
}
protected _logRolledback(
transformId: string,
relativePosition: number,
removed: string[]
): void {
removed.reverse().forEach((id) => {
const inverseOperations = this._transformInverses[id];
if (inverseOperations) {
this.cache.update(inverseOperations);
}
this._clearTransformFromHistory(id);
});
}
}