@verdant-web/store 3.0.0-next.0 → 3.0.1
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.
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/index.js.map +4 -4
- package/dist/cjs/DocumentManager.d.ts +5 -6
- package/dist/cjs/DocumentManager.js +2 -2
- package/dist/cjs/DocumentManager.js.map +1 -1
- package/dist/cjs/client/Client.d.ts +3 -2
- package/dist/cjs/client/Client.js +1 -1
- package/dist/cjs/client/Client.js.map +1 -1
- package/dist/cjs/entities/Entity.d.ts +106 -171
- package/dist/cjs/entities/Entity.js +558 -383
- package/dist/cjs/entities/Entity.js.map +1 -1
- package/dist/cjs/entities/Entity.test.js.map +1 -0
- package/dist/cjs/entities/{2/EntityCache.d.ts → EntityCache.d.ts} +1 -1
- package/dist/cjs/entities/{2/EntityCache.js → EntityCache.js} +1 -1
- package/dist/cjs/entities/EntityCache.js.map +1 -0
- package/dist/{esm/entities/2 → cjs/entities}/EntityMetadata.d.ts +1 -1
- package/dist/cjs/entities/EntityMetadata.js.map +1 -0
- package/dist/cjs/entities/EntityStore.d.ts +63 -68
- package/dist/cjs/entities/EntityStore.js +296 -424
- package/dist/cjs/entities/EntityStore.js.map +1 -1
- package/dist/{esm/entities/2 → cjs/entities}/OperationBatcher.d.ts +2 -2
- package/dist/cjs/entities/OperationBatcher.js.map +1 -0
- package/dist/cjs/entities/{2/types.js.map → types.js.map} +1 -1
- package/dist/cjs/files/EntityFile.d.ts +5 -4
- package/dist/cjs/files/EntityFile.js.map +1 -1
- package/dist/cjs/index.d.ts +3 -3
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/queries/BaseQuery.js +1 -1
- package/dist/cjs/queries/BaseQuery.js.map +1 -1
- package/dist/cjs/queries/CollectionQueries.d.ts +4 -2
- package/dist/cjs/queries/utils.js +1 -1
- package/dist/cjs/queries/utils.js.map +1 -1
- package/dist/esm/DocumentManager.d.ts +5 -6
- package/dist/esm/DocumentManager.js +2 -2
- package/dist/esm/DocumentManager.js.map +1 -1
- package/dist/esm/client/Client.d.ts +3 -2
- package/dist/esm/client/Client.js +1 -1
- package/dist/esm/client/Client.js.map +1 -1
- package/dist/esm/entities/Entity.d.ts +106 -171
- package/dist/esm/entities/Entity.js +559 -383
- package/dist/esm/entities/Entity.js.map +1 -1
- package/dist/esm/entities/Entity.test.js.map +1 -0
- package/dist/esm/entities/{2/EntityCache.d.ts → EntityCache.d.ts} +1 -1
- package/dist/esm/entities/{2/EntityCache.js → EntityCache.js} +1 -1
- package/dist/esm/entities/EntityCache.js.map +1 -0
- package/dist/{cjs/entities/2 → esm/entities}/EntityMetadata.d.ts +1 -1
- package/dist/esm/entities/EntityMetadata.js.map +1 -0
- package/dist/esm/entities/EntityStore.d.ts +63 -68
- package/dist/esm/entities/EntityStore.js +297 -425
- package/dist/esm/entities/EntityStore.js.map +1 -1
- package/dist/{cjs/entities/2 → esm/entities}/OperationBatcher.d.ts +2 -2
- package/dist/esm/entities/OperationBatcher.js.map +1 -0
- package/dist/esm/entities/{2/types.js.map → types.js.map} +1 -1
- package/dist/esm/files/EntityFile.d.ts +5 -4
- package/dist/esm/files/EntityFile.js.map +1 -1
- package/dist/esm/index.d.ts +3 -3
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/queries/BaseQuery.js +1 -1
- package/dist/esm/queries/BaseQuery.js.map +1 -1
- package/dist/esm/queries/CollectionQueries.d.ts +4 -2
- package/dist/esm/queries/utils.js +1 -1
- package/dist/esm/queries/utils.js.map +1 -1
- package/dist/tsconfig-cjs.tsbuildinfo +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/src/DocumentManager.ts +7 -3
- package/src/__tests__/batching.test.ts +1 -1
- package/src/client/Client.ts +1 -1
- package/src/entities/{2/Entity.test.ts → Entity.test.ts} +2 -2
- package/src/entities/{2/Entity.ts → Entity.ts} +4 -4
- package/src/entities/{2/EntityCache.ts → EntityCache.ts} +1 -1
- package/src/entities/{2/EntityMetadata.ts → EntityMetadata.ts} +1 -1
- package/src/entities/{2/EntityStore.ts → EntityStore.ts} +12 -8
- package/src/entities/{2/OperationBatcher.ts → OperationBatcher.ts} +2 -2
- package/src/files/EntityFile.ts +6 -1
- package/src/index.ts +3 -3
- package/src/queries/BaseQuery.ts +1 -1
- package/src/queries/CollectionQueries.ts +2 -2
- package/src/queries/utils.ts +1 -1
- package/dist/cjs/entities/2/Entity.d.ts +0 -148
- package/dist/cjs/entities/2/Entity.js +0 -711
- package/dist/cjs/entities/2/Entity.js.map +0 -1
- package/dist/cjs/entities/2/Entity.test.js.map +0 -1
- package/dist/cjs/entities/2/EntityCache.js.map +0 -1
- package/dist/cjs/entities/2/EntityMetadata.js.map +0 -1
- package/dist/cjs/entities/2/EntityStore.d.ts +0 -78
- package/dist/cjs/entities/2/EntityStore.js +0 -352
- package/dist/cjs/entities/2/EntityStore.js.map +0 -1
- package/dist/cjs/entities/2/OperationBatcher.js.map +0 -1
- package/dist/cjs/entities/DocumentFamiliyCache.d.ts +0 -96
- package/dist/cjs/entities/DocumentFamiliyCache.js +0 -287
- package/dist/cjs/entities/DocumentFamiliyCache.js.map +0 -1
- package/dist/cjs/entities/FakeWeakRef.d.ts +0 -11
- package/dist/cjs/entities/FakeWeakRef.js +0 -19
- package/dist/cjs/entities/FakeWeakRef.js.map +0 -1
- package/dist/cjs/indexes.d.ts +0 -3
- package/dist/cjs/indexes.js +0 -20
- package/dist/cjs/indexes.js.map +0 -1
- package/dist/esm/entities/2/Entity.d.ts +0 -148
- package/dist/esm/entities/2/Entity.js +0 -707
- package/dist/esm/entities/2/Entity.js.map +0 -1
- package/dist/esm/entities/2/Entity.test.js.map +0 -1
- package/dist/esm/entities/2/EntityCache.js.map +0 -1
- package/dist/esm/entities/2/EntityMetadata.js.map +0 -1
- package/dist/esm/entities/2/EntityStore.d.ts +0 -78
- package/dist/esm/entities/2/EntityStore.js +0 -348
- package/dist/esm/entities/2/EntityStore.js.map +0 -1
- package/dist/esm/entities/2/OperationBatcher.js.map +0 -1
- package/dist/esm/entities/DocumentFamiliyCache.d.ts +0 -96
- package/dist/esm/entities/DocumentFamiliyCache.js +0 -283
- package/dist/esm/entities/DocumentFamiliyCache.js.map +0 -1
- package/dist/esm/entities/FakeWeakRef.d.ts +0 -11
- package/dist/esm/entities/FakeWeakRef.js +0 -15
- package/dist/esm/entities/FakeWeakRef.js.map +0 -1
- package/dist/esm/indexes.d.ts +0 -3
- package/dist/esm/indexes.js +0 -15
- package/dist/esm/indexes.js.map +0 -1
- package/src/entities/2/NOTES.md +0 -22
- package/src/entities/design.tldr +0 -808
- /package/dist/cjs/entities/{2/Entity.test.d.ts → Entity.test.d.ts} +0 -0
- /package/dist/cjs/entities/{2/Entity.test.js → Entity.test.js} +0 -0
- /package/dist/cjs/entities/{2/EntityMetadata.js → EntityMetadata.js} +0 -0
- /package/dist/cjs/entities/{2/OperationBatcher.js → OperationBatcher.js} +0 -0
- /package/dist/cjs/entities/{2/types.d.ts → types.d.ts} +0 -0
- /package/dist/cjs/entities/{2/types.js → types.js} +0 -0
- /package/dist/esm/entities/{2/Entity.test.d.ts → Entity.test.d.ts} +0 -0
- /package/dist/esm/entities/{2/Entity.test.js → Entity.test.js} +0 -0
- /package/dist/esm/entities/{2/EntityMetadata.js → EntityMetadata.js} +0 -0
- /package/dist/esm/entities/{2/OperationBatcher.js → OperationBatcher.js} +0 -0
- /package/dist/esm/entities/{2/types.d.ts → types.d.ts} +0 -0
- /package/dist/esm/entities/{2/types.js → types.js} +0 -0
- /package/src/entities/{2/types.ts → types.ts} +0 -0
|
@@ -1,476 +1,348 @@
|
|
|
1
|
-
import { assert, assignOid,
|
|
1
|
+
import { assert, assignOid, decomposeOid, getOidRoot, groupBaselinesByRootOid, groupPatchesByOid, groupPatchesByRootOid, isRootOid, removeOidsFromAllSubObjects, } from '@verdant-web/common';
|
|
2
|
+
import { Entity } from './Entity.js';
|
|
3
|
+
import { Disposable } from '../utils/Disposable.js';
|
|
4
|
+
import { EntityFamilyMetadata } from './EntityMetadata.js';
|
|
5
|
+
import { OperationBatcher } from './OperationBatcher.js';
|
|
6
|
+
import { QueryableStorage } from '../queries/QueryableStorage.js';
|
|
7
|
+
import { WeakEvent } from 'weak-event';
|
|
2
8
|
import { processValueFiles } from '../files/utils.js';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return this.context.undoHistory;
|
|
15
|
-
}
|
|
16
|
-
get schema() {
|
|
17
|
-
return this.context.schema;
|
|
18
|
-
}
|
|
19
|
-
constructor({ context, meta, batchTimeout = 200, files, }) {
|
|
20
|
-
this.documentFamilyCaches = new Map();
|
|
21
|
-
this.unsubscribes = [];
|
|
22
|
-
this._disposed = false;
|
|
23
|
-
this.currentBatchKey = DEFAULT_BATCH_KEY;
|
|
24
|
-
this.setContext = (context) => {
|
|
25
|
-
this.context = context;
|
|
9
|
+
var AbortReason;
|
|
10
|
+
(function (AbortReason) {
|
|
11
|
+
AbortReason[AbortReason["Reset"] = 0] = "Reset";
|
|
12
|
+
})(AbortReason || (AbortReason = {}));
|
|
13
|
+
export class EntityStore extends Disposable {
|
|
14
|
+
constructor({ ctx, meta, files, }) {
|
|
15
|
+
super();
|
|
16
|
+
this.events = {
|
|
17
|
+
add: new WeakEvent(),
|
|
18
|
+
replace: new WeakEvent(),
|
|
19
|
+
resetAll: new WeakEvent(),
|
|
26
20
|
};
|
|
27
|
-
this.
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
},
|
|
40
|
-
};
|
|
41
|
-
};
|
|
42
|
-
this.refreshFamilyCache = async (familyCache, dropUnconfirmed = false, dropAll = false) => {
|
|
43
|
-
// avoid writing to disposed db
|
|
44
|
-
if (this._disposed) {
|
|
45
|
-
this.context.log('debug', `EntityStore is disposed, not refreshing ${familyCache.oid} cache`);
|
|
21
|
+
this.cache = new Map();
|
|
22
|
+
this.pendingEntityPromises = new Map();
|
|
23
|
+
// halts the current data queue processing
|
|
24
|
+
this.abortDataQueueController = new AbortController();
|
|
25
|
+
this.ongoingResetPromise = null;
|
|
26
|
+
this.entityFinalizationRegistry = new FinalizationRegistry((oid) => {
|
|
27
|
+
this.ctx.log('debug', 'Entity GC', oid);
|
|
28
|
+
});
|
|
29
|
+
// internal-ish API to load remote / stored data
|
|
30
|
+
this.addData = async (data) => {
|
|
31
|
+
if (this.disposed) {
|
|
32
|
+
this.ctx.log('warn', 'EntityStore is disposed, not adding incoming data');
|
|
46
33
|
return;
|
|
47
34
|
}
|
|
48
|
-
//
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
'
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
this.
|
|
57
|
-
|
|
58
|
-
}, {
|
|
59
|
-
transaction,
|
|
60
|
-
mode: 'readwrite',
|
|
61
|
-
}),
|
|
62
|
-
this.meta.operations.iterateOverAllOperationsForDocument(familyCache.oid, (op) => {
|
|
63
|
-
op.confirmed = true;
|
|
64
|
-
operations.push(op);
|
|
65
|
-
}, { transaction, mode: 'readwrite' }),
|
|
66
|
-
]);
|
|
67
|
-
familyCache.reset({
|
|
68
|
-
operations,
|
|
69
|
-
baselines,
|
|
70
|
-
dropExistingUnconfirmed: dropUnconfirmed,
|
|
71
|
-
dropAll,
|
|
72
|
-
});
|
|
73
|
-
};
|
|
74
|
-
this.openFamilyCache = async (oid) => {
|
|
75
|
-
const documentOid = getOidRoot(oid);
|
|
76
|
-
let familyCache = this.documentFamilyCaches.get(documentOid);
|
|
77
|
-
if (!familyCache) {
|
|
78
|
-
this.context.log('debug', 'opening family cache for', documentOid);
|
|
79
|
-
// metadata must be loaded from database to initialize family cache
|
|
80
|
-
familyCache = new DocumentFamilyCache({
|
|
81
|
-
oid: documentOid,
|
|
82
|
-
store: this,
|
|
83
|
-
context: this.context,
|
|
35
|
+
// for resets - abort any other changes, reset everything,
|
|
36
|
+
// then proceed
|
|
37
|
+
if (data.reset) {
|
|
38
|
+
this.ctx.log('info', 'Resetting local store to replicate remote synced data - dropping any current transactions');
|
|
39
|
+
// cancel any other ongoing data - it will all
|
|
40
|
+
// be replaced by the reset
|
|
41
|
+
this.abortDataQueueController.abort(AbortReason.Reset);
|
|
42
|
+
this.abortDataQueueController = new AbortController();
|
|
43
|
+
this.ongoingResetPromise = this.resetData().finally(() => {
|
|
44
|
+
this.ongoingResetPromise = null;
|
|
84
45
|
});
|
|
85
|
-
// PROBLEM: because the next line is async, it yields to
|
|
86
|
-
// queued promises which may need data from this cache,
|
|
87
|
-
// but the cache is empty. But if we move the set to
|
|
88
|
-
// after the async, we can clobber an existing cache
|
|
89
|
-
// with race conditions...
|
|
90
|
-
// So as an attempt to fix that, I've added a promise
|
|
91
|
-
// on DocumentFamilyCache which I manually resolve
|
|
92
|
-
// with setInitialized, then await initializedPromise
|
|
93
|
-
// further down even if there was a cache hit.
|
|
94
|
-
// Surely there is a better pattern for this.
|
|
95
|
-
// FIXME:
|
|
96
|
-
this.documentFamilyCaches.set(documentOid, familyCache);
|
|
97
|
-
await this.refreshFamilyCache(familyCache);
|
|
98
|
-
familyCache.setInitialized();
|
|
99
|
-
// this.unsubscribes.push(
|
|
100
|
-
// familyCache.subscribe('change:*', this.onEntityChange),
|
|
101
|
-
// );
|
|
102
|
-
// TODO: cleanup cache when all documents are disposed
|
|
103
46
|
}
|
|
104
|
-
await
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
47
|
+
// await either the reset we just started, or any that was
|
|
48
|
+
// in progress when this data came in.
|
|
49
|
+
if (this.ongoingResetPromise) {
|
|
50
|
+
this.ctx.log('debug', 'Waiting for ongoing reset to complete');
|
|
51
|
+
await this.ongoingResetPromise;
|
|
52
|
+
this.ctx.log('debug', 'Ongoing reset complete');
|
|
53
|
+
}
|
|
54
|
+
await this.processData(data);
|
|
109
55
|
};
|
|
110
|
-
this.
|
|
111
|
-
if (this.
|
|
112
|
-
this.log('warn', 'EntityStore is disposed, not
|
|
56
|
+
this.resetData = async () => {
|
|
57
|
+
if (this.disposed) {
|
|
58
|
+
this.ctx.log('warn', 'EntityStore is disposed, not resetting local data');
|
|
113
59
|
return;
|
|
114
60
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
61
|
+
await this.meta.reset();
|
|
62
|
+
await this.queryableStorage.reset();
|
|
63
|
+
this.events.resetAll.invoke(this);
|
|
64
|
+
};
|
|
65
|
+
this.processData = async (data) => {
|
|
66
|
+
var _a, _b, _c;
|
|
67
|
+
if (this.disposed) {
|
|
68
|
+
this.ctx.log('warn', 'EntityStore is disposed, not processing incoming data');
|
|
120
69
|
return;
|
|
121
70
|
}
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
71
|
+
const baselines = (_a = data === null || data === void 0 ? void 0 : data.baselines) !== null && _a !== void 0 ? _a : [];
|
|
72
|
+
const operations = (_b = data === null || data === void 0 ? void 0 : data.operations) !== null && _b !== void 0 ? _b : [];
|
|
73
|
+
this.ctx.log('debug', 'Processing incoming data', {
|
|
74
|
+
operations: operations.length,
|
|
75
|
+
baselines: baselines.length,
|
|
76
|
+
reset: !!data.reset,
|
|
77
|
+
});
|
|
78
|
+
const allDocumentOids = Array.from(new Set(baselines
|
|
79
|
+
.map((b) => getOidRoot(b.oid))
|
|
80
|
+
.concat(operations.map((o) => getOidRoot(o.oid)))));
|
|
81
|
+
const baselinesGroupedByOid = groupBaselinesByRootOid(baselines);
|
|
82
|
+
const operationsGroupedByOid = groupPatchesByRootOid(operations);
|
|
83
|
+
this.ctx.log('debug', 'Applying data to live entities');
|
|
84
|
+
// synchronously add/replace data in any open entities via eventing
|
|
85
|
+
for (const oid of allDocumentOids) {
|
|
86
|
+
const baselines = baselinesGroupedByOid[oid];
|
|
87
|
+
const operations = (_c = operationsGroupedByOid[oid]) !== null && _c !== void 0 ? _c : [];
|
|
88
|
+
const groupedOperations = groupPatchesByOid(operations);
|
|
89
|
+
// what happens if an entity is being hydrated
|
|
90
|
+
// while this is happening? - we wait for the hydration promise
|
|
91
|
+
// to complete, then invoke the event
|
|
92
|
+
const event = data.reset ? this.events.replace : this.events.add;
|
|
93
|
+
const hydrationPromise = this.pendingEntityPromises.get(oid);
|
|
94
|
+
if (hydrationPromise) {
|
|
95
|
+
hydrationPromise.then(() => {
|
|
96
|
+
event.invoke(this, {
|
|
97
|
+
oid,
|
|
98
|
+
baselines,
|
|
99
|
+
operations: groupedOperations,
|
|
100
|
+
isLocal: false,
|
|
101
|
+
});
|
|
102
|
+
});
|
|
130
103
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
104
|
+
else {
|
|
105
|
+
if (this.cache.has(oid)) {
|
|
106
|
+
this.ctx.log('debug', 'Cache has', oid, ', an event should follow.');
|
|
107
|
+
}
|
|
108
|
+
event.invoke(this, {
|
|
109
|
+
oid,
|
|
110
|
+
baselines,
|
|
111
|
+
operations: groupedOperations,
|
|
112
|
+
isLocal: false,
|
|
113
|
+
});
|
|
135
114
|
}
|
|
136
115
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
116
|
+
const abortOptions = {
|
|
117
|
+
abort: this.abortDataQueueController.signal,
|
|
118
|
+
};
|
|
119
|
+
// then, asynchronously add to the database
|
|
120
|
+
await this.meta.insertData(data, abortOptions);
|
|
121
|
+
// FIXME: entities hydrated here are not seeing
|
|
122
|
+
// the operations just inserted above!!
|
|
123
|
+
// IDEA: can we coordinate here with hydrate promises
|
|
124
|
+
// based on affected OIDs?
|
|
125
|
+
// recompute all affected documents for querying
|
|
126
|
+
const entities = await Promise.all(allDocumentOids.map(async (oid) => {
|
|
127
|
+
const entity = await this.hydrate(oid, abortOptions);
|
|
128
|
+
// if the entity is not found, we return a stub that
|
|
129
|
+
// indicates it's deleted and should be cleared
|
|
130
|
+
return (entity !== null && entity !== void 0 ? entity : {
|
|
131
|
+
oid,
|
|
132
|
+
getSnapshot() {
|
|
133
|
+
return null;
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
}));
|
|
137
|
+
try {
|
|
138
|
+
await this.queryableStorage.saveEntities(entities, abortOptions);
|
|
142
139
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
140
|
+
catch (err) {
|
|
141
|
+
if (this.disposed) {
|
|
142
|
+
this.ctx.log('warn', 'Error saving entities to queryable storage - EntityStore is disposed', err);
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
this.ctx.log('error', 'Error saving entities to queryable storage', err);
|
|
146
|
+
}
|
|
149
147
|
}
|
|
150
|
-
return familyCache.getEntity({ oid, fieldSchema: schema, readonlyKeys });
|
|
151
148
|
};
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
const
|
|
161
|
-
if (
|
|
149
|
+
// internal-ish API for creating Entities from OIDs
|
|
150
|
+
// when query results come in
|
|
151
|
+
this.hydrate = async (oid, opts) => {
|
|
152
|
+
if (!isRootOid(oid)) {
|
|
153
|
+
throw new Error('Cannot hydrate non-root entity');
|
|
154
|
+
}
|
|
155
|
+
if (this.cache.has(oid)) {
|
|
156
|
+
this.ctx.log('debug', 'Hydrating entity from cache', oid);
|
|
157
|
+
const cached = this.cache.get(oid);
|
|
158
|
+
if (cached) {
|
|
159
|
+
const entity = cached.deref();
|
|
160
|
+
if (entity) {
|
|
161
|
+
if (entity.deleted) {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
return entity;
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
this.ctx.log('debug', "Removing GC'd entity from cache", oid);
|
|
168
|
+
this.cache.delete(oid);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
// we don't want to hydrate two entities in parallel, so
|
|
173
|
+
// we use a promise to ensure that only one is ever
|
|
174
|
+
// constructed at a time
|
|
175
|
+
const pendingPromise = this.pendingEntityPromises.get(oid);
|
|
176
|
+
if (!pendingPromise) {
|
|
177
|
+
this.ctx.log('debug', 'Hydrating entity from storage', oid);
|
|
178
|
+
const entity = this.constructEntity(oid);
|
|
179
|
+
if (!entity) {
|
|
162
180
|
return null;
|
|
163
181
|
}
|
|
164
|
-
|
|
182
|
+
const pendingPromise = this.loadEntity(entity, opts);
|
|
183
|
+
pendingPromise.finally(() => {
|
|
184
|
+
this.pendingEntityPromises.delete(oid);
|
|
185
|
+
});
|
|
186
|
+
this.pendingEntityPromises.set(oid, pendingPromise);
|
|
187
|
+
return pendingPromise;
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
this.ctx.log('debug', 'Waiting for entity hydration', oid);
|
|
191
|
+
return pendingPromise;
|
|
165
192
|
}
|
|
166
|
-
return null;
|
|
167
193
|
};
|
|
194
|
+
this.destroy = async () => {
|
|
195
|
+
this.dispose();
|
|
196
|
+
await this.batcher.flushAll();
|
|
197
|
+
};
|
|
198
|
+
// public APIs for manipulating entities
|
|
168
199
|
/**
|
|
169
|
-
* Creates a new
|
|
170
|
-
* document is submitted to storage and sync.
|
|
200
|
+
* Creates a new Entity with the given initial data.
|
|
171
201
|
*/
|
|
172
|
-
this.create = async (initial, oid,
|
|
173
|
-
|
|
202
|
+
this.create = async (initial, oid, { undoable = true } = {}) => {
|
|
203
|
+
this.ctx.log('debug', 'Creating new entity', oid);
|
|
204
|
+
const { collection } = decomposeOid(oid);
|
|
205
|
+
// remove any OID associations from the initial data
|
|
174
206
|
removeOidsFromAllSubObjects(initial);
|
|
175
|
-
//
|
|
207
|
+
// grab files and replace them with refs
|
|
176
208
|
const processed = processValueFiles(initial, this.files.add);
|
|
177
209
|
assignOid(processed, oid);
|
|
178
|
-
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
// we do this so it can be immediately queryable from storage...
|
|
183
|
-
// only holding it in memory would introduce lag before it shows up
|
|
184
|
-
// in other queries.
|
|
185
|
-
await this.submitOperations(operations, options);
|
|
186
|
-
const { schema, readonlyKeys } = this.getDocumentSchema(oid);
|
|
187
|
-
if (!schema) {
|
|
188
|
-
throw new Error(`Cannot create a document in the ${decomposeOid(oid).collection} collection; it is not defined in the current schema version.`);
|
|
210
|
+
// creating a new Entity with no data, then preloading the operations
|
|
211
|
+
const entity = this.constructEntity(oid);
|
|
212
|
+
if (!entity) {
|
|
213
|
+
throw new Error(`Could not put new document: no schema exists for collection ${collection}`);
|
|
189
214
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
}
|
|
215
|
+
const operations = this.meta.patchCreator.createInitialize(processed, oid);
|
|
216
|
+
await this.batcher.commitOperations(operations, {
|
|
217
|
+
undoable: !!undoable,
|
|
218
|
+
source: entity,
|
|
219
|
+
});
|
|
220
|
+
// TODO: what happens if you create an entity with an OID that already
|
|
221
|
+
// exists?
|
|
222
|
+
// we still need to synchronously add the initial operations to the Entity
|
|
223
|
+
// even though they are flowing through the system
|
|
224
|
+
// TODO: this could be better aligned to avoid grouping here
|
|
225
|
+
const operationsGroupedByOid = groupPatchesByOid(operations);
|
|
226
|
+
this.events.add.invoke(this, {
|
|
227
|
+
operations: operationsGroupedByOid,
|
|
228
|
+
isLocal: true,
|
|
229
|
+
oid,
|
|
206
230
|
});
|
|
231
|
+
this.cache.set(oid, this.ctx.weakRef(entity));
|
|
232
|
+
return entity;
|
|
207
233
|
};
|
|
208
|
-
this.
|
|
209
|
-
|
|
210
|
-
|
|
234
|
+
this.deleteAll = async (oids, options) => {
|
|
235
|
+
this.ctx.log('info', 'Deleting documents', oids);
|
|
236
|
+
assert(oids.every((oid) => oid === getOidRoot(oid)), 'Only root documents may be deleted via client methods');
|
|
237
|
+
const allOids = await Promise.all(oids.flatMap(async (oid) => {
|
|
238
|
+
var _a;
|
|
239
|
+
const entity = await this.hydrate(oid);
|
|
240
|
+
return (_a = entity === null || entity === void 0 ? void 0 : entity.__getFamilyOids__()) !== null && _a !== void 0 ? _a : [];
|
|
241
|
+
}));
|
|
242
|
+
// remove the entities from cache
|
|
211
243
|
oids.forEach((oid) => {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
244
|
+
this.cache.delete(oid);
|
|
245
|
+
this.ctx.log('debug', 'Deleted document from cache', oid);
|
|
246
|
+
});
|
|
247
|
+
// create the delete patches and wait for them to be applied
|
|
248
|
+
const operations = this.meta.patchCreator.createDeleteAll(allOids.flat());
|
|
249
|
+
await this.batcher.commitOperations(operations, {
|
|
250
|
+
undoable: (options === null || options === void 0 ? void 0 : options.undoable) === undefined ? true : options.undoable,
|
|
217
251
|
});
|
|
218
252
|
};
|
|
219
|
-
this.
|
|
220
|
-
|
|
221
|
-
const baselinesByDocumentOid = groupBaselinesByRootOid(baselines);
|
|
222
|
-
const operationsByDocumentOid = groupPatchesByRootOid(operations);
|
|
223
|
-
const allDocumentOids = Array.from(new Set(Object.keys(baselinesByDocumentOid).concat(Object.keys(operationsByDocumentOid))));
|
|
224
|
-
for (const oid of allDocumentOids) {
|
|
225
|
-
const familyCache = this.documentFamilyCaches.get(oid);
|
|
226
|
-
if (familyCache) {
|
|
227
|
-
familyCache.addData({
|
|
228
|
-
operations: operationsByDocumentOid[oid] || [],
|
|
229
|
-
baselines: baselinesByDocumentOid[oid] || [],
|
|
230
|
-
reset,
|
|
231
|
-
isLocal,
|
|
232
|
-
});
|
|
233
|
-
this.log('debug', 'Added data to cache for', oid, (_b = (_a = operationsByDocumentOid[oid]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0, 'operations', (_d = (_c = baselinesByDocumentOid[oid]) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0, 'baselines');
|
|
234
|
-
}
|
|
235
|
-
else {
|
|
236
|
-
this.log('debug', 'Could not add data to cache for', oid, 'because it is not open');
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
return allDocumentOids;
|
|
253
|
+
this.delete = async (oid, options) => {
|
|
254
|
+
return this.deleteAll([oid], options);
|
|
240
255
|
};
|
|
241
|
-
this.
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const taggedOperations = operations;
|
|
250
|
-
for (const op of taggedOperations) {
|
|
251
|
-
op.confirmed = false;
|
|
252
|
-
}
|
|
253
|
-
let allDocumentOids = [];
|
|
254
|
-
// in a reset scenario, it only makes things confusing if we
|
|
255
|
-
// optimistically apply incoming operations, since the local
|
|
256
|
-
// history is out of sync
|
|
257
|
-
if (reset) {
|
|
258
|
-
this.log('Resetting local store to replicate remote synced data', baselines.length, 'baselines, and', operations.length, 'operations');
|
|
259
|
-
await this.meta.reset();
|
|
260
|
-
await this.resetStoredDocuments();
|
|
261
|
-
allDocumentOids = Array.from(new Set(baselines
|
|
262
|
-
.map((b) => getOidRoot(b.oid))
|
|
263
|
-
.concat(operations.map((o) => getOidRoot(o.oid)))));
|
|
264
|
-
}
|
|
265
|
-
else {
|
|
266
|
-
// first, synchronously add data to any open caches for immediate change propagation
|
|
267
|
-
allDocumentOids = this.addDataToOpenCaches({
|
|
268
|
-
operations: taggedOperations,
|
|
269
|
-
baselines,
|
|
270
|
-
reset,
|
|
271
|
-
});
|
|
272
|
-
}
|
|
273
|
-
// then, asynchronously add data to storage
|
|
274
|
-
await this.meta.insertRemoteBaselines(baselines);
|
|
275
|
-
await this.meta.insertRemoteOperations(operations);
|
|
276
|
-
if (reset) {
|
|
277
|
-
await this.refreshAllCaches(true, true);
|
|
278
|
-
}
|
|
279
|
-
// recompute all affected documents for querying
|
|
280
|
-
for (const oid of allDocumentOids) {
|
|
281
|
-
await this.writeDocumentToStorage(oid);
|
|
256
|
+
this.getCollectionSchema = (collectionName) => {
|
|
257
|
+
const schema = this.ctx.schema.collections[collectionName];
|
|
258
|
+
if (!schema) {
|
|
259
|
+
this.ctx.log('warn', `Missing schema for collection: ${collectionName}`);
|
|
260
|
+
return {
|
|
261
|
+
schema: null,
|
|
262
|
+
readonlyKeys: [],
|
|
263
|
+
};
|
|
282
264
|
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
this.log('Adding local operations', operations.length);
|
|
290
|
-
this.addOperationsToOpenCaches(operations, {
|
|
291
|
-
isLocal: true,
|
|
292
|
-
confirmed: false,
|
|
293
|
-
});
|
|
294
|
-
this.operationBatcher.add({
|
|
295
|
-
key: this.currentBatchKey,
|
|
296
|
-
items: operations,
|
|
297
|
-
});
|
|
298
|
-
};
|
|
299
|
-
this.batch = ({ undoable = true, batchName = generateId(), max = null, timeout = this.defaultBatchTimeout, } = {}) => {
|
|
300
|
-
const internalBatch = this.operationBatcher.add({
|
|
301
|
-
key: batchName,
|
|
302
|
-
max,
|
|
303
|
-
timeout,
|
|
304
|
-
items: [],
|
|
305
|
-
userData: { undoable },
|
|
306
|
-
});
|
|
307
|
-
const externalApi = {
|
|
308
|
-
run: (fn) => {
|
|
309
|
-
// while the provided function runs, operations are forwarded
|
|
310
|
-
// to the new batch instead of default. this relies on the function
|
|
311
|
-
// being synchronous.
|
|
312
|
-
this.currentBatchKey = batchName;
|
|
313
|
-
fn();
|
|
314
|
-
this.currentBatchKey = DEFAULT_BATCH_KEY;
|
|
315
|
-
return externalApi;
|
|
316
|
-
},
|
|
317
|
-
flush: async () => {
|
|
318
|
-
// before running a batch, the default operations must be flushed
|
|
319
|
-
// this better preserves undo history behavior...
|
|
320
|
-
// if we left the default batch open while flushing a named batch,
|
|
321
|
-
// then the default batch would be flushed after the named batch,
|
|
322
|
-
// and the default batch could contain operations both prior and
|
|
323
|
-
// after the named batch. this would result in a confusing undo
|
|
324
|
-
// history where the first undo might reverse changes before and
|
|
325
|
-
// after a set of other changes.
|
|
326
|
-
await this.operationBatcher.flush(DEFAULT_BATCH_KEY);
|
|
327
|
-
return internalBatch.flush();
|
|
328
|
-
},
|
|
329
|
-
discard: () => {
|
|
330
|
-
this.operationBatcher.discard(batchName);
|
|
265
|
+
return {
|
|
266
|
+
// convert to object schema for compatibility
|
|
267
|
+
schema: {
|
|
268
|
+
type: 'object',
|
|
269
|
+
nullable: false,
|
|
270
|
+
properties: schema.fields,
|
|
331
271
|
},
|
|
272
|
+
readonlyKeys: [schema.primaryKey],
|
|
332
273
|
};
|
|
333
|
-
return externalApi;
|
|
334
274
|
};
|
|
335
275
|
/**
|
|
336
|
-
*
|
|
276
|
+
* Constructs an entity from an OID, but does not load it.
|
|
337
277
|
*/
|
|
338
|
-
this.
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
};
|
|
344
|
-
this.flushOperations = async (operations, batchKey, meta) => {
|
|
345
|
-
if (!operations.length)
|
|
346
|
-
return;
|
|
347
|
-
this.log('Flushing operations', operations.length, 'to storage / sync');
|
|
348
|
-
// rewrite timestamps of all operations to now - this preserves
|
|
349
|
-
// the linear history of operations which are sent to the server.
|
|
350
|
-
// even if multiple batches are spun up in parallel and flushed
|
|
351
|
-
// after delay, the final operations in each one should reflect
|
|
352
|
-
// when the batch flushed, not when the changes were made.
|
|
353
|
-
// This also corresponds to user-observed behavior, since unconfirmed
|
|
354
|
-
// operations are applied universally after confirmed operations locally,
|
|
355
|
-
// so even operations which were made before a remote operation but
|
|
356
|
-
// have not been confirmed yet will appear to come after the remote one
|
|
357
|
-
// despite the provisional timestamp being earlier (see DocumentFamilyCache#computeView)
|
|
358
|
-
for (const op of operations) {
|
|
359
|
-
op.timestamp = this.meta.now;
|
|
360
|
-
}
|
|
361
|
-
await this.submitOperations(operations, meta);
|
|
362
|
-
};
|
|
363
|
-
this.submitOperations = async (operations, { undoable = true } = {}) => {
|
|
364
|
-
if (undoable) {
|
|
365
|
-
// FIXME: this is too slow and needs to be optimized.
|
|
366
|
-
this.undoHistory.addUndo(await this.createUndo(operations));
|
|
367
|
-
}
|
|
368
|
-
await this.meta.insertLocalOperation(operations);
|
|
369
|
-
// confirm the operations
|
|
370
|
-
this.addDataToOpenCaches({ operations, baselines: [] });
|
|
371
|
-
// recompute all affected documents for querying
|
|
372
|
-
const allDocumentOids = Array.from(new Set(operations.map((op) => getOidRoot(op.oid))));
|
|
373
|
-
for (const oid of allDocumentOids) {
|
|
374
|
-
await this.writeDocumentToStorage(oid);
|
|
375
|
-
}
|
|
376
|
-
// TODO: find a more efficient and straightforward way to update affected
|
|
377
|
-
// queries. Move to Metadata?
|
|
378
|
-
const affectedCollections = new Set(operations.map(({ oid }) => decomposeOid(oid).collection));
|
|
379
|
-
this.context.log('changes to collections', affectedCollections);
|
|
380
|
-
this.context.entityEvents.emit('collectionsChanged', Array.from(affectedCollections));
|
|
381
|
-
};
|
|
382
|
-
this.getInverseOperations = async (ops) => {
|
|
383
|
-
const grouped = groupPatchesByIdentifier(ops);
|
|
384
|
-
const inverseOps = [];
|
|
385
|
-
const getNow = () => this.meta.now;
|
|
386
|
-
for (const [oid, patches] of Object.entries(grouped)) {
|
|
387
|
-
const familyCache = await this.openFamilyCache(oid);
|
|
388
|
-
let { view, deleted } = familyCache.computeConfirmedView(oid);
|
|
389
|
-
const inverse = getUndoOperations(oid, view, patches, getNow);
|
|
390
|
-
inverseOps.unshift(...inverse);
|
|
391
|
-
}
|
|
392
|
-
return inverseOps;
|
|
393
|
-
};
|
|
394
|
-
this.createUndo = async (ops) => {
|
|
395
|
-
const inverseOps = await this.getInverseOperations(ops);
|
|
396
|
-
return async () => {
|
|
397
|
-
const redo = await this.createUndo(inverseOps);
|
|
398
|
-
await this.submitOperations(inverseOps.map((op) => {
|
|
399
|
-
op.timestamp = this.meta.now;
|
|
400
|
-
return op;
|
|
401
|
-
}),
|
|
402
|
-
// undos should not generate their own undo operations
|
|
403
|
-
// since they already calculate redo as the inverse.
|
|
404
|
-
{ undoable: false });
|
|
405
|
-
return redo;
|
|
406
|
-
};
|
|
407
|
-
};
|
|
408
|
-
this.delete = async (oid, options) => {
|
|
409
|
-
assert(oid === getOidRoot(oid), 'Only root documents may be deleted via client methods');
|
|
410
|
-
// we need to get all sub-object oids to delete alongside the root
|
|
411
|
-
const allOids = await this.meta.getAllDocumentRelatedOids(oid);
|
|
412
|
-
const patches = this.meta.patchCreator.createDeleteAll(allOids);
|
|
413
|
-
// don't enqueue these, submit as distinct operation
|
|
414
|
-
await this.submitOperations(patches, options);
|
|
415
|
-
};
|
|
416
|
-
this.deleteAll = async (oids, options) => {
|
|
417
|
-
const allOids = await Promise.all(oids.map((oid) => this.meta.getAllDocumentRelatedOids(oid)));
|
|
418
|
-
const patches = this.meta.patchCreator.createDeleteAll(allOids.flat());
|
|
419
|
-
// don't enqueue these, submit as distinct operation
|
|
420
|
-
await this.submitOperations(patches, options);
|
|
421
|
-
};
|
|
422
|
-
this.reset = async () => {
|
|
423
|
-
this.context.log('warn', 'Resetting local database');
|
|
424
|
-
await this.resetStoredDocuments();
|
|
425
|
-
await this.refreshAllCaches(true);
|
|
426
|
-
// this.context.entityEvents.emit(
|
|
427
|
-
// 'collectionsChanged',
|
|
428
|
-
// Object.keys(this.schema.collections),
|
|
429
|
-
// );
|
|
430
|
-
};
|
|
431
|
-
this.destroy = async () => {
|
|
432
|
-
this._disposed = true;
|
|
433
|
-
for (const unsubscribe of this.unsubscribes) {
|
|
434
|
-
unsubscribe();
|
|
278
|
+
this.constructEntity = (oid) => {
|
|
279
|
+
const { collection } = decomposeOid(oid);
|
|
280
|
+
const { schema, readonlyKeys } = this.getCollectionSchema(collection);
|
|
281
|
+
if (!schema) {
|
|
282
|
+
return null;
|
|
435
283
|
}
|
|
436
|
-
|
|
437
|
-
|
|
284
|
+
if (this.disposed) {
|
|
285
|
+
throw new Error('Cannot hydrate entity after store has been disposed');
|
|
438
286
|
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
//
|
|
445
|
-
//
|
|
446
|
-
|
|
287
|
+
const metadataFamily = new EntityFamilyMetadata({
|
|
288
|
+
ctx: this.ctx,
|
|
289
|
+
onPendingOperations: this.onPendingOperations,
|
|
290
|
+
rootOid: oid,
|
|
291
|
+
});
|
|
292
|
+
// this is created synchronously so it's immediately available
|
|
293
|
+
// to begin capturing incoming data.
|
|
294
|
+
return new Entity({
|
|
295
|
+
ctx: this.ctx,
|
|
296
|
+
oid,
|
|
297
|
+
schema,
|
|
298
|
+
readonlyKeys,
|
|
299
|
+
files: this.files,
|
|
300
|
+
metadataFamily: metadataFamily,
|
|
301
|
+
patchCreator: this.meta.patchCreator,
|
|
302
|
+
events: this.events,
|
|
303
|
+
});
|
|
447
304
|
};
|
|
448
|
-
this.
|
|
449
|
-
|
|
450
|
-
for (const collection of Object.keys(this.schema.collections)) {
|
|
451
|
-
const store = tx.objectStore(collection);
|
|
452
|
-
await storeRequestPromise(store.clear());
|
|
453
|
-
}
|
|
305
|
+
this.onPendingOperations = (operations) => {
|
|
306
|
+
this.batcher.addOperations(operations);
|
|
454
307
|
};
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
308
|
+
/**
|
|
309
|
+
* Loads initial Entity data from storage
|
|
310
|
+
*/
|
|
311
|
+
this.loadEntity = async (entity, opts) => {
|
|
312
|
+
const { operations, baselines } = await this.meta.getDocumentData(entity.oid, opts);
|
|
313
|
+
if (!baselines.length && !Object.keys(operations).length) {
|
|
314
|
+
this.ctx.log('debug', 'No data found for entity', entity.oid);
|
|
315
|
+
return null;
|
|
458
316
|
}
|
|
317
|
+
this.ctx.log('debug', 'Loaded entity from storage', entity.oid);
|
|
318
|
+
this.events.replace.invoke(this, {
|
|
319
|
+
oid: entity.oid,
|
|
320
|
+
baselines,
|
|
321
|
+
operations,
|
|
322
|
+
isLocal: false,
|
|
323
|
+
});
|
|
324
|
+
// only set the cache after loading.
|
|
325
|
+
// TODO: is this cache/promise stuff redundant?
|
|
326
|
+
this.cache.set(entity.oid, this.ctx.weakRef(entity));
|
|
327
|
+
this.entityFinalizationRegistry.register(entity, entity.oid);
|
|
328
|
+
return entity;
|
|
459
329
|
};
|
|
460
|
-
this.
|
|
461
|
-
this.defaultBatchTimeout = batchTimeout;
|
|
330
|
+
this.ctx = ctx;
|
|
462
331
|
this.meta = meta;
|
|
463
332
|
this.files = files;
|
|
464
|
-
this.
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
max: 100,
|
|
470
|
-
timeout: batchTimeout,
|
|
471
|
-
userData: { undoable: true },
|
|
333
|
+
this.queryableStorage = new QueryableStorage({ ctx });
|
|
334
|
+
this.batcher = new OperationBatcher({
|
|
335
|
+
ctx,
|
|
336
|
+
meta,
|
|
337
|
+
entities: this,
|
|
472
338
|
});
|
|
473
|
-
|
|
339
|
+
}
|
|
340
|
+
// expose batch APIs
|
|
341
|
+
get batch() {
|
|
342
|
+
return this.batcher.batch;
|
|
343
|
+
}
|
|
344
|
+
get flushAllBatches() {
|
|
345
|
+
return this.batcher.flushAll;
|
|
474
346
|
}
|
|
475
347
|
}
|
|
476
348
|
//# sourceMappingURL=EntityStore.js.map
|