@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.
Files changed (134) hide show
  1. package/dist/bundle/index.js +1 -1
  2. package/dist/bundle/index.js.map +4 -4
  3. package/dist/cjs/DocumentManager.d.ts +5 -6
  4. package/dist/cjs/DocumentManager.js +2 -2
  5. package/dist/cjs/DocumentManager.js.map +1 -1
  6. package/dist/cjs/client/Client.d.ts +3 -2
  7. package/dist/cjs/client/Client.js +1 -1
  8. package/dist/cjs/client/Client.js.map +1 -1
  9. package/dist/cjs/entities/Entity.d.ts +106 -171
  10. package/dist/cjs/entities/Entity.js +558 -383
  11. package/dist/cjs/entities/Entity.js.map +1 -1
  12. package/dist/cjs/entities/Entity.test.js.map +1 -0
  13. package/dist/cjs/entities/{2/EntityCache.d.ts → EntityCache.d.ts} +1 -1
  14. package/dist/cjs/entities/{2/EntityCache.js → EntityCache.js} +1 -1
  15. package/dist/cjs/entities/EntityCache.js.map +1 -0
  16. package/dist/{esm/entities/2 → cjs/entities}/EntityMetadata.d.ts +1 -1
  17. package/dist/cjs/entities/EntityMetadata.js.map +1 -0
  18. package/dist/cjs/entities/EntityStore.d.ts +63 -68
  19. package/dist/cjs/entities/EntityStore.js +296 -424
  20. package/dist/cjs/entities/EntityStore.js.map +1 -1
  21. package/dist/{esm/entities/2 → cjs/entities}/OperationBatcher.d.ts +2 -2
  22. package/dist/cjs/entities/OperationBatcher.js.map +1 -0
  23. package/dist/cjs/entities/{2/types.js.map → types.js.map} +1 -1
  24. package/dist/cjs/files/EntityFile.d.ts +5 -4
  25. package/dist/cjs/files/EntityFile.js.map +1 -1
  26. package/dist/cjs/index.d.ts +3 -3
  27. package/dist/cjs/index.js +1 -1
  28. package/dist/cjs/index.js.map +1 -1
  29. package/dist/cjs/queries/BaseQuery.js +1 -1
  30. package/dist/cjs/queries/BaseQuery.js.map +1 -1
  31. package/dist/cjs/queries/CollectionQueries.d.ts +4 -2
  32. package/dist/cjs/queries/utils.js +1 -1
  33. package/dist/cjs/queries/utils.js.map +1 -1
  34. package/dist/esm/DocumentManager.d.ts +5 -6
  35. package/dist/esm/DocumentManager.js +2 -2
  36. package/dist/esm/DocumentManager.js.map +1 -1
  37. package/dist/esm/client/Client.d.ts +3 -2
  38. package/dist/esm/client/Client.js +1 -1
  39. package/dist/esm/client/Client.js.map +1 -1
  40. package/dist/esm/entities/Entity.d.ts +106 -171
  41. package/dist/esm/entities/Entity.js +559 -383
  42. package/dist/esm/entities/Entity.js.map +1 -1
  43. package/dist/esm/entities/Entity.test.js.map +1 -0
  44. package/dist/esm/entities/{2/EntityCache.d.ts → EntityCache.d.ts} +1 -1
  45. package/dist/esm/entities/{2/EntityCache.js → EntityCache.js} +1 -1
  46. package/dist/esm/entities/EntityCache.js.map +1 -0
  47. package/dist/{cjs/entities/2 → esm/entities}/EntityMetadata.d.ts +1 -1
  48. package/dist/esm/entities/EntityMetadata.js.map +1 -0
  49. package/dist/esm/entities/EntityStore.d.ts +63 -68
  50. package/dist/esm/entities/EntityStore.js +297 -425
  51. package/dist/esm/entities/EntityStore.js.map +1 -1
  52. package/dist/{cjs/entities/2 → esm/entities}/OperationBatcher.d.ts +2 -2
  53. package/dist/esm/entities/OperationBatcher.js.map +1 -0
  54. package/dist/esm/entities/{2/types.js.map → types.js.map} +1 -1
  55. package/dist/esm/files/EntityFile.d.ts +5 -4
  56. package/dist/esm/files/EntityFile.js.map +1 -1
  57. package/dist/esm/index.d.ts +3 -3
  58. package/dist/esm/index.js +1 -1
  59. package/dist/esm/index.js.map +1 -1
  60. package/dist/esm/queries/BaseQuery.js +1 -1
  61. package/dist/esm/queries/BaseQuery.js.map +1 -1
  62. package/dist/esm/queries/CollectionQueries.d.ts +4 -2
  63. package/dist/esm/queries/utils.js +1 -1
  64. package/dist/esm/queries/utils.js.map +1 -1
  65. package/dist/tsconfig-cjs.tsbuildinfo +1 -1
  66. package/dist/tsconfig.tsbuildinfo +1 -1
  67. package/package.json +2 -2
  68. package/src/DocumentManager.ts +7 -3
  69. package/src/__tests__/batching.test.ts +1 -1
  70. package/src/client/Client.ts +1 -1
  71. package/src/entities/{2/Entity.test.ts → Entity.test.ts} +2 -2
  72. package/src/entities/{2/Entity.ts → Entity.ts} +4 -4
  73. package/src/entities/{2/EntityCache.ts → EntityCache.ts} +1 -1
  74. package/src/entities/{2/EntityMetadata.ts → EntityMetadata.ts} +1 -1
  75. package/src/entities/{2/EntityStore.ts → EntityStore.ts} +12 -8
  76. package/src/entities/{2/OperationBatcher.ts → OperationBatcher.ts} +2 -2
  77. package/src/files/EntityFile.ts +6 -1
  78. package/src/index.ts +3 -3
  79. package/src/queries/BaseQuery.ts +1 -1
  80. package/src/queries/CollectionQueries.ts +2 -2
  81. package/src/queries/utils.ts +1 -1
  82. package/dist/cjs/entities/2/Entity.d.ts +0 -148
  83. package/dist/cjs/entities/2/Entity.js +0 -711
  84. package/dist/cjs/entities/2/Entity.js.map +0 -1
  85. package/dist/cjs/entities/2/Entity.test.js.map +0 -1
  86. package/dist/cjs/entities/2/EntityCache.js.map +0 -1
  87. package/dist/cjs/entities/2/EntityMetadata.js.map +0 -1
  88. package/dist/cjs/entities/2/EntityStore.d.ts +0 -78
  89. package/dist/cjs/entities/2/EntityStore.js +0 -352
  90. package/dist/cjs/entities/2/EntityStore.js.map +0 -1
  91. package/dist/cjs/entities/2/OperationBatcher.js.map +0 -1
  92. package/dist/cjs/entities/DocumentFamiliyCache.d.ts +0 -96
  93. package/dist/cjs/entities/DocumentFamiliyCache.js +0 -287
  94. package/dist/cjs/entities/DocumentFamiliyCache.js.map +0 -1
  95. package/dist/cjs/entities/FakeWeakRef.d.ts +0 -11
  96. package/dist/cjs/entities/FakeWeakRef.js +0 -19
  97. package/dist/cjs/entities/FakeWeakRef.js.map +0 -1
  98. package/dist/cjs/indexes.d.ts +0 -3
  99. package/dist/cjs/indexes.js +0 -20
  100. package/dist/cjs/indexes.js.map +0 -1
  101. package/dist/esm/entities/2/Entity.d.ts +0 -148
  102. package/dist/esm/entities/2/Entity.js +0 -707
  103. package/dist/esm/entities/2/Entity.js.map +0 -1
  104. package/dist/esm/entities/2/Entity.test.js.map +0 -1
  105. package/dist/esm/entities/2/EntityCache.js.map +0 -1
  106. package/dist/esm/entities/2/EntityMetadata.js.map +0 -1
  107. package/dist/esm/entities/2/EntityStore.d.ts +0 -78
  108. package/dist/esm/entities/2/EntityStore.js +0 -348
  109. package/dist/esm/entities/2/EntityStore.js.map +0 -1
  110. package/dist/esm/entities/2/OperationBatcher.js.map +0 -1
  111. package/dist/esm/entities/DocumentFamiliyCache.d.ts +0 -96
  112. package/dist/esm/entities/DocumentFamiliyCache.js +0 -283
  113. package/dist/esm/entities/DocumentFamiliyCache.js.map +0 -1
  114. package/dist/esm/entities/FakeWeakRef.d.ts +0 -11
  115. package/dist/esm/entities/FakeWeakRef.js +0 -15
  116. package/dist/esm/entities/FakeWeakRef.js.map +0 -1
  117. package/dist/esm/indexes.d.ts +0 -3
  118. package/dist/esm/indexes.js +0 -15
  119. package/dist/esm/indexes.js.map +0 -1
  120. package/src/entities/2/NOTES.md +0 -22
  121. package/src/entities/design.tldr +0 -808
  122. /package/dist/cjs/entities/{2/Entity.test.d.ts → Entity.test.d.ts} +0 -0
  123. /package/dist/cjs/entities/{2/Entity.test.js → Entity.test.js} +0 -0
  124. /package/dist/cjs/entities/{2/EntityMetadata.js → EntityMetadata.js} +0 -0
  125. /package/dist/cjs/entities/{2/OperationBatcher.js → OperationBatcher.js} +0 -0
  126. /package/dist/cjs/entities/{2/types.d.ts → types.d.ts} +0 -0
  127. /package/dist/cjs/entities/{2/types.js → types.js} +0 -0
  128. /package/dist/esm/entities/{2/Entity.test.d.ts → Entity.test.d.ts} +0 -0
  129. /package/dist/esm/entities/{2/Entity.test.js → Entity.test.js} +0 -0
  130. /package/dist/esm/entities/{2/EntityMetadata.js → EntityMetadata.js} +0 -0
  131. /package/dist/esm/entities/{2/OperationBatcher.js → OperationBatcher.js} +0 -0
  132. /package/dist/esm/entities/{2/types.d.ts → types.d.ts} +0 -0
  133. /package/dist/esm/entities/{2/types.js → types.js} +0 -0
  134. /package/src/entities/{2/types.ts → types.ts} +0 -0
