-
Notifications
You must be signed in to change notification settings - Fork 134
/
memory-source.ts
438 lines (378 loc) · 12.7 KB
/
memory-source.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
import { Assertion } from '@orbit/core';
import {
coalesceRecordOperations,
RecordOperation,
RecordOperationResult,
RecordQueryResult,
RecordQueryExpressionResult,
RecordTransformResult,
RecordSource,
RecordSourceSettings,
RecordTransform,
RecordQuery,
RecordSyncable,
RecordUpdatable,
RecordQueryable,
RecordSourceQueryOptions
} from '@orbit/records';
import {
syncable,
RequestOptions,
queryable,
updatable,
buildTransform,
FullResponse,
DefaultRequestOptions
} from '@orbit/data';
import { ResponseHints } from '@orbit/data';
import { Dict } from '@orbit/utils';
import {
MemoryCache,
MemoryCacheClass,
MemoryCacheSettings
} from './memory-cache';
export interface MemorySourceSettings extends RecordSourceSettings {
base?: MemorySource;
cacheClass?: MemoryCacheClass;
cacheSettings?: Partial<MemoryCacheSettings>;
}
export interface MemorySourceMergeOptions {
coalesce?: boolean;
sinceTransformId?: string;
transformOptions?: RequestOptions;
}
export interface MemorySource
extends RecordSource,
RecordSyncable,
RecordQueryable<unknown>,
RecordUpdatable<unknown> {}
@syncable
@queryable
@updatable
export class MemorySource extends RecordSource {
private _cache: MemoryCache;
private _base?: MemorySource;
private _forkPoint?: string;
private _transforms: Dict<RecordTransform>;
private _transformInverses: Dict<RecordOperation[]>;
constructor(settings: MemorySourceSettings) {
const { keyMap, schema } = 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> =
settings.cacheSettings ?? {};
cacheSettings.schema = schema;
cacheSettings.keyMap = keyMap;
cacheSettings.queryBuilder =
cacheSettings.queryBuilder ?? this.queryBuilder;
cacheSettings.transformBuilder =
cacheSettings.transformBuilder ?? this.transformBuilder;
cacheSettings.defaultQueryOptions =
cacheSettings.defaultQueryOptions ?? settings.defaultQueryOptions;
cacheSettings.defaultTransformOptions =
cacheSettings.defaultTransformOptions ?? settings.defaultTransformOptions;
if (settings.base) {
this._base = settings.base;
this._forkPoint = this._base.transformLog.head;
cacheSettings.base = this._base.cache;
}
const cacheClass = settings.cacheClass ?? MemoryCache;
this._cache = new cacheClass(cacheSettings as MemoryCacheSettings);
}
get cache(): MemoryCache {
return this._cache;
}
get base(): MemorySource | 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, unknown>
): Promise<FullResponse<RecordTransformResult, unknown, RecordOperation>> {
let results: RecordTransformResult;
const response: FullResponse<
RecordTransformResult,
unknown,
RecordOperation
> = {};
if (!this.transformLog.contains(transform.id)) {
results = this._applyTransform(transform);
response.transforms = [transform];
}
if (hints?.data) {
if (transform.operations.length > 1 && 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) {
if (transform.operations.length === 1 && Array.isArray(results)) {
response.data = results[0];
} else {
response.data = results;
}
}
if (hints?.details) {
response.details = hints.details;
}
return response;
}
/////////////////////////////////////////////////////////////////////////////
// Queryable interface implementation
/////////////////////////////////////////////////////////////////////////////
async _query(
query: RecordQuery,
hints?: ResponseHints<RecordQueryResult, unknown>
): Promise<FullResponse<RecordQueryResult, unknown, RecordOperation>> {
let response: FullResponse<RecordQueryResult, unknown, RecordOperation>;
if (hints?.data) {
response = {};
if (query.expressions.length > 1 && 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 });
}
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: MemorySourceSettings = { schema: this.schema }): MemorySource {
const schema = this.schema;
settings.schema = schema;
settings.cacheSettings = settings.cacheSettings || { schema };
settings.keyMap = this._keyMap;
settings.queryBuilder = this.queryBuilder;
settings.transformBuilder = this.transformBuilder;
settings.base = this;
return new MemorySource(settings);
}
/**
* 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(
forkedSource: MemorySource,
options: MemorySourceMergeOptions = {}
): Promise<any> {
let transforms: RecordTransform[];
if (options.sinceTransformId) {
transforms = forkedSource.transformsSince(options.sinceTransformId);
} else {
transforms = forkedSource.allTransforms();
}
let reducedTransform;
let ops: RecordOperation[] = [];
transforms.forEach((t) => {
Array.prototype.push.apply(ops, t.operations);
});
if (options.coalesce !== false) {
ops = coalesceRecordOperations(ops);
}
reducedTransform = buildTransform(ops, options.transformOptions);
return this.update(reducedTransform);
}
/**
* 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. If, after some updates on both sources
* `childSource.rebase()` is called, the result on the child source will look
* like, as if all updates to the parent source were added first, followed by
* those made in the child source. This means that updates in the child source
* have a tendency of winning.
*/
rebase(): void {
let base = this._base;
let forkPoint = this._forkPoint;
if (!base) {
throw new Assertion(
'A `base` source must be defined for `rebase` to work'
);
}
let baseTransforms: RecordTransform[];
if (forkPoint === undefined) {
// source was empty at fork point
baseTransforms = base.allTransforms();
} else {
baseTransforms = base.transformsSince(forkPoint);
}
if (baseTransforms.length > 0) {
let localTransforms = this.allTransforms();
localTransforms.reverse().forEach((transform) => {
const inverseOperations = this._transformInverses[transform.id];
if (inverseOperations) {
this.cache.update(inverseOperations);
}
this._clearTransformFromHistory(transform.id);
});
baseTransforms.forEach((transform) => this._applyTransform(transform));
localTransforms.forEach((transform) => this._applyTransform(transform));
this._forkPoint = base.transformLog.head;
}
}
/**
* 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 transforms since a particular `transformId`.
*/
transformsSince(transformId: string): RecordTransform[] {
return this.transformLog
.after(transformId)
.map((id) => this._transforms[id]);
}
/**
* Returns all tracked transforms.
*/
allTransforms(): RecordTransform[] {
return this.transformLog.entries.map((id) => this._transforms[id]);
}
getTransform(transformId: string): RecordTransform {
return this._transforms[transformId];
}
getInverseOperations(transformId: string): RecordOperation[] {
return this._transformInverses[transformId];
}
get defaultQueryOptions():
| DefaultRequestOptions<RecordSourceQueryOptions>
| undefined {
return super.defaultQueryOptions;
}
set defaultQueryOptions(
options: DefaultRequestOptions<RecordSourceQueryOptions> | undefined
) {
super.defaultQueryOptions = this.cache.defaultQueryOptions = options;
}
get defaultTransformOptions():
| DefaultRequestOptions<RequestOptions>
| undefined {
return super.defaultTransformOptions;
}
set defaultTransformOptions(
options: DefaultRequestOptions<RequestOptions> | 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
});
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);
});
}
}