@@ -1,476 +1,348 @@
1
- import { assert, assignOid, Batcher, decomposeOid, generateId, getIndexValues, getOidRoot, getUndoOperations, groupBaselinesByRootOid, groupPatchesByIdentifier, groupPatchesByRootOid, removeOidsFromAllSubObjects, } from '@verdant-web/common';
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
- import { storeRequestPromise } from '../idb.js';
4
- import { DocumentFamilyCache } from './DocumentFamiliyCache.js';
5
- const DEFAULT_BATCH_KEY = '@@default';
6
- export class EntityStore {
7
- get log() {
8
- return this.context.log;
9
- }
10
- get db() {
11
- return this.context.documentDb;
12
- }
13
- get undoHistory() {
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.getDocumentSchema = (oid) => {
28
- const { collection } = decomposeOid(oid);
29
- if (!this.schema.collections[collection]) {
30
- this.log('warn', `Missing schema for collection: ${collection}`);
31
- return { schema: null, readonlyKeys: [] };
32
- }
33
- const schema = this.schema.collections[collection];
34
- return {
35
- readonlyKeys: [schema.primaryKey],
36
- schema: {
37
- type: 'object',
38
- properties: schema.fields,
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
- // metadata must be loaded from database to initialize family cache
49
- const transaction = this.meta.createTransaction([
50
- 'baselines',
51
- 'operations',
52
- ]);
53
- const baselines = [];
54
- const operations = [];
55
- await Promise.all([
56
- this.meta.baselines.iterateOverAllForDocument(familyCache.oid, (baseline) => {
57
- baselines.push(baseline);
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 familyCache.initializedPromise;
105
- return familyCache;
106
- };
107
- this.onEntityChange = async (oid) => {
108
- // queueMicrotask(() => this.writeDocumentToStorage(oid));
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.writeDocumentToStorage = async (oid) => {
111
- if (this._disposed) {
112
- this.log('warn', 'EntityStore is disposed, not writing to storage');
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
- const rootOid = getOidRoot(oid);
116
- const { id, collection } = decomposeOid(rootOid);
117
- const entity = await this.get(rootOid);
118
- if (this._disposed) {
119
- this.log('warn', 'EntityStore is disposed, not writing to storage');
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 snapshot = entity === null || entity === void 0 ? void 0 : entity.getSnapshot();
123
- if (snapshot) {
124
- const stored = getIndexValues(this.schema.collections[collection], snapshot);
125
- try {
126
- const tx = this.db.transaction(collection, 'readwrite');
127
- const store = tx.objectStore(collection);
128
- await storeRequestPromise(store.put(stored));
129
- this.log('info', '📝', 'wrote', collection, id, 'to storage', stored);
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
- catch (err) {
132
- // if the document can't be written, something's very wrong :(
133
- // log the error and move on...
134
- this.log("⚠️ CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues", '\n', 'Invalid data:', JSON.stringify(stored));
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
- else {
138
- const tx = this.db.transaction(collection, 'readwrite');
139
- const store = tx.objectStore(collection);
140
- await storeRequestPromise(store.delete(id));
141
- this.log('info', '❌', 'deleted', collection, id, 'from storage');
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
- this.get = async (oid) => {
145
- const familyCache = await this.openFamilyCache(oid);
146
- const { schema, readonlyKeys } = this.getDocumentSchema(oid);
147
- if (!schema) {
148
- return null;
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
- * Advanced usage!
154
- * Immediately returns an entity if it exists in the memory cache. An
155
- * entity would be cached if it has been retrieved by a live query.
156
- */
157
- this.getCached = (oid) => {
158
- const cache = this.documentFamilyCaches.get(oid);
159
- if (cache) {
160
- const { schema, readonlyKeys } = this.getDocumentSchema(oid);
161
- if (!schema) {
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
- return cache.getEntity({ oid, fieldSchema: schema, readonlyKeys });
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 document and returns an Entity for it. The created
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, options) => {
173
- // remove all OID associations from initial data
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
- // first grab any file and replace them with refs
207
+ // grab files and replace them with refs
176
208
  const processed = processValueFiles(initial, this.files.add);
177
209
  assignOid(processed, oid);
178
- const operations = this.meta.patchCreator.createInitialize(processed, oid);
179
- const familyCache = await this.openFamilyCache(oid);
180
- familyCache.insertLocalOperations(operations);
181
- // don't enqueue these, submit as distinct operation.
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
- return familyCache.getEntity({ oid, fieldSchema: schema, readonlyKeys });
191
- };
192
- this.addOperationsToOpenCaches = async (operations, info) => {
193
- const operationsByOid = groupPatchesByRootOid(operations);
194
- const oids = Object.keys(operationsByOid);
195
- oids.forEach((oid) => {
196
- const familyCache = this.documentFamilyCaches.get(oid);
197
- if (familyCache) {
198
- this.log('adding', info.confirmed ? 'confirmed' : 'unconfirmed', 'operations to cache', oid, operationsByOid[oid].length);
199
- if (info.isLocal) {
200
- familyCache.insertLocalOperations(operationsByOid[oid]);
201
- }
202
- else {
203
- familyCache.insertOperations(operationsByOid[oid], info);
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.addBaselinesToOpenCaches = async (baselines, info) => {
209
- const baselinesByOid = groupBaselinesByRootOid(baselines);
210
- const oids = Object.keys(baselinesByOid);
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
- const cache = this.documentFamilyCaches.get(oid);
213
- if (cache) {
214
- this.log('adding', 'baselines to cache', oid, baselinesByOid[oid].length);
215
- cache.insertBaselines(baselinesByOid[oid], info);
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.addDataToOpenCaches = ({ baselines, operations, reset, isLocal, }) => {
220
- var _a, _b, _c, _d;
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.addData = async ({ operations, baselines, reset, }) => {
242
- if (this._disposed) {
243
- this.log('warn', 'EntityStore is disposed, not adding data');
244
- return;
245
- }
246
- // convert operations to tagged operations with confirmed = false
247
- // while we process and store them. this is in-place so as to
248
- // not allocate a bunch of objects...
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
- // notify active queries
284
- const affectedCollections = Array.from(new Set(allDocumentOids.map((oid) => decomposeOid(oid).collection)));
285
- this.context.log('changes to collections', affectedCollections);
286
- this.context.entityEvents.emit('collectionsChanged', affectedCollections);
287
- };
288
- this.addLocalOperations = async (operations) => {
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
- * @deprecated use `batch` instead
276
+ * Constructs an entity from an OID, but does not load it.
337
277
  */
338
- this.flushPatches = async () => {
339
- await this.operationBatcher.flush(this.currentBatchKey);
340
- };
341
- this.flushAllBatches = async () => {
342
- await Promise.all(this.operationBatcher.flushAll());
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
- for (const cache of this.documentFamilyCaches.values()) {
437
- cache.dispose();
284
+ if (this.disposed) {
285
+ throw new Error('Cannot hydrate entity after store has been disposed');
438
286
  }
439
- this.documentFamilyCaches.clear();
440
- await this.flushAllBatches();
441
- };
442
- this.handleRebase = (baselines) => {
443
- this.log('debug', 'Reacting to rebases', baselines.length);
444
- // update any open caches with new baseline. this will automatically
445
- // drop operations before the baseline.
446
- this.addBaselinesToOpenCaches(baselines, { isLocal: true });
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.resetStoredDocuments = async () => {
449
- const tx = this.db.transaction(Object.keys(this.schema.collections), 'readwrite');
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
- this.refreshAllCaches = async (dropUnconfirmed = false, dropAll = false) => {
456
- for (const [_, cache] of this.documentFamilyCaches) {
457
- await this.refreshFamilyCache(cache, dropUnconfirmed, dropAll);
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.context = context;
461
- this.defaultBatchTimeout = batchTimeout;
330
+ this.ctx = ctx;
462
331
  this.meta = meta;
463
332
  this.files = files;
464
- this.operationBatcher = new Batcher(this.flushOperations);
465
- // initialize default batch
466
- this.operationBatcher.add({
467
- key: DEFAULT_BATCH_KEY,
468
- items: [],
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
- this.unsubscribes.push(this.meta.subscribe('rebase', this.handleRebase));
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